summaryrefslogtreecommitdiffstats
path: root/mlog/stdlog.go
blob: a875b2e32b3e1bddbd82c9b6d6717a8956cd7089 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package mlog

import (
	"strings"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

// Implementation of zapcore.Core to interpret log messages from a standard logger
// and translate the levels to zapcore levels.
type stdLogLevelInterpreterCore struct {
	wrappedCore zapcore.Core
}

func stdLogInterpretZapEntry(entry zapcore.Entry) zapcore.Entry {
	message := entry.Message
	if strings.Index(message, "[DEBUG]") == 0 {
		entry.Level = zapcore.DebugLevel
		entry.Message = message[7:]
	} else if strings.Index(message, "[DEBG]") == 0 {
		entry.Level = zapcore.DebugLevel
		entry.Message = message[6:]
	} else if strings.Index(message, "[WARN]") == 0 {
		entry.Level = zapcore.WarnLevel
		entry.Message = message[6:]
	} else if strings.Index(message, "[ERROR]") == 0 {
		entry.Level = zapcore.ErrorLevel
		entry.Message = message[7:]
	} else if strings.Index(message, "[EROR]") == 0 {
		entry.Level = zapcore.ErrorLevel
		entry.Message = message[6:]
	} else if strings.Index(message, "[ERR]") == 0 {
		entry.Level = zapcore.ErrorLevel
		entry.Message = message[5:]
	} else if strings.Index(message, "[INFO]") == 0 {
		entry.Level = zapcore.InfoLevel
		entry.Message = message[6:]
	}
	return entry
}

func (s *stdLogLevelInterpreterCore) Enabled(lvl zapcore.Level) bool {
	return s.wrappedCore.Enabled(lvl)
}

func (s *stdLogLevelInterpreterCore) With(fields []zapcore.Field) zapcore.Core {
	return s.wrappedCore.With(fields)
}

func (s *stdLogLevelInterpreterCore) Check(entry zapcore.Entry, checkedEntry *zapcore.CheckedEntry) *zapcore.CheckedEntry {
	entry = stdLogInterpretZapEntry(entry)
	return s.wrappedCore.Check(entry, checkedEntry)
}

func (s *stdLogLevelInterpreterCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {
	entry = stdLogInterpretZapEntry(entry)
	return s.wrappedCore.Write(entry, fields)
}

func (s *stdLogLevelInterpreterCore) Sync() error {
	return s.wrappedCore.Sync()
}

func getStdLogOption() zap.Option {
	return zap.WrapCore(
		func(core zapcore.Core) zapcore.Core {
			return &stdLogLevelInterpreterCore{core}
		},
	)
}