golang中的log庫

weixin_34146805發表於2018-08-13

golang中有很多優秀的第三方開源庫,比如

  • go-slog, 這個是筆者自己開源的一個簡單的日誌庫
  • logrus
  • zap
  • oklog
  • glog
  • seelog
  • zerolog
    都是很優秀的開源庫,功能也很強大,很多都支援以txt的方式輸入日誌或者json的方式輸出日誌,我簡單的試了下幾個日誌庫

1. logrus

package main

import (
    "flag"
    "fmt"
    "os"
    "path"
    "runtime"
    "strings"
    "time"

    "github.com/Sirupsen/logrus"
)

func logrus_test() {

    fmt.Printf("<<<<<<<<<logrus test>>>>>>>>>>>>>>\n")

    logrus.WithFields(logrus.Fields{
        "sb": "sbvalue",
    }).Info("A walrus appears")

    log1 := logrus.New()
    fmt.Printf("log1 level: %d\n", log1.Level)
    log1.Debug("log1 debug")
    log1.Debugf("log1 debug f, %d", 10)
    log1.Info("log1 info")
    log1.Warn("log1 warn")
    log1.Error("log1 error")
    // log1.Panic("log1 panic")

    log1.SetLevel(logrus.ErrorLevel)
    fmt.Printf("after set log1 level to errorlevel\n")
    log1.Debug("log1 debug")

    fmt.Printf("-------------test formater-------------\n")
    log1.SetLevel(logrus.DebugLevel)
    log1.Formatter = &logrus.TextFormatter{
        DisableColors:  true,
        FullTimestamp:  true,
        DisableSorting: true,
    }

    log1.Debug("log text formatter test")

    fmt.Printf("-----------json formatter-------------\n")
    log1.Formatter = &logrus.JSONFormatter{}
    log1.Debug("log json formatter test")

    fmt.Printf("-----------log to file test-----------\n")
    log2 := logrus.New()
    log2.SetLevel(logrus.DebugLevel)
    log2.Formatter = &logrus.TextFormatter{
        DisableColors:  true,
        FullTimestamp:  true,
        DisableSorting: true,
    }

    logger_name := "logrus"
    cur_time := time.Now()
    log_file_name := fmt.Sprintf("%s_%04d-%02d-%02d-%02d-%02d.txt",
        logger_name, cur_time.Year(), cur_time.Month(), cur_time.Day(), cur_time.Hour(), cur_time.Minute())
    log_file, err := os.OpenFile(log_file_name, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModeExclusive)
    if err != nil {
        fmt.Printf("try create logfile[%s] error[%s]\n", log_file_name, err.Error())
        return
    }

    defer log_file.Close()

    log2.SetOutput(log_file)

    for i := 0; i < 10; i++ {
        log2.Debugf("logrus to file test %d", i)
    }

}

使用起來很簡單,輸出樣式多樣化

2. zap

package main

import (
    "flag"
    "fmt"
    "os"
    "path"
    "runtime"
    "strings"
    "time"

    "github.com/golang/glog"
)

func zap_log_test() {
    fmt.Printf("<<<<<<<<<zap log test>>>>>>>>>>>\n")
    logger := zap.NewExample()
    defer logger.Sync()

    const url = "http://example.com"

    // In most circumstances, use the SugaredLogger. It's 4-10x faster than most
    // other structured logging packages and has a familiar, loosely-typed API.
    sugar := logger.Sugar()
    sugar.Infow("Failed to fetch URL.",
        // Structured context as loosely typed key-value pairs.
        "url", url,
        "attempt", 3,
        "backoff", time.Second,
    )
    sugar.Infof("Failed to fetch URL: %s", url)

    // In the unusual situations where every microsecond matters, use the
    // Logger. It's even faster than the SugaredLogger, but only supports
    // structured logging.
    logger.Info("Failed to fetch URL.",
        // Structured context as strongly typed fields.
        zap.String("url", url),
        zap.Int("attempt", 3),
        zap.Duration("backoff", time.Second),
    )
}

zap的效能應該只這些庫裡面最高的

3. glog

package main

