2017-03-25 12 views
1

golangでlogrusを使用してファイルにログを記録しています。現在、logrusはフィールド名を使ってファイルにロギングしています。ファイルへのログ記録中にlogrusのフィールド名を無効にする方法

すなわち

time="26-03-2017 03:37:58" level=error msg="Not fatal. An error. Won't stop execution"

ログエントリは、それが標準エラー出力の場合にどのように動作するかのような

ERRO 26-03-2017 03:37:58 Not fatal. An error. Won't stop execution

になるように、どのように私は、フィールド名を削除しますか?

答えて

0

表示したいフィールドのみを出力するカスタムフォーマッタを記述する必要があります。

例はlogrus readmeであり:ここでは

type MyJSONFormatter struct { 
} 

log.SetFormatter(new(MyJSONFormatter)) 

func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { 
    // Note this doesn't include Time, Level and Message which are available on 
    // the Entry. Consult `godoc` on information about those fields or read the 
    // source of the official loggers. 
    serialized, err := json.Marshal(entry.Data) 
    if err != nil { 
     return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) 
    } 
    return append(serialized, '\n'), nil 
} 
0

は、あなたが要求したものを手に入れる方法は次のとおりです。

package main 

import (
    log "github.com/sirupsen/logrus" 
    "fmt" 
) 

type PlainFormatter struct { 
    TimestampFormat string 
    LevelDesc []string 
} 

func (f *PlainFormatter) Format(entry *log.Entry) ([]byte, error) { 
    timestamp := fmt.Sprintf(entry.Time.Format(f.TimestampFormat)) 
    return []byte(fmt.Sprintf("%s %s %s\n", f.LevelDesc[entry.Level], timestamp, entry.Message)), nil 
} 

func main() { 
    plainFormatter := new(PlainFormatter) 
    plainFormatter.TimestampFormat = "2006-01-02 15:04:05" 
    plainFormatter.LevelDesc = []string{"PANC", "FATL", "ERRO", "WARN", "INFO", "DEBG"} 
    log.SetFormatter(plainFormatter) 
    log.Errorln("Not fatal. An error. Won't stop execution") 
    log.Infoln("Just some info") 
} 
  • は、(タイムスタンプ書式とレベルのフィールドを持つ)PlainFormatter構造体
  • を作成します。
  • フォーマット関数/メソッドを作成する(構造体がレシーバ)
  • セットlogrusカスタムフォーマッタを使用する

出力:私の本で

ERRO 2017-07-01 18:22:21 Not fatal. An error. Won't stop execution 
INFO 2017-07-01 18:22:21 Just some info 

あなたが装飾と機能の追加でアプリケーションロガーを操作する方法のより実用的な例を見ることができますLearn Functional Programming in Goブック章。

関連する問題