GO Log統(tǒng)一接口

一、問題

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容