log.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package logging
  2. import (
  3. "fmt"
  4. "log"
  5. "lttc-go-adm-znaf/pkg/file"
  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. // 初始化
  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. func setPrefix(level Level) {
  38. _, f, line, ok := runtime.Caller(DefaultCallerDepth)
  39. if ok {
  40. logPrefix = fmt.Sprintf("[%s][%s:%d]", levelFlags[level], filepath.Base(f), line)
  41. } else {
  42. logPrefix = fmt.Sprintf("[%s]", levelFlags[level])
  43. }
  44. logger.SetPrefix(logPrefix)
  45. }
  46. // debug 模式下输出日志
  47. func Debug(v ...interface{}) {
  48. setPrefix(DEBUG)
  49. logger.Println(v)
  50. }
  51. // Info 模式下输出日志
  52. func Info(v ...interface{}) {
  53. setPrefix(INFO)
  54. logger.Println(v)
  55. }
  56. // warning 模式下输出日志
  57. func Warn(v ...interface{}) {
  58. setPrefix(WARNING)
  59. logger.Println(v)
  60. }
  61. // Error 模式下输出日志
  62. func Error(v ...interface{}) {
  63. setPrefix(ERROR)
  64. logger.Println(v)
  65. }
  66. // Fatal 模式下输出日志
  67. func Fatal(v ...interface{}) {
  68. setPrefix(FATAL)
  69. logger.Println(v)
  70. }