日志处理类

master
flyfish 2020-07-23 17:52:13 +08:00
parent 36542fc159
commit 773b3bb783
5 changed files with 186 additions and 27 deletions

11
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,11 @@
{
"gopls": {
"usePlaceholders": true,
"completeUnimported": true
},
"go.gopath": "D:/project/golang",
"go.goroot": "C:/GO",
"go.gotoSymbol.includeImports": true,
"go.inferGopath": true,
"go.gotoSymbol.includeGoroot": true,
}

145
logs/logs.go Normal file
View File

@ -0,0 +1,145 @@
package logs
import (
"fmt"
"os"
"runtime"
"time"
)
const (
LOG_ERROR = iota
LOG_WARING
LOG_INFO
LOG_DEBUG
)
var log *mylog
/*
*
*/
func init() {
log = newMylog()
}
func Init(dir string, file string, level int, savefile bool) {
log.setDir(dir)
log.setFile(file)
log.setLevel(level)
log.setSavefile(savefile)
}
func Error(err ...interface{}) {
log.write(LOG_ERROR, fmt.Sprint(err...))
}
func Waring(war ...interface{}) {
log.write(LOG_WARING, fmt.Sprint(war...))
}
func SetLevel(level int) {
log.setLevel(level)
}
func Info(info ...interface{}) {
log.write(LOG_INFO, fmt.Sprint(info...))
}
func Debug(deb ...interface{}) {
log.write(LOG_DEBUG, fmt.Sprint(deb...))
}
/*
*
*/
type mylog struct {
log chan string // 日志chan
dir string // 日志存放目录
file string // 日志文件名
savefile bool // 是否保存到文件
level int // 日志级别
saveTime time.Time // 上次保存时间
}
func newMylog() *mylog {
log := &mylog{}
log.log = make(chan string, 100)
log.dir = "/opt/logs"
log.file = "out"
log.savefile = false
go log.run()
return log
}
func (l *mylog) setDir(dir string) {
l.dir = dir
}
func (l *mylog) setFile(file string) {
l.file = file
}
func (l *mylog) setSavefile(b bool) {
l.savefile = b
}
func (l *mylog) setLevel(level int) {
l.level = level
}
func (l *mylog) getLevelString(level int) string {
switch level {
case LOG_ERROR:
return "ERROR"
case LOG_WARING:
return "WARING"
case LOG_INFO:
return "INFO"
case LOG_DEBUG:
return "DEBUG"
}
return "unknown"
}
func (l *mylog) write(level int, str string) {
// 判断级别
if level > l.level {
return
}
// 输出日志
pc, _, line, _ := runtime.Caller(2)
p := runtime.FuncForPC(pc)
t := time.Now()
str = fmt.Sprintf("[%04d-%02d-%02d %02d:%02d:%02d] [%s] %s(%d): %s\n",
t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(),
l.getLevelString(level), p.Name(), line, str)
// 输出到控制台
if false == l.savefile {
fmt.Print(str)
return
}
// 输出到文件
l.log <- str
}
func (l *mylog) run() {
for {
str := <-l.log
// 判断文件夹是否存在
_, err := os.Stat(l.dir)
if nil != err {
os.MkdirAll(l.dir, os.ModePerm)
}
// 获取时间
t := time.Now()
path := fmt.Sprintf("%s/%s-%04d-%02d-%02d.log", l.dir, l.file,
t.Year(), t.Month(), t.Day())
fp, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, os.ModePerm)
if nil == err {
fp.WriteString(str)
fp.Close()
}
}
}

View File

