logrusカスタムログ出力フォーマット

4954 ワード

1.ログ形式の設定方法
logrusでは、次の方法でログフォーマットを設定します.
func SetFormatter(formatter Formatter) 

Formatterはインタフェースです
type Formatter interface {
    Format(*Entry) ([]byte, error)
}

したがって、カスタムログフォーマットを実装することは、本質的にFormatterインタフェースを実装し、SetFormatter方式でlogrusに通知することである.
2.既にFormatterがある
logrusパッケージには、TextFormatterとJSOnFormatterの2種類のFormatterが付属しています.デフォルトでは、TextFormatter出力を使用します.
func main(){
    logrus.WithField("name", "ball").Info("this is from logrus")
}

//  
INFO[0000] this is from logrus      name=ball

説明:
  • 以上はgo version go 1である.14.4 linux/amd 64環境の出力.go version go1.14.4 windows/amd 64の出力は友好的:
  • time="2021-05-10T15:54:33+08:00" level=info msg="this is from logrus" name=ball
    
    
  • 以下の出力はgo version go 1である.14.4 linux/amd 64が基準です.

  • 2.1 TextFormatter
    TextFormatterにはいくつかのカスタマイズ可能なパラメータがあり、一般的なパラメータは以下の通りで、より多くのパラメータと機能は、ソースコードのtext_formatter.goで見ました.
    type TextFormatter struct{
        //      
        ForceColors bool
        EnvironmentOverrideColors bool
        DisableColors bool
        
        //            
        ForceQuote bool
        DisableQuote bool
        QuoteEmptyFields bool
        
        //     
        DisableTimestamp bool
        FullTimestamp bool
        TimestampFormat string
    }
    

    例1
    func main(){
        logrus.SetFormatter(&logrus.TextFormatter{
            ForceQuote:true,    //      
            TimestampFormat:"2006-01-02 15:04:05",  //    
            FullTimestamp:true,     
        })
        
        logrus.WithField("name", "ball").WithField("say", "hi").Info("info log")
    }
    
    //   
    INFO[2021-05-10 16:28:50] info log      name="ball" say="hi"
    

    説明:デフォルトはColorsモードです.このモードでは、FullTimestamp:trueを設定する必要があります.そうしないと、時間表示は有効ではありません.
    例2
    func main(){
        logrus.SetFormatter(&logrus.TextFormatter{
            DisableColors:true,
            ForceQuote:false,
            TimestampFormat:"2006-01-02 15:04:05",
        })
        logrus.WithField("name", "ball").WithField("say", "hi").Info("info log")
    }
    
    //  
    time="2021-05-10 16:32:42" level=info msg="info log" name=ball say=hi
    

    説明:DisableColorsがtrueの場合、ログの様子が変わります.
    2.2 JSONFormatter
    一般的なパラメータは以下の通りで、より多くのパラメータと機能は、ソースコードのjson_formatter.goで見ました.
    type JSONFormatter struct {
        //     
        TimestampFormat string
        DisableTimestamp bool
    
        DisableHTMLEscape bool
    
        // PrettyPrint will indent all json logs
        PrettyPrint bool
    }
    

    func main(){
        logrus.SetFormatter(&logrus.JSONFormatter{
            TimestampFormat:"2006-01-02 15:04:05",
            PrettyPrint: true,
        })
        logrus.WithField("name", "ball").WithField("say", "hi").Info("info log")
    }
    
    //  
    {
      "level": "info",
      "msg": "info log",
      "name": "ball",
      "say": "hi",
      "time": "2021-05-10 16:36:05"
    }
    

    説明:PrettyPrint:trueを設定しないと、jsonは単行出力になります.
    3.カスタムFormatter
    カスタムFormatterは、実際にはFormatterインタフェースを実現します.
    type Formatter interface {
        Format(*Entry) ([]byte, error)
    }
    

    インタフェースの戻り値[]byte、すなわち出力列です.ポイントは入力パラメータEntryを理解することです.
    3.1 Entryパラメータ
    type Entry struct {
        // Contains all the fields set by the user.
        Data Fields
    
        // Time at which the log entry was created
        Time time.Time
    
        // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
        Level Level
    
        //Calling method, with package name
        Caller *runtime.Frame
    
        //Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
        Message string
    
        //When formatter is called in entry.log(), a Buffer may be set to entry
        Buffer *bytes.Buffer
    }
    

    説明:
  • Dataはkey/value形式のデータで、WithFieldで設定したログです.
  • Callerはログ呼び出し者に関する情報であり、その出力ファイル名、行番号などの情報を利用することができ、興味があれば『logrusにおける出力ファイル名、行番号および関数名』
  • を参照することができる.
    type MyFormatter struct {
    
    }
    
    func (m *MyFormatter) Format(entry *logrus.Entry) ([]byte, error){
        var b *bytes.Buffer
        if entry.Buffer != nil {
            b = entry.Buffer
        } else {
            b = &bytes.Buffer{}
        }
    
        timestamp := entry.Time.Format("2006-01-02 15:04:05")
        var newLog string
        newLog = fmt.Sprintf("[%s] [%s] %s
    ", timestamp, entry.Level, entry.Message) b.WriteString(newLog) return b.Bytes(), nil } func main(){ logrus.SetFormatter(&MyFormatter{}) logrus.WithField("name", "ball").WithField("say", "hi").Info("info log") } // [2021-05-10 17:26:06] [info] info log

    説明:例ではentryを処理する.Dataのデータなので、WithFieldで設定したnameを使ってもsayデータは出力されません.