github.com/RajatVaryani/mattermost-server@v5.11.1+incompatible/mlog/human/logrus_writer.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package human
     5  
     6  import (
     7  	"fmt"
     8  	"io"
     9  	"time"
    10  
    11  	"github.com/sirupsen/logrus"
    12  )
    13  
    14  type LogrusWriter struct {
    15  	logger *logrus.Logger
    16  }
    17  
    18  func (w *LogrusWriter) Write(e LogEntry) {
    19  	if e.Level == "" {
    20  		fmt.Fprintln(w.logger.Out, e.Message)
    21  		return
    22  	}
    23  
    24  	lvl, err := logrus.ParseLevel(e.Level)
    25  	if err != nil {
    26  		fmt.Fprintln(w.logger.Out, err)
    27  		lvl = logrus.TraceLevel + 1 // will invoke Println
    28  	}
    29  
    30  	logger := w.logger.WithTime(e.Time)
    31  
    32  	if e.Caller != "" {
    33  		// logrus has a system of reporting the caller, but there's no easy way to override it
    34  		logger = logger.WithField("caller", e.Caller)
    35  	}
    36  
    37  	for _, field := range e.Fields {
    38  		logger = logger.WithField(field.Key, field.Interface)
    39  	}
    40  
    41  	switch lvl {
    42  	case logrus.PanicLevel:
    43  		// Prevent panic from causing us to exit
    44  		defer func() {
    45  			recover()
    46  		}()
    47  		logger.Panic(e.Message)
    48  	case logrus.FatalLevel:
    49  		logger.Fatal(e.Message)
    50  	case logrus.ErrorLevel:
    51  		logger.Error(e.Message)
    52  	case logrus.WarnLevel:
    53  		logger.Warn(e.Message)
    54  	case logrus.InfoLevel:
    55  		logger.Info(e.Message)
    56  	case logrus.DebugLevel:
    57  		logger.Debug(e.Message)
    58  	case logrus.TraceLevel:
    59  		logger.Trace(e.Message)
    60  	default:
    61  		logger.Println(e.Message)
    62  	}
    63  }
    64  
    65  func NewLogrusWriter(output io.Writer) *LogrusWriter {
    66  	w := new(LogrusWriter)
    67  	w.logger = logrus.New()
    68  	w.logger.SetLevel(logrus.TraceLevel) // don't filter any logs
    69  	w.logger.ExitFunc = func(int) {}     // prevent Fatal from causing us to exit
    70  	w.logger.SetReportCaller(false)
    71  	w.logger.SetOutput(output)
    72  	var tf logrus.TextFormatter
    73  	tf.FullTimestamp = true
    74  	tf.TimestampFormat = time.RFC3339Nano
    75  	w.logger.SetFormatter(&tf)
    76  	return w
    77  }