1.kratos
Log:
type Logger interface { Log(level Level, keyvals ...interface{}) error } type logger struct { logger Logger prefix []interface{} hasValuer bool ctx context.Context }
kratos抽象了Logger接口,通过调Logger的Log方法来打印日志
l := log.DefaultLogger _ = l.Log(log.LevelInfo, "test1:", 1) // INFO test1:=1 //所以可以调用不同的日志库,只要实现了Log接口。 type Helper struct { logger Logger msgKey string } h := log.NewHelper(l) h.Info("test2:", 2) // INFO msg=test2:2
可以通过NewHelper()方法来传入Logger
Helper用来帮助简写代码,省略了一些日志等级,用Info,Debug等方法输出日志。
with:
l := log.DefaultLogger logger := log.With(l, "time:", log.DefaultTimestamp) h := log.NewHelper(logger) h.Info("test2:", 2) // INFO time:=2023-03-23T16:26:25+08:00 msg=test2:2
kratos日志 还有日志过滤,绑定context,全局日志等。
使用:
kratos框架建议是注入到各层初始化方法,然后通过结构体调用。
2.kitex 日志
type FullLogger interface { Logger FormatLogger CtxLogger Control }
FullLogger定义了kitex日志要实现的方法,包括了Infof,Debugf,Debug,Info,CtxDebugf,CtxInfof等等方法。
kitex在 pkg/klog 里定义了一个全局defaultLogger ,可以通过SetLogger 传入实现了FullLogger接口的结果换掉默认的logger
打印日志
import ( "github.com/cloudwego/kitex/pkg/klog" kitexlogrus "github.com/kitex-contrib/obs-opentelemetry/logging/logrus" ) func main() { klog.Info("test1:", 1) klog.SetLogger(kitexlogrus.NewLogger()) klog.SetLevel(klog.LevelDebug) klog.Info("test2:", 2) } //2023/03/23 17:34:08.368679 mytest.go:9: [Info] test1:1 //{"level":"info","msg":"test2:2","time":"2023-03-23T17:34:08+08:00"}
3.go-zero 日志
go-zero在logx包下定义了日志的一些配置
type LogConf struct { ServiceName string `json:",optional"` Mode string `json:",default=console,options=[console,file,volume]"` Encoding string `json:",default=json,options=[json,plain]"` TimeFormat string `json:",optional"` Path string `json:",default=logs"` Level string `json:",default=info,options=[info,error,severe]"` Compress bool `json:",optional"` KeepDays int `json:",optional"` StackCooldownMillis int `json:",default=100"` }
其中包括了ServiceName,Encoding,Path等
定义了日志的打印方法
type Logger interface { Debug(...any) Debugf(string, ...any) ….. Errorw(string, ...LogField) WithFields(fields ...LogField) Logger }
logx定义了两个接口,方便自定义 logx,将日志写入任何存储。
* logx.NewWriter(w io.Writer)
* logx.SetWriter(write logx.Writer)
import ( "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/zero-contrib/logx/zapx" ) func main() { logx.Error("test1:", 1) logx.Info("test2:", 2) writer, _ := zapx.NewZapWriter() logx.SetWriter(writer) logx.Info("test3:", 3) } //{"@timestamp":"2023-03-23T18:05:26.332+08:00","caller":"test/mytest.go:9","content":"test1:1","level":"error"} //{"@timestamp":"2023-03-23T18:05:26.332+08:00","caller":"test/mytest.go:10","content":"test2:2","level":"info"} //{"level":"info","ts":1679565926.332802,"caller":"test/mytest.go:14","msg":"test3:3","caller":"test/mytest.go:14"}
标签:Info,log,logx,json,go,日志,string From: https://www.cnblogs.com/gz-wod/p/17248450.html