本文主要研究一下golang的zap的

zap@/
var(__globalL=NewNop()_globalS=_())//LreturnstheglobalLogger,whichcanbereconfiguredwithReplaceGlobals.//It'()*Logger{_()l:=_globalL_()returnl}//SreturnstheglobalSugaredLogger,whichcanbereconfiguredwith//'()*SugaredLogger{_()s:=_globalS_()returns}//ReplaceGlobalsreplacestheglobalLoggerandSugaredLogger,andreturnsa//'(logger*Logger)func(){_()prev:=_globalL_globalL=logger_globalS=()_()returnfunc(){ReplaceGlobals(prev)}}StdLogzap@/
//NewStdLogreturnsa*//'spackage-globallogging//functions,(l*Logger)*{logger:=(AddCallerSkip(_stdLogDefaultDepth+_loggerWriterDepth))f:=(loggerWriter{f},""/*prefix*/,0/*flags*/)}//NewStdLogAtreturns*//(l*Logger,)(*,error){logger:=(AddCallerSkip(_stdLogDefaultDepth+_loggerWriterDepth))logFunc,err:=levelToFunc(logger,level)iferr!=nil{returnnil,err}(loggerWriter{logFunc},""/*prefix*/,0/*flags*/),nil}funclevelToFunc(logger*Logger,)(func(string,Field),error){switchlvl{caseDebugLevel:,nilcaseInfoLevel:,nilcaseWarnLevel:,nilcaseErrorLevel:,nilcaseDPanicLevel:,nilcasePanicLevel:,nilcaseFatalLevel:,nil}returnnil,("unrecognizedlevel:%q",lvl)}typeloggerWriterstruct{logFuncfunc(msgstring,fieldsField)}func(l*loggerWriter)Write(p[]byte)(int,error){p=(p)(string(p))returnlen(p),nil}RedirectStdLog//RedirectStdLogredirectsoutputfromthestandardlibrary'spackage-global////annotations,timestamps,etc.,itautomaticallydisablesthestandard//library'sannotationsandprefixing.////Itreturnsafunctiontorestoretheoriginalprefixandflagsandresetthe//standardlibrary'(l*Logger)func(){f,err:=redirectStdLogAt(l,InfoLevel)iferr!=nil{//Can'tgethere,sincepassingInfoLeveltoredirectStdLogAtalways//((_programmerErrorTemplate,err))}returnf}//RedirectStdLogAtredirectsoutputfromthestandardlibrary'spackage-global////handlescallerannotations,timestamps,etc.,itautomaticallydisablesthe//standardlibrary'sannotationsandprefixing.////Itreturnsafunctiontorestoretheoriginalprefixandflagsandresetthe//standardlibrary'(l*Logger,)(func(),error){returnredirectStdLogAt(l,level)}funcredirectStdLogAt(l*Logger,)(func(),error){flags:=()prefix:=()(0)("")logger:=(AddCallerSkip(_stdLogDefaultDepth+_loggerWriterDepth))logFunc,err:=levelToFunc(logger,level)iferr!=nil{returnnil,err}(loggerWriter{logFunc})returnfunc(){(flags)(prefix)()},nil}实例funcglobalDemo(){logger,_:=()()//flushesbuffer,(logger)().Info("hello")stdLog:=(logger)("thisisstandardloggerbutlogwithoutputtozaplogger")undo:=(logger)("")undo()("standardlogwithoriginaloutput")}输出
{"level":"info","ts":1607860586.171433,"caller":"zap/zap_:23","msg":"hello"}{"level":"info","ts":1607860586.171505,"caller":"zap/zap_:26","msg":"thisisstandardloggerbutlogwithoutputtozaplogger"}{"level":"info","ts":1607860586.1715178,"caller":"zap/zap_:29","msg":""}2020/12/1319:56:26standardlogwithoriginaloutput小结提供了ReplaceGlobals方法用于注册全局的单例的logger;提供了NewStdLog方法用于返回标准库的,然后使用该logger的输出都会通过来输出;提供了RedirectStdLog方法用于改变全局的标准库的log的输出,将其通过来输出,该方法返回一个func来撤销这种重定向。
doczap