模块介绍
logger
是基于 zap
日志包进行封装的。
方法说明
方法 |
说明 |
logger.NewJSONLogger(opts …Option) |
实例化 JSON 类型的 zap logger |
logger.NewMeta(key string, value interface{}) |
创建 Meta 标签 |
logger.WrapMeta(err error, metas …Meta) |
包装多个Meta 标签 |
配置说明
配置项 |
配置方法 |
设置 Debug 日志级别 |
logger.WithDebugLevel() |
设置 Info 日志级别(默认) |
logger.WithInfoLevel() |
设置 Warn 日志级别 |
logger.WithWarnLevel() |
设置 Error 日志级别 |
logger.WithErrorLevel() |
设置关闭日志输出到控制台 |
logger.WithDisableConsole() |
设置日志字段(key => value) |
logger.WithField(key, value string) |
设置日志输出到文件 |
logger.WithFileP(file string) |
设置日志输出到文件(滚动形式) |
logger.WithFileRotationP(file string) |
设置日志时间格式 |
logger.WithTimeLayout(timeLayout string) |
使用示例
loggers, err := logger.NewJSONLogger(
logger.WithInfoLevel(),
logger.WithField("domain", configs.ProjectName()),
logger.WithTimeLayout("2006-01-02 15:04:05"),
logger.WithFileP(fmt.Sprintf("./logs/%s-access.log", configs.ProjectName())),
)
测试用例
func TestJSONLogger(t *testing.T) {
logger, err := NewJSONLogger(
WithInfoLevel(),
WithField("defined_key", "defined_value"),
)
if err != nil {
t.Fatal(err)
}
defer logger.Sync()
err = errors.New("pkg error")
logger.Error("err occurs", WrapMeta(nil, NewMeta("para1", "value1"), NewMeta("para2", "value2"))...)
logger.Error("err occurs", WrapMeta(err, NewMeta("para1", "value1"), NewMeta("para2", "value2"))...)
}
// 输出
=== RUN TestJSONLogger
{"level":"error","time":"2021-01-30T15:51:50+08:00","caller":"logger/logger_test.go:20","msg":"err occurs","defined_key":"defined_value","meta":{"para1":"value1","para2":"value2"}}
{"level":"error","time":"2021-01-30T15:51:50+08:00","caller":"logger/logger_test.go:21","msg":"err occurs","defined_key":"defined_value","error":"pkg error","errorVerbose":"pkg error\ngithub.com/xinliangnote/go-gin-api/pkg/logger.TestJSONLogger\n\t/Users/xinliangnote/github/go-gin-api/pkg/logger/logger_test.go:19\ntesting.tRunner\n\t/usr/local/go/src/testing/testing.go:1108\nruntime.goexit\n\t/usr/local/go/src/runtime/asm_amd64.s:1374","meta":{"para1":"value1","para2":"value2"}}
--- PASS: TestJSONLogger (0.00s)
PASS
基准测试
func BenchmarkJsonLogger(b *testing.B) {
b.ResetTimer()
logger, err := NewJSONLogger(
WithField("defined_key", "defined_value"),
)
if err != nil {
b.Fatal(err)
}
defer logger.Sync()
}
// 输出
goos: darwin
goarch: amd64
pkg: github.com/xinliangnote/go-gin-api/pkg/logger
BenchmarkJsonLogger
BenchmarkJsonLogger-12 1000000000 0.000096 ns/op
PASS