log.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package logging
  2. import (
  3. "fmt"
  4. "github.com/EDDYCJY/go-gin-example/pkg/file"
  5. "log"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. )
  10. type Level int
  11. var (
  12. F *os.File
  13. DefaultPrefix = ""
  14. DefaultCallerDepth = 2
  15. logger *log.Logger
  16. logPrefix = ""
  17. levelFlags = []string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL"}
  18. )
  19. const (
  20. DEBUG Level = iota
  21. INFO
  22. WARNING
  23. ERROR
  24. FATAL
  25. )
  26. // Setup initialize the log instance
  27. func Setup() {
  28. var err error
  29. filePath := getLogFilePath()
  30. fileName := getLogFileName()
  31. F, err = file.MustOpen(fileName, filePath)
  32. if err != nil {
  33. log.Fatalf("logging.Setup err: %v", err)
  34. }
  35. logger = log.New(F, DefaultPrefix, log.LstdFlags)
  36. }
  37. // Debug output logs at debug level
  38. func Debug(v ...interface{}) {
  39. setPrefix(DEBUG)
  40. logger.Println(v)
  41. log.Println(v)
  42. }
  43. // Info output logs at info level
  44. func Info(v ...interface{}) {
  45. setPrefix(INFO)
  46. logger.Println(v)
  47. log.Println(v)
  48. }
  49. // Warn output logs at warn level
  50. func Warn(v ...interface{}) {
  51. setPrefix(WARNING)
  52. logger.Println(v)
  53. log.Println(v)
  54. }
  55. // Error output logs at error level
  56. func Error(v ...interface{}) {
  57. setPrefix(ERROR)
  58. logger.Println(v)
  59. log.Println(v)
  60. }
  61. // Fatal output logs at fatal level
  62. func Fatal(v ...interface{}) {
  63. setPrefix(FATAL)
  64. logger.Fatalln(v)
  65. log.Println(v)
  66. }
  67. // setPrefix set the prefix of the log output
  68. func setPrefix(level Level) {
  69. _, file, line, ok := runtime.Caller(DefaultCallerDepth)
  70. if ok {
  71. logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(file), line)
  72. } else {
  73. logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
  74. }
  75. logger.SetPrefix(logPrefix)
  76. }