logger.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 // import "miniflux.app/logger"
  5. import (
  6. "fmt"
  7. "os"
  8. )
  9. var requestedLevel = InfoLevel
  10. // LogLevel type.
  11. type LogLevel uint32
  12. const (
  13. // FatalLevel should be used in fatal situations, the app will exit.
  14. FatalLevel LogLevel = iota
  15. // ErrorLevel should be used when someone should really look at the error.
  16. ErrorLevel
  17. // InfoLevel should be used during normal operations.
  18. InfoLevel
  19. // DebugLevel should be used only during development.
  20. DebugLevel
  21. )
  22. func (level LogLevel) String() string {
  23. switch level {
  24. case DebugLevel:
  25. return "DEBUG"
  26. case InfoLevel:
  27. return "INFO"
  28. case ErrorLevel:
  29. return "ERROR"
  30. case FatalLevel:
  31. return "FATAL"
  32. default:
  33. return "UNKNOWN"
  34. }
  35. }
  36. // EnableDebug increases logging, more verbose (debug)
  37. func EnableDebug() {
  38. requestedLevel = DebugLevel
  39. formatMessage(InfoLevel, "Debug mode enabled")
  40. }
  41. // Debug sends a debug log message.
  42. func Debug(format string, v ...interface{}) {
  43. if requestedLevel >= DebugLevel {
  44. formatMessage(DebugLevel, format, v...)
  45. }
  46. }
  47. // Info sends an info log message.
  48. func Info(format string, v ...interface{}) {
  49. if requestedLevel >= InfoLevel {
  50. formatMessage(InfoLevel, format, v...)
  51. }
  52. }
  53. // Error sends an error log message.
  54. func Error(format string, v ...interface{}) {
  55. if requestedLevel >= ErrorLevel {
  56. formatMessage(ErrorLevel, format, v...)
  57. }
  58. }
  59. // Fatal sends a fatal log message and stop the execution of the program.
  60. func Fatal(format string, v ...interface{}) {
  61. if requestedLevel >= FatalLevel {
  62. formatMessage(FatalLevel, format, v...)
  63. os.Exit(1)
  64. }
  65. }
  66. func formatMessage(level LogLevel, format string, v ...interface{}) {
  67. prefix := fmt.Sprintf("[%s] ", level.String())
  68. fmt.Fprintf(os.Stderr, prefix+format+"\n", v...)
  69. }