logger.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. // Package logger provides logging capabilities.
  2. // It is a wrapper around zerolog for logging and lumberjack for log rotation.
  3. // Logs are written to the specified log file.
  4. // Logging on the console is provided to print initialization info, errors and warnings.
  5. // The package provides a request logger to log the HTTP requests for REST API too.
  6. // The request logger uses chi.middleware.RequestLogger,
  7. // chi.middleware.LogFormatter and chi.middleware.LogEntry to build a structured
  8. // logger using zerolog
  9. package logger
  10. import (
  11. "errors"
  12. "fmt"
  13. "os"
  14. "path/filepath"
  15. "runtime"
  16. "github.com/rs/zerolog"
  17. lumberjack "gopkg.in/natefinch/lumberjack.v2"
  18. )
  19. const (
  20. dateFormat = "2006-01-02T15:04:05.000" // YYYY-MM-DDTHH:MM:SS.ZZZ
  21. )
  22. // LogLevel defines log levels.
  23. type LogLevel uint8
  24. // defines our own log level, just in case we'll change logger in future
  25. const (
  26. LevelDebug LogLevel = iota
  27. LevelInfo
  28. LevelWarn
  29. LevelError
  30. )
  31. var (
  32. logger zerolog.Logger
  33. consoleLogger zerolog.Logger
  34. rollingLogger *lumberjack.Logger
  35. )
  36. // GetLogger get the configured logger instance
  37. func GetLogger() *zerolog.Logger {
  38. return &logger
  39. }
  40. // InitLogger configures the logger using the given parameters
  41. func InitLogger(logFilePath string, logMaxSize int, logMaxBackups int, logMaxAge int, logCompress bool, level zerolog.Level) {
  42. zerolog.TimeFieldFormat = dateFormat
  43. if isLogFilePathValid(logFilePath) {
  44. rollingLogger = &lumberjack.Logger{
  45. Filename: logFilePath,
  46. MaxSize: logMaxSize,
  47. MaxBackups: logMaxBackups,
  48. MaxAge: logMaxAge,
  49. Compress: logCompress,
  50. }
  51. logger = zerolog.New(rollingLogger)
  52. EnableConsoleLogger(level)
  53. } else {
  54. logger = zerolog.New(&logSyncWrapper{
  55. output: os.Stdout,
  56. })
  57. consoleLogger = zerolog.Nop()
  58. }
  59. logger = logger.Level(level)
  60. }
  61. // DisableLogger disable the main logger.
  62. // ConsoleLogger will not be affected
  63. func DisableLogger() {
  64. logger = zerolog.Nop()
  65. rollingLogger = nil
  66. }
  67. // EnableConsoleLogger enables the console logger
  68. func EnableConsoleLogger(level zerolog.Level) {
  69. consoleOutput := zerolog.ConsoleWriter{
  70. Out: os.Stdout,
  71. TimeFormat: dateFormat,
  72. NoColor: runtime.GOOS == "windows",
  73. }
  74. consoleLogger = zerolog.New(consoleOutput).With().Timestamp().Logger().Level(level)
  75. }
  76. // RotateLogFile closes the existing log file and immediately create a new one
  77. func RotateLogFile() error {
  78. if rollingLogger != nil {
  79. return rollingLogger.Rotate()
  80. }
  81. return errors.New("logging to file is disabled")
  82. }
  83. // Log logs at the specified level for the specified sender
  84. func Log(level LogLevel, sender string, connectionID string, format string, v ...interface{}) {
  85. switch level {
  86. case LevelDebug:
  87. Debug(sender, connectionID, format, v...)
  88. case LevelInfo:
  89. Info(sender, connectionID, format, v...)
  90. case LevelWarn:
  91. Warn(sender, connectionID, format, v...)
  92. default:
  93. Error(sender, connectionID, format, v...)
  94. }
  95. }
  96. // Debug logs at debug level for the specified sender
  97. func Debug(sender string, connectionID string, format string, v ...interface{}) {
  98. logger.Debug().Timestamp().Str("sender", sender).Str("connection_id", connectionID).Msg(fmt.Sprintf(format, v...))
  99. }
  100. // Info logs at info level for the specified sender
  101. func Info(sender string, connectionID string, format string, v ...interface{}) {
  102. logger.Info().Timestamp().Str("sender", sender).Str("connection_id", connectionID).Msg(fmt.Sprintf(format, v...))
  103. }
  104. // Warn logs at warn level for the specified sender
  105. func Warn(sender string, connectionID string, format string, v ...interface{}) {
  106. logger.Warn().Timestamp().Str("sender", sender).Str("connection_id", connectionID).Msg(fmt.Sprintf(format, v...))
  107. }
  108. // Error logs at error level for the specified sender
  109. func Error(sender string, connectionID string, format string, v ...interface{}) {
  110. logger.Error().Timestamp().Str("sender", sender).Str("connection_id", connectionID).Msg(fmt.Sprintf(format, v...))
  111. }
  112. // DebugToConsole logs at debug level to stdout
  113. func DebugToConsole(format string, v ...interface{}) {
  114. consoleLogger.Debug().Msg(fmt.Sprintf(format, v...))
  115. }
  116. // InfoToConsole logs at info level to stdout
  117. func InfoToConsole(format string, v ...interface{}) {
  118. consoleLogger.Info().Msg(fmt.Sprintf(format, v...))
  119. }
  120. // WarnToConsole logs at info level to stdout
  121. func WarnToConsole(format string, v ...interface{}) {
  122. consoleLogger.Warn().Msg(fmt.Sprintf(format, v...))
  123. }
  124. // ErrorToConsole logs at error level to stdout
  125. func ErrorToConsole(format string, v ...interface{}) {
  126. consoleLogger.Error().Msg(fmt.Sprintf(format, v...))
  127. }
  128. // TransferLog logs an SFTP/SCP upload or download
  129. func TransferLog(operation string, path string, elapsed int64, size int64, user string, connectionID string, protocol string) {
  130. logger.Info().
  131. Timestamp().
  132. Str("sender", operation).
  133. Int64("elapsed_ms", elapsed).
  134. Int64("size_bytes", size).
  135. Str("username", user).
  136. Str("file_path", path).
  137. Str("connection_id", connectionID).
  138. Str("protocol", protocol).
  139. Msg("")
  140. }
  141. // CommandLog logs an SFTP/SCP/SSH command
  142. func CommandLog(command, path, target, user, fileMode, connectionID, protocol string, uid, gid int, atime, mtime,
  143. sshCommand string, size int64) {
  144. logger.Info().
  145. Timestamp().
  146. Str("sender", command).
  147. Str("username", user).
  148. Str("file_path", path).
  149. Str("target_path", target).
  150. Str("filemode", fileMode).
  151. Int("uid", uid).
  152. Int("gid", gid).
  153. Str("access_time", atime).
  154. Str("modification_time", atime).
  155. Int64("size", size).
  156. Str("ssh_command", sshCommand).
  157. Str("connection_id", connectionID).
  158. Str("protocol", protocol).
  159. Msg("")
  160. }
  161. // ConnectionFailedLog logs failed attempts to initialize a connection.
  162. // A connection can fail for an authentication error or other errors such as
  163. // a client abort or a time out if the login does not happen in two minutes.
  164. // These logs are useful for better integration with Fail2ban and similar tools.
  165. func ConnectionFailedLog(user, ip, loginType, protocol, errorString string) {
  166. logger.Debug().
  167. Timestamp().
  168. Str("sender", "connection_failed").
  169. Str("client_ip", ip).
  170. Str("username", user).
  171. Str("login_type", loginType).
  172. Str("protocol", protocol).
  173. Str("error", errorString).
  174. Msg("")
  175. }
  176. func isLogFilePathValid(logFilePath string) bool {
  177. cleanInput := filepath.Clean(logFilePath)
  178. if cleanInput == "." || cleanInput == ".." {
  179. return false
  180. }
  181. return true
  182. }