1. 程式人生 > >golang log模組之log4go使用介紹

golang log模組之log4go使用介紹

1. 描述

在go語言中,自身已經集成了一定log模組,開發者可以使用go語言自身的log包(import “log”)。也有不少對自身log的開源封裝。對於一些簡單的開發,自身的log模組就已經足夠應付。但是對一些大型,複雜的開發,log需要分門別類的輸出,或者通過網路進行輸出,自身log模組將難以應對。

當前也有一些比較重量級的log模組,比如logrus,可以實現比較複雜的功能。這裡介紹一個輕量級的log模組——log4go. 源於google的一項log工程,官方已經停止維護更新,這裡對他進行了重構,使用起來也特別簡單,就像自身的log模組一樣。

2. 特點

  • 日誌輸出到終端
  • 日誌輸出到檔案,支援按大小和時間切片
  • 日誌輸出到網路
  • 日誌非同步輸出
  • 支援json檔案配置
  • 日誌分類
    • 不同類別的日誌,輸出到不同的printer中.
  • 相容老的日誌方式

使用方式

首先,下載原始碼.

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 example:

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 …

4. 感謝

Thanks alecthomas for providing the original resource.