import (
    "flag"
    "fmt"
    "os"
    "path"
    "runtime"
    "strings"
    "time"

    "github.com/golang/glog"
)

func glog_test() {
    fmt.Printf("<<<<<<<glog_test>>>>>>>>>>\n")
    flag.Parse()

    defer glog.Flush()

    glog.Info("glog info test")
    glog.Warning("glog warn test")
    // glog.Error("glog error test")
    // glog.Fatal("glog fatal test")
}

glog就更輕量化,就兩個檔案,是google的c++日誌庫glog的golang版本

用了下這幾個庫,雖然都很強大,但是感覺跟我的需求不太符合,我需要能夠每日一個檔案或者每個小時一個檔案或者限定檔案格式動態rotating的功能,但是好像沒有(或者我沒有發現),然後日誌的輸出格式也不是我習慣的,所有沒辦法,就花了一兩天時間自己寫了個簡單的符合我自己要求的日誌庫 go-slog,有興趣的同學可以clone下來試試看,O(∩_∩)O

4. slog

因為上面的幾個日誌庫,感覺不太符合我自己的口味,就自己寫了個簡單的日誌庫,下載地址:https://github.com/yandaren/go-slog, 有興趣的同學可以clone下來試試,程式碼很簡單,下面給出一些
example

package slog_example

import (
    "fmt"
    "go-slog/slog"
    "time"
)

func Slog_test() {
    for _, lg_lvl := range slog.AllLogLevels {
        fmt.Printf("%d = %s\n", lg_lvl, lg_lvl.String())
    }

    fmt.Printf("----------------------------------\n")
    var lvl_strings = []string{
        "debug",
        "info",
        "warn",
        "warning",
        "error",
        "fatal",
        "none",
        "sblv",
    }

    for _, lg_lvl_str := range lvl_strings {
        lg_lvl, err := slog.ParseLevel(lg_lvl_str)
        if err != nil {
            fmt.Printf("parse lg_lvl_str[%s] error[%s]\n", lg_lvl_str, err.Error())
        } else {
            fmt.Printf("log_lvl_str[%s] = %d\n", lg_lvl_str, lg_lvl)
        }
    }

    fmt.Printf("---------------slog test---------------\n")
    logger := slog.NewStdoutLoggerSt("stdout_logger")

    logger.Debug("slog stdoutlogger test")
    logger.Info("slog stdoutlogger test")
    logger.Warn("slog stdoutlogger test, %d", 3)

    stderr_logger := slog.NewStderrLoggerSt("stderr_logger")
    stderr_logger.Debug("slog stderr_logger test")
    stderr_logger.Info("slog stderr_logger test")
    stderr_logger.Warn("slog stderr_logger test, %d", 3)
}

func File_writer_test() {
    fmt.Printf("file_writer_test\n")

    fwriter := slog.NewFileWriter()

    file_name := "file_writer_test.txt"

    if !fwriter.Open(file_name, false) {
        fmt.Printf("create file[%s] failed\n", file_name)
        return
    }

    defer fwriter.Close()

    for i := 0; i < 10; i++ {
        fwriter.Write([]byte("11111111111111111111\n"))
    }

    file_name1 := "file_writer_test1.txt"

    if !fwriter.Open(file_name1, false) {
        fmt.Printf("create file[%s] failed\n", file_name1)
        return
    }

    defer fwriter.Close()

    for i := 0; i < 10; i++ {
        fwriter.Write([]byte("2222222222222222222222\n"))
    }
}

// 這個就是最簡單的單個檔案的logger
func Simple_file_logger_test() {
    fmt.Printf("simple_file_logger_test\n")

    logger := slog.NewBasicLoggerSt("base_logger", "basic_logger.txt")

    for i := 0; i < 10; i++ {
        logger.Debug("base logger debug log test")
        logger.Info("base logger info log test")
        logger.Warn("base logger warn log test")
    }
}

