-
-
Notifications
You must be signed in to change notification settings - Fork 703
/
logger.go
220 lines (195 loc) · 6.25 KB
/
logger.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
// Package logger provides logging capabilities.
// It is a wrapper around zerolog for logging and lumberjack for log rotation.
// Logs are written to the specified log file.
// Logging on the console is provided to print initialization info, errors and warnings.
// The package provides a request logger to log the HTTP requests for REST API too.
// The request logger uses chi.middleware.RequestLogger,
// chi.middleware.LogFormatter and chi.middleware.LogEntry to build a structured
// logger using zerolog
package logger
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/rs/zerolog"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
const (
dateFormat = "2006-01-02T15:04:05.000" // YYYY-MM-DDTHH:MM:SS.ZZZ
)
// LogLevel defines log levels.
type LogLevel uint8
// defines our own log level, just in case we'll change logger in future
const (
LevelDebug LogLevel = iota
LevelInfo
LevelWarn
LevelError
)
var (
logger zerolog.Logger
consoleLogger zerolog.Logger
rollingLogger *lumberjack.Logger
)
// GetLogger get the configured logger instance
func GetLogger() *zerolog.Logger {
return &logger
}
// InitLogger configures the logger using the given parameters
func InitLogger(logFilePath string, logMaxSize int, logMaxBackups int, logMaxAge int, logCompress bool, level zerolog.Level) {
zerolog.TimeFieldFormat = dateFormat
if isLogFilePathValid(logFilePath) {
rollingLogger = &lumberjack.Logger{
Filename: logFilePath,
MaxSize: logMaxSize,
MaxBackups: logMaxBackups,
MaxAge: logMaxAge,
Compress: logCompress,
}
logger = zerolog.New(rollingLogger)
EnableConsoleLogger(level)
} else {
logger = zerolog.New(&logSyncWrapper{
output: os.Stdout,
})
consoleLogger = zerolog.Nop()
}
logger = logger.Level(level)
}
// InitStdErrLogger configures the logger to write to stderr
func InitStdErrLogger(level zerolog.Level) {
logger = zerolog.New(&logSyncWrapper{
output: os.Stderr,
}).Level(level)
consoleLogger = zerolog.Nop()
}
// DisableLogger disable the main logger.
// ConsoleLogger will not be affected
func DisableLogger() {
logger = zerolog.Nop()
rollingLogger = nil
}
// EnableConsoleLogger enables the console logger
func EnableConsoleLogger(level zerolog.Level) {
consoleOutput := zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: dateFormat,
NoColor: runtime.GOOS == "windows",
}
consoleLogger = zerolog.New(consoleOutput).With().Timestamp().Logger().Level(level)
}
// RotateLogFile closes the existing log file and immediately create a new one
func RotateLogFile() error {
if rollingLogger != nil {
return rollingLogger.Rotate()
}
return errors.New("logging to file is disabled")
}
// Log logs at the specified level for the specified sender
func Log(level LogLevel, sender string, connectionID string, format string, v ...interface{}) {
var ev *zerolog.Event
switch level {
case LevelDebug:
ev = logger.Debug()
case LevelInfo:
ev = logger.Info()
case LevelWarn:
ev = logger.Warn()
default:
ev = logger.Error()
}
ev.Timestamp().Str("sender", sender)
if connectionID != "" {
ev.Str("connection_id", connectionID)
}
ev.Msg(fmt.Sprintf(format, v...))
}
// Debug logs at debug level for the specified sender
func Debug(sender string, connectionID string, format string, v ...interface{}) {
Log(LevelDebug, sender, connectionID, format, v...)
}
// Info logs at info level for the specified sender
func Info(sender string, connectionID string, format string, v ...interface{}) {
Log(LevelInfo, sender, connectionID, format, v...)
}
// Warn logs at warn level for the specified sender
func Warn(sender string, connectionID string, format string, v ...interface{}) {
Log(LevelWarn, sender, connectionID, format, v...)
}
// Error logs at error level for the specified sender
func Error(sender string, connectionID string, format string, v ...interface{}) {
Log(LevelError, sender, connectionID, format, v...)
}
// DebugToConsole logs at debug level to stdout
func DebugToConsole(format string, v ...interface{}) {
consoleLogger.Debug().Msg(fmt.Sprintf(format, v...))
}
// InfoToConsole logs at info level to stdout
func InfoToConsole(format string, v ...interface{}) {
consoleLogger.Info().Msg(fmt.Sprintf(format, v...))
}
// WarnToConsole logs at info level to stdout
func WarnToConsole(format string, v ...interface{}) {
consoleLogger.Warn().Msg(fmt.Sprintf(format, v...))
}
// ErrorToConsole logs at error level to stdout
func ErrorToConsole(format string, v ...interface{}) {
consoleLogger.Error().Msg(fmt.Sprintf(format, v...))
}
// TransferLog logs an SFTP/SCP upload or download
func TransferLog(operation string, path string, elapsed int64, size int64, user string, connectionID string, protocol string) {
logger.Info().
Timestamp().
Str("sender", operation).
Int64("elapsed_ms", elapsed).
Int64("size_bytes", size).
Str("username", user).
Str("file_path", path).
Str("connection_id", connectionID).
Str("protocol", protocol).
Send()
}
// CommandLog logs an SFTP/SCP/SSH command
func CommandLog(command, path, target, user, fileMode, connectionID, protocol string, uid, gid int, atime, mtime,
sshCommand string, size int64) {
logger.Info().
Timestamp().
Str("sender", command).
Str("username", user).
Str("file_path", path).
Str("target_path", target).
Str("filemode", fileMode).
Int("uid", uid).
Int("gid", gid).
Str("access_time", atime).
Str("modification_time", atime).
Int64("size", size).
Str("ssh_command", sshCommand).
Str("connection_id", connectionID).
Str("protocol", protocol).
Send()
}
// ConnectionFailedLog logs failed attempts to initialize a connection.
// A connection can fail for an authentication error or other errors such as
// a client abort or a time out if the login does not happen in two minutes.
// These logs are useful for better integration with Fail2ban and similar tools.
func ConnectionFailedLog(user, ip, loginType, protocol, errorString string) {
logger.Debug().
Timestamp().
Str("sender", "connection_failed").
Str("client_ip", ip).
Str("username", user).
Str("login_type", loginType).
Str("protocol", protocol).
Str("error", errorString).
Send()
}
func isLogFilePathValid(logFilePath string) bool {
cleanInput := filepath.Clean(logFilePath)
if cleanInput == "." || cleanInput == ".." {
return false
}
return true
}