golang log模組之log4go文件
阿新 • • 發佈:2018-11-08
介紹
這個儲存庫是從alecthomas的log4go重構而來的,log4go是一個日誌包,類似於Go程式語言的log4j。
支援兩個新特性,一個是Json配置樣式,另一個是根據類別的不同輸出。
特點
- 記錄到控制檯
- 日誌檔案,支援按大小或時間旋轉。
- 登入到網路,支援tcp和udp
- 支援xml配置
- 支援Json樣式配置
- 為日誌新增類別
- 根據不同的輸出和不同的用法對日誌進行分類。
- 相容舊的
安裝使用
首先,下載原始碼:
go get github.com/jeanphorn/log4go
匯入進工程:
import log "github.com/jeanphorn/log4go"
原始碼也可以直接從github倉庫下載使用。
使用示例
這裡使用json配置檔案,配置檔案是可選的,如果不配置,預設輸出到終端。
{
"console": {
"enable": true, // wether output the log
"level": "FINE" // log level: FINE, DEBUG, TRACE, INFO, WARNING,ERROR, CRITICAL
},
"files" : [{
"enable": true,
"level": "DEBUG",
"filename":"./test.log",
"category": "Test", // different category log to different files
"pattern": "[%D %T] [%C] [%L] (%S) %M" // log output formmat
},{
"enable": false,
"level": "DEBUG",
"filename" :"rotate_test.log",
"category": "TestRotate",
"pattern": "[%D %T] [%C] [%L] (%S) %M",
"rotate": true, // wether rotate the log
"maxsize": "500M",
"maxlines": "10K",
"daily": true
}],
"sockets": [{
"enable": false,
"level": "DEBUG",
"category": "TestSocket",
"pattern": "[%D %T] [%C] [%L] (%S) %M",
"addr": "127.0.0.1:12124",
"protocol":"udp"
}]
}
Code
package main
import (
log "github.com/jeanphorn/log4go"
)
func main() {
// load config file, it's optional
// or log.LoadConfiguration("./example.json", "json")
// config file could be json or xml
log.LoadConfiguration("./example.json")
log.LOGGER("Test").Info("category Test info test ...")
log.LOGGER("Test").Info("category Test info test message: %s", "new test msg")
log.LOGGER("Test").Debug("category Test debug test ...")
// Other category not exist, test
log.LOGGER("Other").Debug("category Other debug test ...")
// socket log test
log.LOGGER("TestSocket").Debug("category TestSocket debug test ...")
// original log4go test
log.Info("nomal info test ...")
log.Debug("nomal debug test ...")
log.Close()
}
輸出樣式
[2017/11/15 14:35:11 CST] [Test] [INFO] (main.main:15) category Test info test ...
[2017/11/15 14:35:11 CST] [Test] [INFO] (main.main:16) category Test info test message: new test msg
[2017/11/15 14:35:11 CST] [Test] [DEBG] (main.main:17) category Test debug test ...
[2017/11/15 14:35:11 CST] [DEFAULT] [INFO] (main.main:26) nomal info test ...
[2017/11/15 14:35:11 CST] [DEFAULT] [DEBG] (main.main:27) nomal debug test ...
文件
日誌等級
func (log Logger) Log(lvl Level, source, message string) {
func (log Logger) Finest(arg0 interface{}, args ...interface{}) {
func (log Logger) Fine(arg0 interface{}, args ...interface{}) {
func (log Logger) Debug(arg0 interface{}, args ...interface{}) {
func (log Logger) Trace(arg0 interface{}, args ...interface{}) {
func (log Logger) Info(arg0 interface{}, args ...interface{}) {
func (log Logger) Error(arg0 interface{}, args ...interface{}) error {
func (log Logger) Critical(arg0 interface{}, args ...interface{}) error {