@ -36,6 +36,7 @@ func HttpPut(url string,ct string,dat []byte,timeout time.Duration) ([]byte,erro
body, er := ioutil.ReadAll(res.Body) body, er := ioutil.ReadAll(res.Body)
return body,er return body,er
} }
func HttpPost(url string,ct string,headers map[string] string, dat []byte,timeout time.Duration) ([]byte,error) { func HttpPost(url string,ct string,headers map[string] string, dat []byte,timeout time.Duration) ([]byte,error) {
req, _ := http.NewRequest("POST", url, bytes.NewReader(dat)) req, _ := http.NewRequest("POST", url, bytes.NewReader(dat))
req.Header.Add("Content-Type", ct) req.Header.Add("Content-Type", ct)

View File

@ -1,14 +1,14 @@
package go_utils package utils
import ( import (
"reflect"
"strings"
"encoding/json" "encoding/json"
"log" "log"
"reflect"
"strings"
) )
// 驼峰转蛇形 // 驼峰转蛇形
func ToSnakeString(s string) string { func ToSnakeString(s string) string {
data := make([]byte, 0, len(s)*2) data := make([]byte, 0, len(s)*2)
j := false j := false
num := len(s) num := len(s)
@ -23,6 +23,7 @@ import (
data = append(data, d) data = append(data, d)
} }
return strings.ToLower(string(data[:])) return strings.ToLower(string(data[:]))
} }
// 蛇形转驼峰 // 蛇形转驼峰
@ -50,32 +51,31 @@ func ToCamelString(s string) string {
return string(data[:]) return string(data[:])
} }
//递归的语义化分析 //递归的语义化分析
// todo 目前只做单层,以后支持多层 // todo 目前只做单层,以后支持多层
func GetStructCodeFromJson(s string,structName string) string { func GetStructCodeFromJson(s string, structName string) string {
gencode := "type " + structName + " struct {\r\n" gencode := "type " + structName + " struct {\r\n"
dat := map[string]interface{}{} dat := map[string]interface{}{}
e := json.Unmarshal([]byte(s),&dat) e := json.Unmarshal([]byte(s), &dat)
if nil != e{ if nil != e {
log.Print(e.Error()) log.Print(e.Error())
return "" return ""
} }
for k,v := range dat{ for k, v := range dat {
log.Print(k , " ",reflect.TypeOf(v).Kind().String()) log.Print(k, " ", reflect.TypeOf(v).Kind().String())
//如果是切片,切片类型 //如果是切片,切片类型
if reflect.TypeOf(v).Kind() == reflect.Slice{ if reflect.TypeOf(v).Kind() == reflect.Slice {
gencode += " " + ToCamelString(k) + " " + reflect.TypeOf(v).Kind().String() + " `json:\"" + k + "\"` \r\n" gencode += " " + ToCamelString(k) + " " + reflect.TypeOf(v).Kind().String() + " `json:\"" + k + "\"` \r\n"
log.Print(reflect.ValueOf(v).Slice(0,0).Kind()) log.Print(reflect.ValueOf(v).Slice(0, 0).Kind())
//reflect.ValueOf(v).Slice(0,1) //reflect.ValueOf(v).Slice(0,1)
// todo 先暂时用interface代替 // todo 先暂时用interface代替
continue continue
} }
// 如果是字典 // 如果是字典
if reflect.TypeOf(v).Kind() == reflect.Map{ if reflect.TypeOf(v).Kind() == reflect.Map {
gencode += " " + ToCamelString(k) + " map[string]interface{} " + " `json:\"" + k + "\"` \r\n" gencode += " " + ToCamelString(k) + " map[string]interface{} " + " `json:\"" + k + "\"` \r\n"
for _ ,v := range reflect.ValueOf(v).MapKeys(){ for _, v := range reflect.ValueOf(v).MapKeys() {
log.Print(v) log.Print(v)
} }
continue continue

View File

@ -9,28 +9,30 @@ import (
// GetMd5ToLow Md5加密小写 // GetMd5ToLow Md5加密小写
func GetMd5ToLow(str string) string { func GetMd5ToLow(str string) string {
m := md5.New() m := md5.New()
m.Write([]byte(str)) m.Write([]byte(str))
result := hex.EncodeToString(m.Sum(nil)) result := hex.EncodeToString(m.Sum(nil))
result = strings.ToLower(result) result = strings.ToLower(result)
return result return result
} }
// InArrary 是否在数组 // InArrary 是否在数组
func InArrary(arr interface{},ele interface{}) int{ func InArrary(arr interface{}, ele interface{}) int {
if reflect.TypeOf(arr).Kind() != reflect.Slice && reflect.TypeOf(arr).Kind() != reflect.Array{ if reflect.TypeOf(arr).Kind() != reflect.Slice && reflect.TypeOf(arr).Kind() != reflect.Array {
return -1 return -1
} }
//数组为空 //数组为空
if reflect.ValueOf(arr).Len() == 0{ if reflect.ValueOf(arr).Len() == 0 {
return 1 return 1
} }
// 数组和元素不一致 // 数组和元素不一致
if reflect.ValueOf(arr).Index(0).Type().Kind() != reflect.TypeOf(ele).Kind() { if reflect.ValueOf(arr).Index(0).Type().Kind() != reflect.TypeOf(ele).Kind() {
return 1 return 1
} }
for i := 0; i < reflect.ValueOf(arr).Len();i ++ { for i := 0; i < reflect.ValueOf(arr).Len(); i++ {
if reflect.ValueOf(arr).Index(i).Interface() == if reflect.ValueOf(arr).Index(i).Interface() ==
reflect.ValueOf(ele).Interface(){ reflect.ValueOf(ele).Interface() {
return 0 return 0
} }
} }