// 這個指定每個檔案的最大大小,以及維護的最大檔案格式
// 當前檔案大小到達指定的最大檔案大小之後,就會進行一次rotating
// 比如最多保留3個檔案的話
// Rotate files:
// log.txt -> log.1.txt
// log.1.txt -> log.2.txt
// log.2.txt -> log.3.txt
// log.3.txt -> delete
func Rotating_logger_test() {
    fmt.Printf("rotating_logger_test\n")

    logger := slog.NewRotatingLoggerSt("rotating_logger", "rotating_logger.txt", 500, 5)

    for i := 0; i < 20; i++ {
        logger.Debug("rorating msg xxx now_time[%s]", time.Now().String())
    }
}

// 這個是每日一個檔案的logger
func Daily_logger_test() {
    fmt.Printf("daily_logger_test\n")

    logger := slog.NewDailyLoggerSt("daily_logger", "daily_logger.txt", 12, 30)

    for i := 0; i < 20; i++ {
        logger.Debug("daily_logger test")
    }
}

// 這個是每個小時會重新生成一個檔案的logger
func Hourly_logger_test() {
    fmt.Printf("Hourly_logger_test\n")

    logger := slog.NewHourlyLoggerSt("houly_logger", "houly_logger.txt")

    for i := 0; i < 20; i++ {
        logger.Debug("houlry_logger test")
    }
}

// 你建立的一個logger,同一條日誌可以根據需要列印到多個地方
// 比如stdout, stderr, file 之類的
func Muti_sink_test() {
    logger := slog.NewLogger("muti_logger")
    sink1 := slog.NewSimpleFileSinkSt("muti_sink_logger.txt")
    sink2 := slog.NewHourlyFileSinkSt("muti_hourly_logger.txt")
    sink3 := slog.NewStdoutSinkSt()

    logger.AppendSink(sink1).AppendSink(sink2).AppendSink(sink3)

    for i := 0; i < 20; i++ {
        logger.Debug("muti_sink_test test")
    }
}

func logger_log_test(gid int, logger *slog.Logger) {

    fmt.Printf("logger_log_test gid[%d]\n", gid)

    for i := 0; i < 5; i++ {
        logger.Debug("logger_log_test gid[%d] msgid[%d]", gid, i)
    }
}

func Muti_goroutine_stdout_test_nolock() {

    fmt.Printf("Muti_goroutine_stdout_test_nolock")

    logger := slog.NewStdoutLoggerSt("Muti_goroutine_test_nolock")

    for i := 0; i < 5; i++ {
        go logger_log_test(i, logger)
    }

    fmt.Printf("try sleep for a while\n")
    time.Sleep(time.Millisecond * 100)
    fmt.Printf("sleep finished, Muti_goroutine_test_nolock end\n")
}

func Muti_goroutine_stdout_test_lock() {
    fmt.Printf("Muti_goroutine_stdout_test_lock")

    logger := slog.NewStdoutLoggerMt("Muti_goroutine_test_lock")

    for i := 0; i < 5; i++ {
        go logger_log_test(i, logger)
    }

    fmt.Printf("try sleep for a while\n")
    time.Sleep(time.Millisecond * 100)
    fmt.Printf("sleep finished, Muti_goroutine_test_nolock end\n")
}

func Muti_goroutine_log_file_test_nolock() {

    fmt.Printf("Muti_goroutine_log_file_test_nolock")

    logger := slog.NewBasicLoggerSt("Muti_goroutine_log_file_test_nolock", "Muti_goroutine_log_file_test_nolock.txt")

    for i := 0; i < 5; i++ {
        go logger_log_test(i, logger)
    }

    fmt.Printf("try sleep for a while\n")
    time.Sleep(time.Millisecond * 100)
    fmt.Printf("sleep finished, Muti_goroutine_test_nolock end\n")
}

func Muti_goroutine_log_file_test_lock() {
    fmt.Printf("Muti_goroutine_log_file_test_lock")

    logger := slog.NewBasicLoggerMt("Muti_goroutine_log_file_test_lock", "Muti_goroutine_log_file_test_lock.txt")

    for i := 0; i < 5; i++ {
        go logger_log_test(i, logger)
    }

    fmt.Printf("try sleep for a while\n")
    time.Sleep(time.Millisecond * 100)
    fmt.Printf("sleep finished, Muti_goroutine_test_nolock end\n")
}

相關文章