github.com/levb/mattermost-server@v5.3.1+incompatible/mlog/stdlog.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package mlog 5 6 import ( 7 "bytes" 8 "strings" 9 10 "go.uber.org/zap" 11 "go.uber.org/zap/zapcore" 12 ) 13 14 // Implementation of zapcore.Core to interpret log messages from a standard logger 15 // and translate the levels to zapcore levels. 16 type stdLogLevelInterpreterCore struct { 17 wrappedCore zapcore.Core 18 } 19 20 func stdLogInterpretZapEntry(entry zapcore.Entry) zapcore.Entry { 21 message := entry.Message 22 if strings.Index(message, "[DEBUG]") == 0 { 23 entry.Level = zapcore.DebugLevel 24 entry.Message = message[7:] 25 } else if strings.Index(message, "[DEBG]") == 0 { 26 entry.Level = zapcore.DebugLevel 27 entry.Message = message[6:] 28 } else if strings.Index(message, "[WARN]") == 0 { 29 entry.Level = zapcore.WarnLevel 30 entry.Message = message[6:] 31 } else if strings.Index(message, "[ERROR]") == 0 { 32 entry.Level = zapcore.ErrorLevel 33 entry.Message = message[7:] 34 } else if strings.Index(message, "[EROR]") == 0 { 35 entry.Level = zapcore.ErrorLevel 36 entry.Message = message[6:] 37 } else if strings.Index(message, "[ERR]") == 0 { 38 entry.Level = zapcore.ErrorLevel 39 entry.Message = message[5:] 40 } else if strings.Index(message, "[INFO]") == 0 { 41 entry.Level = zapcore.InfoLevel 42 entry.Message = message[6:] 43 } 44 return entry 45 } 46 47 func (s *stdLogLevelInterpreterCore) Enabled(lvl zapcore.Level) bool { 48 return s.wrappedCore.Enabled(lvl) 49 } 50 51 func (s *stdLogLevelInterpreterCore) With(fields []zapcore.Field) zapcore.Core { 52 return s.wrappedCore.With(fields) 53 } 54 55 func (s *stdLogLevelInterpreterCore) Check(entry zapcore.Entry, checkedEntry *zapcore.CheckedEntry) *zapcore.CheckedEntry { 56 entry = stdLogInterpretZapEntry(entry) 57 return s.wrappedCore.Check(entry, checkedEntry) 58 } 59 60 func (s *stdLogLevelInterpreterCore) Write(entry zapcore.Entry, fields []zapcore.Field) error { 61 entry = stdLogInterpretZapEntry(entry) 62 return s.wrappedCore.Write(entry, fields) 63 } 64 65 func (s *stdLogLevelInterpreterCore) Sync() error { 66 return s.wrappedCore.Sync() 67 } 68 69 func getStdLogOption() zap.Option { 70 return zap.WrapCore( 71 func(core zapcore.Core) zapcore.Core { 72 return &stdLogLevelInterpreterCore{core} 73 }, 74 ) 75 } 76 77 type loggerWriter struct { 78 logFunc func(msg string, fields ...Field) 79 } 80 81 func (l *loggerWriter) Write(p []byte) (int, error) { 82 trimmed := string(bytes.TrimSpace(p)) 83 for _, line := range strings.Split(trimmed, "\n") { 84 l.logFunc(string(line)) 85 } 86 return len(p), nil 87 }