logger.go 6.2 KB

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