一、問題
go日志庫(kù)有很多:zap、 Logrus等,它們沒有統(tǒng)一的接口。作為中間件提供方,中間件的日志怎么輸出到業(yè)務(wù)的日志文件中?
解決方式:統(tǒng)一日志接口,類似于java中的slf4j。
二、實(shí)現(xiàn)
方案一
1)統(tǒng)一接口層面
type Logger interface {
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
Fatal(args ...interface{})
Infof(format string, args ...interface{})
Info( args ...interface{})
Warnf(format string, args ...interface{})
Debugf(format string, args ...interface{})
Debug(args ...interface{})
}
2)日志實(shí)現(xiàn)橋接到接口
方案二
sofa-mons有個(gè)pkg/log/proxylog.go文件,定義了log的代理。
1)接口
func (l *proxyLogger) formatter(ctx context.Context, lvPre string, format string) string {
return logTime() + " " + lvPre + " " + traceInfo(ctx) + " " + format
}
func (l *proxyLogger) Infof(ctx context.Context, format string, args ...interface{}) {
if l.disable {
return
}
if l.level >= INFO {
s := l.formatter(ctx, InfoPre, format)
l.Printf(s, args...)
}
}
在接口層面,統(tǒng)一增加context參數(shù),方便日志打印時(shí)獲取通用參數(shù)(比如:trace信息)。
三、參考
https://medium.com/@jfeng45/go-microservice-with-clean-architecture-application-logging-b43dc5839bce