|
I guess I am quite late to this, but recently I was also struggling to get this logging message format customized and I was hoping to get this done preferably in a simpler way. Coming from Python, this wasn't really as straight forward as I though it to be and logrus documentation also isn't very clear on this. So I had to go through their source code to actually get this done. Here is my code for the same. type myFormatter struct { log.TextFormatter } func (f *myFormatter) Format(entry *log.Entry) ([]byte, error) { // this whole mess of dealing with ansi color codes is required if you want the colored output otherwise you will lose colors in the log levels var levelColor int switch entry.Level { case log.DebugLevel, log.TraceLevel: levelColor = 31 // gray case log.WarnLevel: levelColor = 33 // yellow case log.ErrorLevel, log.FatalLevel, log.PanicLevel: levelColor = 31 // red default: levelColor = 36 // blue } return []byte(fmt.Sprintf("[%s] - \x1b[%dm%s\x1b[0m - %s\n", entry.Time.Format(f.TimestampFormat), levelColor, strings.ToUpper(entry.Level.String()), entry.Message)), nil } func main() { f, _ := os.OpenFile("log.txt", os.O_CREATE|os.O_WRONLY, 0777) logger := &log.Logger{ Out: io.MultiWriter(os.Stderr, f), Level: log.InfoLevel, Formatter: &myFormatter{log.TextFormatter{ FullTimestamp: true, TimestampFormat: "2006-01-02 15:04:05", ForceColors: true, DisableLevelTruncation: true, }, }, } logger.Info("Info message") logger.Warning("Warning message")Here is the output ± go run main.go <<< [2019-05-13 18:10:34] - INFO - Info message [2019-05-13 18:10:34] - WARNING - Warning messagePS: I am very new to this, so if you guys there can be a better neat way of doing this, please do share. (责任编辑:) |
