golangのロゴライブラリ

11430 ワード

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.WithFields(logrus.Fields{ "sb": "sbvalue", }).Info("A walrus appears") log1 := logrus.New() fmt.Printf("log1 level: %d
    ", 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
    ") log1.Debug("log1 debug") fmt.Printf("-------------test formater-------------
    ") log1.SetLevel(logrus.DebugLevel) log1.Formatter = &logrus.TextFormatter{ DisableColors: true, FullTimestamp: true, DisableSorting: true, } log1.Debug("log text formatter test") fmt.Printf("-----------json formatter-------------
    ") log1.Formatter = &logrus.JSONFormatter{} log1.Debug("log json formatter test") fmt.Printf("-----------log to file test-----------
    ") 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]
    ", 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("<<<<<<<<>>>>>>>>>>
    ") 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("<<<<<<>>>>>>>>>
    ") 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はより軽量化され、2つのファイルだけでgoogleのc++ログライブラリglogのgolangバージョンです.
    これらのライブラリを使用すると、いずれも強力ですが、私のニーズに合わないような気がします.私は毎日1つのファイルや1時間に1つのファイルを限定したり、ファイル形式を限定したりする動的rotatingの機能が必要ですが、ありません(あるいは発見していません)、ログの出力フォーマットも私の習慣ではありません.仕方がありません.1、2日かけて自分の要求に合った簡単な日記庫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
    ", lg_lvl, lg_lvl.String()) } fmt.Printf("----------------------------------
    ") 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]
    ", lg_lvl_str, err.Error()) } else { fmt.Printf("log_lvl_str[%s] = %d
    ", lg_lvl_str, lg_lvl) } } fmt.Printf("---------------slog test---------------
    ") 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
    ") fwriter := slog.NewFileWriter() file_name := "file_writer_test.txt" if !fwriter.Open(file_name, false) { fmt.Printf("create file[%s] failed
    ", file_name) return } defer fwriter.Close() for i := 0; i < 10; i++ { fwriter.Write([]byte("11111111111111111111
    ")) } file_name1 := "file_writer_test1.txt" if !fwriter.Open(file_name1, false) { fmt.Printf("create file[%s] failed
    ", file_name1) return } defer fwriter.Close() for i := 0; i < 10; i++ { fwriter.Write([]byte("2222222222222222222222
    ")) } } // logger func Simple_file_logger_test() { fmt.Printf("simple_file_logger_test
    ") 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
    ") 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
    ") 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
    ") 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]
    ", 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
    ") time.Sleep(time.Millisecond * 100) fmt.Printf("sleep finished, Muti_goroutine_test_nolock end
    ") } 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
    ") time.Sleep(time.Millisecond * 100) fmt.Printf("sleep finished, Muti_goroutine_test_nolock end
    ") } 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
    ") time.Sleep(time.Millisecond * 100) fmt.Printf("sleep finished, Muti_goroutine_test_nolock end
    ") } 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
    ") time.Sleep(time.Millisecond * 100) fmt.Printf("sleep finished, Muti_goroutine_test_nolock end
    ") }