-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.go
95 lines (83 loc) · 2.4 KB
/
logging.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2020 The Centrifuge authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file at:
// https://github.com/centrifugal/centrifuge-go
package apc
// LogLevel describes the chosen log level.
type LogLevel int
const (
// LogLevelNone means no logging.
LogLevelNone LogLevel = iota
// LogLevelDebug turns on debug logs - its generally too much for production in normal
// conditions but can help when developing and investigating problems in production.
LogLevelDebug
// LogLevelInfo is logs useful server information. This includes various information
// about problems with client connections which is not Centrifugo errors but
// in most situations malformed client behaviour.
LogLevelInfo
// LogLevelError level logs only server errors. This is logging that means non-working
// Centrifugo and maybe effort from developers/administrators to make things
// work again.
LogLevelError
)
// levelToString matches LogLevel to its string representation.
var levelToString = map[LogLevel]string{
LogLevelDebug: "debug",
LogLevelInfo: "info",
LogLevelError: "error",
LogLevelNone: "none",
}
// LogLevelToString transforms Level to its string representation.
func LogLevelToString(l LogLevel) string {
if t, ok := levelToString[l]; ok {
return t
}
return ""
}
// LogEntry represents log entry.
type LogEntry struct {
Level LogLevel
Message string
Fields map[string]interface{}
}
// newLogEntry helps to create Entry.
func newLogEntry(level LogLevel, message string, fields ...map[string]interface{}) LogEntry {
var f map[string]interface{}
if len(fields) > 0 {
f = fields[0]
}
return LogEntry{
Level: level,
Message: message,
Fields: f,
}
}
// LogHandler handles log entries - i.e. writes into correct destination if necessary.
type LogHandler func(LogEntry)
func newLogger(level LogLevel, handler LogHandler) *logger {
return &logger{
level: level,
handler: handler,
}
}
// logger can log entries.
type logger struct {
level LogLevel
handler LogHandler
}
// log calls log handler with provided LogEntry.
func (l *logger) log(entry LogEntry) {
if l == nil {
return
}
if l.enabled(entry.Level) {
l.handler(entry)
}
}
// enabled says whether specified Level enabled or not.
func (l *logger) enabled(level LogLevel) bool {
if l == nil {
return false
}
return level >= l.level && l.level != LogLevelNone
}