logger.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package logger
  5. import (
  6. "fmt"
  7. "os"
  8. "time"
  9. )
  10. var requestedLevel = InfoLevel
  11. // LogLevel type.
  12. type LogLevel uint32
  13. const (
  14. // FatalLevel should be used in fatal situations, the app will exit.
  15. FatalLevel LogLevel = iota
  16. // ErrorLevel should be used when someone should really look at the error.
  17. ErrorLevel
  18. // InfoLevel should be used during normal operations.
  19. InfoLevel
  20. // DebugLevel should be used only during development.
  21. DebugLevel
  22. )
  23. func (level LogLevel) String() string {
  24. switch level {
  25. case DebugLevel:
  26. return "DEBUG"
  27. case InfoLevel:
  28. return "INFO"
  29. case ErrorLevel:
  30. return "ERROR"
  31. case FatalLevel:
  32. return "FATAL"
  33. default:
  34. return "UNKNOWN"
  35. }
  36. }
  37. // EnableDebug increases logging, more verbose (debug)
  38. func EnableDebug() {
  39. requestedLevel = DebugLevel
  40. formatMessage(InfoLevel, "Debug mode enabled")
  41. }
  42. // Debug sends a debug log message.
  43. func Debug(format string, v ...interface{}) {
  44. if requestedLevel >= DebugLevel {
  45. formatMessage(DebugLevel, format, v...)
  46. }
  47. }
  48. // Info sends an info log message.
  49. func Info(format string, v ...interface{}) {
  50. if requestedLevel >= InfoLevel {
  51. formatMessage(InfoLevel, format, v...)
  52. }
  53. }
  54. // Error sends an error log message.
  55. func Error(format string, v ...interface{}) {
  56. if requestedLevel >= ErrorLevel {
  57. formatMessage(ErrorLevel, format, v...)
  58. }
  59. }
  60. // Fatal sends a fatal log message and stop the execution of the program.
  61. func Fatal(format string, v ...interface{}) {
  62. if requestedLevel >= FatalLevel {
  63. formatMessage(FatalLevel, format, v...)
  64. os.Exit(1)
  65. }
  66. }
  67. func formatMessage(level LogLevel, format string, v ...interface{}) {
  68. prefix := fmt.Sprintf("[%s] [%s] ", time.Now().Format("2006-01-02T15:04:05"), level.String())
  69. fmt.Fprintf(os.Stderr, prefix+format+"\n", v...)
  70. }