Skip to content

Commit

Permalink
init zlog
Browse files Browse the repository at this point in the history
  • Loading branch information
miajio committed Dec 23, 2022
1 parent d6ed239 commit 393d7ea
Show file tree
Hide file tree
Showing 7 changed files with 253 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Attach to Process",
"type": "go",
"request": "attach",
"mode": "local",
"processId": 0
}
]
}
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,37 @@
# zlog
Uber based zaplog carries out simple and crude encapsulation, allowing users to quickly develop log modules

# Install
go get -u github.com/miajio/zlog

```
package zlog_test
import (
"testing"
"github.com/miajio/zlog"
)
func TestLoggerFile(t *testing.T) {
// set log param
l := zlog.Logger{
Path: "./log",
MaxSize: 256,
MaxBackups: 10,
MaxAge: 7,
Compress: false,
}
// set log level func
lv := zlog.LogMap{
"debug": zlog.DebufLevel,
"info": zlog.InfoLevel,
"error": zlog.ErrorLevel,
}
// init logger
l.Generate(lv)
// info
l.Log.Info("hello")
}
```
4 changes: 4 additions & 0 deletions doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/*
Package zlog implements a log tool called zlog.
*/
package zlog // import "github.com/miajio/zlog"
16 changes: 16 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
module github.com/miajio/zlog

go 1.18

require (
github.com/natefinch/lumberjack v2.0.0+incompatible
go.uber.org/zap v1.24.0
)

require (
github.com/BurntSushi/toml v1.2.1 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
27 changes: 27 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
github.com/BurntSushi/toml v1.2.1 h1:9F2/+DoOYIOksmaJFPw1tGFy1eDnIJXg+UHjuD8lTak=
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/natefinch/lumberjack v2.0.0+incompatible h1:4QJd3OLAMgj7ph+yZTuX13Ld4UpgHp07nNdFX7mqFfM=
github.com/natefinch/lumberjack v2.0.0+incompatible/go.mod h1:Wi9p2TTF5DG5oU+6YfsmYQpsTIOm0B1VNzQg9Mw6nPk=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60=
go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8=
gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
25 changes: 25 additions & 0 deletions model_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package zlog_test

import (
"testing"

"github.com/miajio/zlog"
)

func TestLoggerFile(t *testing.T) {
l := zlog.Logger{
Path: "./log",
MaxSize: 256,
MaxBackups: 10,
MaxAge: 7,
Compress: false,
}
lv := zlog.LogMap{
"debug": zlog.DebufLevel,
"info": zlog.InfoLevel,
"error": zlog.ErrorLevel,
}

l.Generate(lv)
l.Log.Info("hello")
}
131 changes: 131 additions & 0 deletions zlog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package zlog

import (
"os"
"strings"
"sync"
"time"

"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

// Level log level
type Level func(zapcore.Level) bool

// LogMap log level map
// map key is file name
// value is log print level func
type LogMap map[string]Level

// Logger
type Logger struct {
Path string `json:"path" toml:"toml"` // log file path
MaxSize int `json:"maxSize" toml:"maxSize"` // log file max size
MaxBackups int `json:"maxBackups" toml:"maxBackups"` // log file max backups
MaxAge int `json:"maxAge" toml:"maxAge"` // log file max save day
Compress bool `json:"compress" toml:"compress"` // log file whether to compress
logMap *LogMap // log level map
Log *zap.SugaredLogger // zap log object
mu sync.Mutex // logger init lock
}

// LoggerInterface
type LoggerInterface interface {
Generate(LogMap) // Generate logger core
Printf(...string) // Printf
}

// default log level
var (
DebufLevel = func(level zapcore.Level) bool {
return level == zap.DebugLevel
}

InfoLevel = func(level zapcore.Level) bool {
return level == zap.InfoLevel
}

ErrorLevel = func(level zapcore.Level) bool {
return level == zap.ErrorLevel
}
)

// Generate
func (log *Logger) Generate(logMap LogMap) {
if log.Log == nil {
log.mu.Lock()
defer log.mu.Unlock()
if log.Log == nil {
encoderConfig := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "log",
CallerKey: "lineNum",
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: func(t time.Time, pae zapcore.PrimitiveArrayEncoder) {
pae.AppendString(t.Format("[2006-01-02 15:04:05]"))
},
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.FullCallerEncoder,
EncodeName: zapcore.FullNameEncoder,
}

cores := make([]zapcore.Core, 0)

for fileName := range logMap {
if fileName == "" {
continue
}
// logger write
write := &lumberjack.Logger{
Filename: GetLogFilePath(log.Path, fileName),
MaxSize: log.MaxSize,
MaxBackups: log.MaxBackups,
MaxAge: log.MaxAge,
Compress: log.Compress,
}
// the log level
level := zap.LevelEnablerFunc(logMap[fileName])
// log core
core := zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.NewMultiWriteSyncer(zapcore.AddSync(write)), level)
cores = append(cores, core)
}
// append default info log level
cores = append(cores, zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout)), zap.InfoLevel))

core := zapcore.NewTee(cores...)
caller := zap.AddCaller()
development := zap.Development()

log.Log = zap.New(core, caller, development, zap.Fields()).Sugar()
}
}
}

// logFile logger file out path
func GetLogFilePath(filePath, fileName string) string {
filePath = strings.ReplaceAll(filePath, "\\", "/")
fp := strings.Split(filePath, "/")
realPath := make([]string, 0)
for i := range fp {
if fp[i] != "" {
realPath = append(realPath, fp[i])
}
}

filePath = strings.Join(realPath, "/")
if filePath == "" {
filePath = "."
}

if !strings.HasSuffix(fileName, ".log") {
fileName = strings.ReplaceAll(fileName, ".", "_")
fileName = fileName + ".log"
}
return filePath + "/" + fileName
}

0 comments on commit 393d7ea

Please sign in to comment.