參考:https://godoc.org/github.com/cihub/seelog
導入方式:
import "github.com/cihub/seelog"
包seelog通過靈活的調度、過濾和格式化實現日志功能。
1.創建
使用下面的構造函數來創建一個日志記錄器:
func LoggerFromConfigAsBytes
func LoggerFromConfigAsFile
func LoggerFromConfigAsString
func LoggerFromWriterWithMinLevel
func LoggerFromWriterWithMinLevelAndFormat
func LoggerFromCustomReceiver(check https://github.com/cihub/seelog/wiki/Custom-receivers)
舉例:
配置文件seelog.xml為,參考https://blog.csdn.net/luckytanggu/article/details/80345134:
<seelog type="asynctimer" asyncinterval="1000000" minlevel="debug" maxlevel="error"> <outputs formatid="main"> <!-- 僅實現將日志內容輸出到終端 --> <console/> </outputs> <formats> <!-- 設置格式,輸出UTC日期 UTC時間 - 縮寫版大寫日志級別 - 相對於應用程序運行目錄的調用者路徑 - 日志記錄器被調用時的行號 - 消息文本(最后換行) --> <format id="main" format="%UTCDate %UTCTime - [%LEV] - %RelFile - l%Line - %Msg%n"/> </formats> </seelog>
然后應用為:
package main
import (
log "github.com/cihub/seelog" "fmt" ) func main() { logger, err := log.LoggerFromConfigAsFile("seelog.xml") if err != nil { fmt.Println("parse seelog.xml error") } log.ReplaceLogger(logger) defer log.Flush() log.Info("Hello from Seelog!") }
輸出為:
userdeMBP:go-learning user$ go run test.go
2019-03-04 09:19:11 - [INF] - test.go - l20 - Hello from Seelog!
“defer”行語句很重要,因為如果使用異步日志行為,在關閉應用程序時,如果沒有這行,可能會丟失一些消息,因為它們是在另一個非阻塞goroutine中處理的。為了避免這種情況,在關閉之前顯式地延遲刷新所有消息。
2.使用
可以通過調用主日志函數其中之一的函數來直接使用上面的任一個LoggerFrom*函數來創建日志記錄器
import log "github.com/cihub/seelog" func main() { logger, err := log.LoggerFromConfigAsFile("seelog.xml") if err != nil { panic(err) } defer logger.Flush() logger.Trace("test") logger.Debugf("var = %s", "abc") }
如果你正在使用內部日志記錄編寫自己的包,或者你有幾個具有不同選項的日志記錄程序,那么使用日志記錄程序作為變量是非常方便的。但是對於大多數獨立的應用程序來說,使用包級函數和變量會更方便。有一個包級別的變量'Current'就是為它而建的(即上面的logger等價於log.Current)。你也可以使用“ReplaceLogger”將其替換為另一個日志記錄器,然后使用包級別函數:
import log "github.com/cihub/seelog" func main() { logger, err := log.LoggerFromConfigAsFile("seelog.xml") if err != nil { panic(err) } log.ReplaceLogger(logger) defer log.Flush() log.Trace("test") log.Debugf("var = %s", "abc") }
兩面的最后兩行等價於:
log.Current.Trace("test") log.Current.Debugf("var = %s", "abc")
在本例中,'Current'日志記錄器被替換為使用'ReplaceLogger'調用,並成為由config創建的'logger'變量。通過這種方式,你可以使用包級別函數,而不是傳遞logger變量。
3.配置:
1)可見go第三方日志系統-seelog-Basic sections
2)使用代碼進行配置:
雖然不建議使用代碼進行配置,但有時需要使用代碼,可以使用seelog進行配置。基本上,開始時你需要做的是創建約束、例外和分配器樹(與配置相同)。這個包中的大多數New*類函數都用於提供此類功能。
下面是代碼中的配置示例,它演示了一個異步循環日志記錄器,該記錄器使用指定的格式來使用控制台接收器將日志記錄到一個簡單的分割分配器上,並使用最高級別的min-max約束和一個對“main.go”文件的例外進行篩選。所以,這基本上是對大多數功能配置的演示:
package main import log "github.com/cihub/seelog" func main() { defer log.Flush() log.Info("Hello from Seelog!") //這個使用的是默認的日志記錄器 consoleWriter, _ := log.NewConsoleWriter() //創建一個新的控制台寫入器 formatter, _ := log.NewFormatter("%Level %Msg %File%n") //等價於配置中的<format>聲明格式 root, _ := log.NewSplitDispatcher(formatter, []interface{}{consoleWriter}) //即等價於配置中的<output>,formatter是該分配器指定的格式,接收到的日志信息指定接收器為標准輸出 constraints, _ := log.NewMinMaxConstraints(log.TraceLvl, log.CriticalLvl) //使用指定的最小和最大級別創建一個新的minMaxConstraints對象結構,即specificConstraints,指明一個范圍內的級別 specificConstraints, _ := log.NewListConstraints([]log.LogLevel{log.InfoLvl, log.ErrorLvl})//一個個指明可用的級別,這里即只能使用info和error這兩個級別 ex, _ := log.NewLogLevelException("*", "*main.go", specificConstraints) exceptions := []*log.LogLevelException{ex} //生成一個*log.LogLevelException對象列表 logger := log.NewAsyncLoopLogger(log.NewLoggerConfig(constraints, exceptions, root))//使用了這個函數就能夠生成一個完整的seelog配置了 log.ReplaceLogger(logger) //下面的內容使用的就是我們上面自定義的日志生成器了 log.Trace("This should not be seen") log.Debug("This should not be seen") log.Info("Test") log.Error("Test2") }
返回:
userdeMBP:go-learning user$ go run test.go 1551754090234813000 [Info] Hello from Seelog! Trace This should not be seen test.go Debug This should not be seen test.go Info Test test.go Error Test2 test.go
相關使用的函數:
func NewConsoleWriter
func NewConsoleWriter() (writer *consoleWriter, err error)
創建一個新的控制台寫入器。如果無法創建控制台寫入器,則返回錯誤。
func NewFormatter
func NewFormatter(formatString string) (*formatter, error)
NewFormatter使用格式字符串創建新的格式化程序,即等價於配置中的<format>聲明格式
func NewSplitDispatcher
func NewSplitDispatcher(formatter *formatter, receivers []interface{}) (*splitDispatcher, error)
聲明一個Dispatcher分配器,即等價於配置中的<Splitter>。第一個參數即指定該分配器消息輸出使用的格式,第二個參數指定的是日志的接收器,即是輸出到標准輸出,還是文件等
func NewMinMaxConstraints
func NewMinMaxConstraints(min LogLevel, max LogLevel) (*minMaxConstraints, error)
NewMinMaxConstraints使用指定的最小和最大級別創建一個新的minMaxConstraints結構。指明配置中的某個分配器中能夠輸出的日志級別的最大最小限制,這是指定一個范圍
func NewListConstraints
func NewListConstraints(allowList []LogLevel) (*listConstraints, error)
NewListConstraints使用指定的允許級別創建一個新的listConstraints結構。這是一個個指明能夠使用的級別類型
type LogLevelException
type LogLevelException struct { // contains filtered or unexported fields }
LogLevelException表示當你需要一些特定的文件或函數來覆蓋常規約束並使用它們自己的約束時使用的例外情況。即配置中的<exception>
func NewLogLevelException
func NewLogLevelException(funcPattern string, filePattern string, constraints logLevelConstraints) (*LogLevelException, error)
NewLogLevelException創建一個新的例外.第一個參數指明該例外用於的函數需要滿足的模式,第二個參數指明該例外用於的文件需要滿足的模式,第三個例外則是指明該例外的日志級別限制,可使用NewMinMaxConstraints函數和NewListConstraints函數的返回值
func NewAsyncLoopLogger
func NewAsyncLoopLogger(config *logConfig) *asyncLoopLogger
NewAsyncLoopLogger創建一個新的異步循環記錄器,聲明該seelog使用的是異步循環,即等價於配置中的<seelog type="asyncloop">。使用了這個函數就能夠生成一個完整的seelog配置了
func NewLoggerConfig
func NewLoggerConfig(c logLevelConstraints, e []*LogLevelException, d dispatcherInterface) *logConfig
生成一個日志記錄器的配置信息,用來作為NewAsyncLoopLogger函數的輸入。第一個參數是該日志記錄器的日志級別限制,可以使用NewMinMaxConstraints函數和NewListConstraints函數的返回值;第二個參數是使用的例外的例外對象列表;第三個參數是指定了格式format和輸出方式的分配器,即NewSplitDispatcher函數的返回值
4.其他函數:
1)New* 類型函數
1》指明所用的type類型,如上面的NewAsyncLoopLogger函數作用:
func NewSyncLogger
func NewSyncLogger(config *logConfig) *syncLogger
NewSyncLogger創建一個同步的日志記錄器,相當於配置中的<seelog type="sync">。第一個參數使用的是NewLoggerConfig函數的返回值,指明日志級別限制、例外和指定了格式format和輸出方式的分配器
func NewAsyncAdaptiveLogger
func NewAsyncAdaptiveLogger( config *logConfig, minInterval time.Duration, maxInterval time.Duration, criticalMsgCount uint32) (*asyncAdaptiveLogger, error)
NewAsyncLoopLogger創建一個異步適應性生成器,相當於配置中的<seelog type="adaptive" mininterval="200000000" maxinterval="1000000000" critmsgcount="5">,第一個參數使用的是NewLoggerConfig函數的返回值,指明日志級別限制、例外和指定了格式format和輸出方式的分配器;第二個和第三個參數指定計時器最小和最大時間間隔;第四個參數為關鍵消息計數
func NewAsyncTimerLogger
func NewAsyncTimerLogger(config *logConfig, interval time.Duration) (*asyncTimerLogger, error)
NewAsyncLoopLogger創建一個異步循環日志記錄器,即相當於配置中的<seelog type="asynctimer" asyncinterval="5000">,第一個參數使用的是NewLoggerConfig函數的返回值,指明日志級別限制、例外和指定了格式format和輸出方式的分配器;第二個參數指明的是計數器的時間間隔,即asyncinterval
2》接收器,即指定日志輸出的形式,如上面的NewConsoleWriter
func NewBufferedWriter
func NewBufferedWriter(innerWriter io.Writer, bufferSize int, flushPeriod time.Duration) (*bufferedWriter, error)
NewBufferedWriter創建一個新的緩沖寫入器結構,即配置中的<buffered size="10000" flushperiod="1000">。第一個參數指定在寫入內存同時寫入的文件對象;第二個參數bufferSize以字節為單位的內存緩沖區的大小,0 則表示關閉此功能;第三個參數即指定的緩沖區刷新之間的間隔
func NewConnWriter
func NewConnWriter(netName string, addr string, reconnectOnMsg bool) *connWriter
在網絡netName上創建地址addr的寫入器,相當於配置的<conn formatid="syslog" net="tcp4" addr="server.address:5514" tls="true" insecureskipverify="true" />。第一個參數指定使用的網絡類型,即對應的net;第二個參數指定網絡地址;第三個參數如果reconnectOnMsg = true,將在每次寫入時打開連接
func NewFileWriter
func NewFileWriter(fileName string) (writer *fileWriter, err error)
創建一個新文件和相應的寫入器。如果無法創建文件就會返回錯誤。相當於配置中的<file path="log.log"/>,第一個參數用於指明日志文件的名字
func NewFormattedWriter
func NewFormattedWriter(writer io.Writer, formatter *formatter) (*formattedWriter, error)
func NewRollingFileWriterSize
func NewRollingFileWriterSize(fpath string, atype rollingArchiveType, apath string, maxSize int64, maxRolls int, namemode rollingNameMode, archiveExploded bool) (*rollingFileWriterSize, error)
相當於配置中<rollingfile type="size" filename="logs/roll.log" maxsize="1000" maxrolls="5" />,type為size。第一個參數指定回滾文件的路徑;第二個參數指定存儲舊卷而不是刪除舊卷的存檔的類型,相當於archivetype;第三個參數即指定存儲舊卷的存檔的路徑,相當於archivepath;第四個參數為指定文件最大字節數;第五個參數為滾動文件的命名模式,相當於配置的namemode;第六個參數用於用於指定日志是應該被分解還是分組到同一個歸檔文件中
func NewRollingFileWriterTime
func NewRollingFileWriterTime(fpath string, atype rollingArchiveType, apath string, maxr int, timePattern string, namemode rollingNameMode, archiveExploded bool, fullName bool) (*rollingFileWriterTime, error)
相當於配置中的<rollingfile type="date" filename="logs/roll.log" datepattern="02.01.2006" maxrolls="7" />,type為date。第四個參數為指定文件中的最大行數;第五個參數指定輸出在文件中時間的格式
func NewSMTPWriter
func NewSMTPWriter(sa, sn string, ras []string, hn, hp, un, pwd string, cacdps []string, subj string, headers []string) *smtpWriter
NewSMTPWriter 返回一個新的SMTP寫入器,相當於配置中的<smtp senderaddress="noreply-notification-service@none.org" sendername="Automatic notification service" hostname="mail.none.org" hostport="587" username="nns" password="123">。sa,sn對應的就是senderaddress,sendername;ras即配置中子元素recipient的address可以有多個所以為列表,如:
<recipient address="john-smith@none.com"/> <recipient address="hans-meier@none.com"/>
hn, hp, un, pwd對應的是hostname,hostport,username,password;cacdps即子元素cacertdirpath中的path值,如<cacertdirpath path="cacdp1"/>;subj即subject-電子郵件的主題;headers即該郵件的頭消息,可以有多個值,所以為列表,如:
<header name="Priority" value="Urgent" /> <header name="Importance" value="high" />
3》分配器,如上面的NewSplitDispatcher函數
func NewFilterDispatcher
func NewFilterDispatcher(formatter *formatter, receivers []interface{}, allowList ...LogLevel) (*filterDispatcher, error)
NewFilterDispatcher使用允許的級別列表創建一個新的filterDispatcher,相當於配置中的<filter levels="trace,debug">。
下面是自定義的分配器
func NewCustomReceiverDispatcher
func NewCustomReceiverDispatcher(formatter *formatter, customReceiverName string, cArgs CustomReceiverInitArgs) (*customReceiverDispatcher, error)
NewCustomReceiverDispatcher創建一個customReceiverDispatcher,它將數據分派到配置文件中使用<custom>標記創建的特定接收器。
func NewCustomReceiverDispatcherByValue
func NewCustomReceiverDispatcherByValue(formatter *formatter, customReceiver CustomReceiver, name string, cArgs CustomReceiverInitArgs) (*customReceiverDispatcher, error)
NewCustomReceiverDispatcherByValue基本上與NewCustomReceiverDispatcher相同,但是使用特定的CustomReceiver值而不是按類型實例化一個新值
4》格式化,如上面的NewFormatter函數
5》限制,如上面的NewListConstraints和NewMinMaxConstraints
func NewOffConstraints
func NewOffConstraints() (*offConstraints, error)
“off”日志級別
“off”是一個特殊的日志級別,它意味着禁用日志記錄。它可以在minlevel和level約束中使用,因此你可以在全局約束或例外約束中寫入'minlevel= “off”'和'levels= “off”'來禁用日志。
2)常量
1》日志級別
const ( TraceLvl = iota //0 DebugLvl //1 InfoLvl WarnLvl ErrorLvl CriticalLvl Off //6 )
2》日志級別字符串表示(使用在配置文件中)
const ( TraceStr = "trace" DebugStr = "debug" InfoStr = "info" WarnStr = "warn" ErrorStr = "error" CriticalStr = "critical" OffStr = "off" )
3》使用 %Date和%Time別名表示的日期和時間的格式化
const ( DateDefaultFormat = "2006-01-02" TimeFormat = "15:04:05" )
4》FormatterSymbol是配置文件中用於標記特殊格式別名的特殊符號。
const ( FormatterSymbol = '%' )
5》MaxQueueSize是隊列中導致立即刷新的消息的關鍵數量。
const ( MaxQueueSize = 10000 )
6》發送SMTP時的默認subject
const ( // Default subject phrase for sending emails. DefaultSubjectPhrase = "Diagnostic message from server: " )
3)變量
var ( DefaultFormatter *formatter ) var DefaultMsgFormat = "%Ns [%Level] %Msg%n"
默認使用的日志消息的輸出格式 ,即時間 [日志級別] 日志消息 換行符
4)輸出日志函數
func Critical
func Critical(v ...interface{}) error
Critical使用其操作數的默認格式來格式消息,並寫入日志級別= Critical的默認日志記錄器
func Criticalf
func Criticalf(format string, params ...interface{}) error
Criticalf根據格式說明符format格式化消息,並使用日志級別 = Critical寫入默認日志記錄器
func Debug
func Debug(v ...interface{})
Debug使用其操作數的默認格式來格式化消息,並使用日志級別= Debug將消息寫入默認日志記錄器
func Debugf
func Debugf(format string, params ...interface{})
Debugf根據格式說明符格式化消息,並使用日志級別 = Debug寫入默認日志記錄器。
func Error
func Error(v ...interface{}) error
Error使用其操作數的默認格式來格式化消息,並使用日志級別= Error寫入默認日志記錄器
func Errorf
func Errorf(format string, params ...interface{}) error
Errorf根據格式說明符format來格式化消息,並使用日志級別= Error寫入默認日志記錄器
func Info
func Info(v ...interface{})
Info 信息使用其操作數的默認格式來格式化消息,並使用日志級別 = Info寫入默認日志記錄器
func Infof
func Infof(format string, params ...interface{})
Infof根據格式說明符來格式化消息,並使用日志級別= Info寫入默認日志記錄器。
func Trace
func Trace(v ...interface{})
Trace使用其操作數的默認格式來格式化消息,並使用日志級別= Trace寫入默認日志記錄器
func Tracef
func Tracef(format string, params ...interface{})
Tracef根據格式說明符來格式化消息,並使用日志級別= Trace寫入默認日志記錄器。
func Warn
func Warn(v ...interface{}) error
Warn使用其操作數的默認格式來格式化消息,並使用日志級別= Warn寫入默認日志記錄器
func Warnf
func Warnf(format string, params ...interface{}) error
Warnf根據格式說明符來格式化消息,並使用日志級別 = Warn寫入默認日志記錄器
舉例:
package main import log "github.com/cihub/seelog" func main() { testConfig := ` <seelog type="sync" minlevel="trace"> <outputs><console/></outputs> </seelog>` logger, _ := log.LoggerFromConfigAsBytes([]byte(testConfig)) log.ReplaceLogger(logger) defer log.Flush()
log.Trace("NOT Printed") log.Tracef("Returning %s", "NOT Printed") log.Debug("NOT Printed") log.Debugf("Returning %s", "NOT Printed") log.Info("Printed") log.Infof("Returning %s", "Printed") log.Warn("Printed") log.Warnf("Returning %s", "Printed") log.Error("Printed") log.Errorf("Returning %s", "Printed") log.Critical("Printed") log.Criticalf("Returning %s", "Printed") }
返回:
userdeMBP:go-learning user$ go run test.go 1551777220280758000 [Trace] NOT Printed 1551777220280819000 [Trace] Returning NOT Printed 1551777220280842000 [Debug] NOT Printed 1551777220280848000 [Debug] Returning NOT Printed 1551777220280853000 [Info] Printed 1551777220280858000 [Info] Returning Printed 1551777220280863000 [Warn] Printed 1551777220280871000 [Warn] Returning Printed 1551777220280876000 [Error] Printed 1551777220280885000 [Error] Returning Printed 1551777220280891000 [Critical] Printed 1551777220280896000 [Critical] Returning Printed
5)
func Flush
func Flush()
Flush立即處理所有當前排隊的消息和所有當前緩沖的消息。它是一個阻塞調用,僅在隊列為空且所有緩沖區為空時才返回。
如果同步日志程序調用Flush (type='sync'),它只刷新緩沖區(例如'<buffered>' 接收器),因為沒有隊列。
當你的應用程序將要關閉時,調用這個方法可以保證不丟失任何日志消息。所以一定要在最后調用該函數
func UseLogger
func UseLogger(logger LoggerInterface) error
UseLogger將 'Current'包級別的日志記錄器變量設置為指定值。此變量用於所有Trace/Debug/... 包級功能。
⚠️:UseLogger不關閉前一個日志記錄器(只刷新它)。因此,如果你經常使用它來替換日志記錄程序,而不是在其他代碼中關閉它們,那么最終將導致內存泄漏。
要安全地替換日志記錄器,請使用ReplaceLogger。
如果你調用了:
seelog.UseLogger(somelogger)
之后你再調用:
seelog.Debug("abc")
它其實久等價於:
somelogger.Debug("abc")
func ReplaceLogger
func ReplaceLogger(logger LoggerInterface) error
ReplaceLogger充當UseLogger,但是以前使用的日志記錄器會被銷毀(默認和禁用的日志記錄器除外)。
舉例:
package main import log "github.com/cihub/seelog" func main() { log.Info("Replace before Printed") //使用的是默認的格式 testConfig := ` <seelog type="sync" minlevel="info"> <outputs formatid="main"><console/></outputs> <formats> <format id="main" format="%UTCDate %UTCTime - [%LEV] - %RelFile - l%Line - %Msg%n"></format> </formats> </seelog>` logger, _ := log.LoggerFromConfigAsBytes([]byte(testConfig)) log.ReplaceLogger(logger) //替換后使用的就是上面新定義的格式了 defer log.Flush() log.Info("Replace after Printed") }
返回:
userdeMBP:go-learning user$ go run test.go 1551777876234048000 [Info] Replace before Printed 2019-03-05 09:24:36 - [INF] - test.go - l20 - Replace after Printed
6)日志級別
type LogLevel
type LogLevel uint8
日志級別類型
func LogLevelFromString
func LogLevelFromString(levelStr string) (level LogLevel, found bool)
LogLevelFromString解析字符串,如果成功就返回字符串相應的日志級別。
func (LogLevel) String
func (level LogLevel) String() string
LogLevelToString返回指定級別的seelog字符串表示形式。返回“”用於無效的日志級別。
7)日志級別例外
之前上面也講到了,即
type LogLevelException
type LogLevelException struct { // contains filtered or unexported fields }
LogLevelException表示當你需要一些特定的文件或函數來覆蓋常規約束並使用它們自己的約束時使用的例外情況。即配置中的<exception>
func NewLogLevelException
func NewLogLevelException(funcPattern string, filePattern string, constraints logLevelConstraints) (*LogLevelException, error)
NewLogLevelException創建一個新的例外.第一個參數指明該例外用於的函數需要滿足的模式,第二個參數指明該例外用於的文件需要滿足的模式,第三個例外則是指明該例外的日志級別限制,可使用NewMinMaxConstraints函數和NewListConstraints函數的返回值
然后下面是一些讀取定義的例外中的一些值的方法:
func (*LogLevelException) FilePattern
func (logLevelEx *LogLevelException) FilePattern() string
FilePattern返回例外的文件模式
對應配置中的:
<exceptions> <exception filepattern="test*" minlevel="error"/> </exceptions>
func (*LogLevelException) FuncPattern
func (logLevelEx *LogLevelException) FuncPattern() string
FuncPattern返回例外的函數模式
對應配置中的:
<exceptions> <exception funcpattern="main.testFunc" minlevel="warn"/> </exceptions>
func (*LogLevelException) IsAllowed
func (logLevelEx *LogLevelException) IsAllowed(level LogLevel) bool
如果此LogLevelException的約束是允許指定的level日志級別的,那么IsAllowed將返回true
func (*LogLevelException) MatchesContext
func (logLevelEx *LogLevelException) MatchesContext(context LogContextInterface) bool
如果上下文context匹配此LogLevelException的模式,則MatchesContext返回true
func (*LogLevelException) String
func (logLevelEx *LogLevelException) String() string
8)LoggerInterface日志記錄器接口
type LoggerInterface
type LoggerInterface interface { // Tracef formats message according to format specifier // and writes to log with level = Trace. Tracef(format string, params ...interface{}) // Debugf formats message according to format specifier // and writes to log with level = Debug. Debugf(format string, params ...interface{}) // Infof formats message according to format specifier // and writes to log with level = Info. Infof(format string, params ...interface{}) // Warnf formats message according to format specifier // and writes to log with level = Warn. Warnf(format string, params ...interface{}) error // Errorf formats message according to format specifier // and writes to log with level = Error. Errorf(format string, params ...interface{}) error // Criticalf formats message according to format specifier // and writes to log with level = Critical. Criticalf(format string, params ...interface{}) error // Trace formats message using the default formats for its operands // and writes to log with level = Trace Trace(v ...interface{}) // Debug formats message using the default formats for its operands // and writes to log with level = Debug Debug(v ...interface{}) // Info formats message using the default formats for its operands // and writes to log with level = Info Info(v ...interface{}) // Warn formats message using the default formats for its operands // and writes to log with level = Warn Warn(v ...interface{}) error // Error formats message using the default formats for its operands // and writes to log with level = Error Error(v ...interface{}) error // Critical formats message using the default formats for its operands // and writes to log with level = Critical Critical(v ...interface{}) error // Close flushes all the messages in the logger and closes it. It cannot be used after this operation. Close() // Flush flushes all the messages in the logger. Flush() // Closed returns true if the logger was previously closed. Closed() bool // SetAdditionalStackDepth sets the additional number of frames to skip by runtime.Caller // when getting function information needed to print seelog format identifiers such as %Func or %File. // // This func may be used when you wrap seelog funcs and want to print caller info of you own // wrappers instead of seelog func callers. In this case you should set depth = 1. If you then // wrap your wrapper, you should set depth = 2, etc. // // NOTE: Incorrect depth value may lead to errors in runtime.Caller evaluation or incorrect // function/file names in log files. Do not use it if you are not going to wrap seelog funcs. // You may reset the value to default using a SetAdditionalStackDepth(0) call. SetAdditionalStackDepth(depth int) error // Sets logger context that can be used in formatter funcs and custom receivers SetContext(context interface{}) // contains filtered or unexported methods }
var Current LoggerInterface
Current是用於所有包級別的便利功能(如 'Trace', 'Debug', 'Flush'等)中的日志程序。
var Default LoggerInterface
默認日志記錄器,它是由一個空配置“<seelog/>”創建的。它不是由ReplaceLogger調用關閉的。
var Disabled LoggerInterface
禁用的日志記錄器,在任何情況下都不會產生任何輸出。它既不會被ReplaceLogger調用關閉,也不會被刷新。
生成日志記錄器的幾種方法,這里只講其中幾種:
func LoggerFromConfigAsBytes
func LoggerFromConfigAsBytes(data []byte) (LoggerInterface, error)
LoggerFromConfigAsBytes使用來自字節流的配置創建一個日志記錄器。字節應該包含有效的seelog xml。
舉例:
package main
import log "github.com/cihub/seelog" func main() { log.Info("Replace before Printed") //使用的是默認的格式 testConfig := ` <seelog type="sync" minlevel="info"> <outputs formatid="main"><console/></outputs> <formats> <format id="main" format="%UTCDate %UTCTime - [%LEV] - %RelFile - l%Line - %Msg%n"></format> </formats> </seelog>` logger, _ := log.LoggerFromConfigAsBytes([]byte(testConfig)) log.ReplaceLogger(logger) //替換后使用的就是上面新定義的格式了 defer log.Flush() log.Info("Replace after Printed") }
返回:
userdeMBP:go-learning user$ go run test.go
1551777876234048000 [Info] Replace before Printed 2019-03-05 09:24:36 - [INF] - test.go - l20 - Replace after Printed
func LoggerFromConfigAsFile
func LoggerFromConfigAsFile(fileName string) (LoggerInterface, error)
LoggerFromConfigAsFile使用配置文件創建日志記錄器。文件應該包含有效的seelog xml。
舉例:
其實就是將配置信息xml寫到seelog.xml文件中:
<seelog type="sync" minlevel="info"> <outputs formatid="main"><console/></outputs> <formats> <format id="main" format="%UTCDate %UTCTime - [%LEV] - %RelFile - l%Line - %Msg%n"></format> </formats> </seelog>
然后示例為:
package main import log "github.com/cihub/seelog" func main() { log.Info("Replace before Printed") //使用的是默認的格式 logger, _ := log.LoggerFromConfigAsFile("seelog.xml") log.ReplaceLogger(logger) //替換后使用的就是上面新定義的格式了 defer log.Flush() log.Info("Replace after Printed") }
返回結果和上面類似
func LoggerFromConfigAsString
func LoggerFromConfigAsString(data string) (LoggerInterface, error)
LoggerFromConfigAsString使用配置從字符串創建一個日志記錄器。字符串應該包含有效的seelog xml。
package main import log "github.com/cihub/seelog" func main() { log.Info("Replace before Printed") //使用的是默認的格式 testConfig := ` <seelog type="sync" minlevel="info"> <outputs formatid="main"><console/></outputs> <formats> <format id="main" format="%UTCDate %UTCTime - [%LEV] - %RelFile - l%Line - %Msg%n"></format> </formats> </seelog>` logger, _ := log.LoggerFromConfigAsString(testConfig) log.ReplaceLogger(logger) //替換后使用的就是上面新定義的格式了 defer log.Flush() log.Info("Replace after Printed") }
返回結果和上面類似
其他沒寫的部分未完待續