log.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "fmt"
  4. "sync"
  5. "time"
  6. )
  7. type LogLevel uint8
  8. const (
  9. DebugLevel = iota
  10. TraceLevel
  11. InfoLevel
  12. WarningLevel
  13. ErrorLevel
  14. )
  15. var (
  16. levels = map[LogLevel]string{
  17. DebugLevel: "Debug",
  18. TraceLevel: "Trace",
  19. InfoLevel: "Info",
  20. WarningLevel: "Warning",
  21. ErrorLevel: "Error",
  22. }
  23. )
  24. var Logger *SystemLogger = newSystemLogger()
  25. type SystemLogger struct {
  26. locker *sync.Mutex
  27. }
  28. //Create the default console logger.
  29. func newSystemLogger() *SystemLogger {
  30. l := new(SystemLogger)
  31. l.locker = new(sync.Mutex)
  32. return l
  33. }
  34. //Write the log by different level.
  35. func (l *SystemLogger) log(level LogLevel, msg string) {
  36. defer func() {
  37. var p = any(recover())
  38. if p != nil {
  39. l.locker.Unlock()
  40. }
  41. }()
  42. now := time.Now()
  43. timeStr := now.Format("2006-01-02 15:04:05.000000000")
  44. l.locker.Lock()
  45. fmt.Println(levels[level] + "- [" + timeStr + "] " + msg)
  46. l.locker.Unlock()
  47. }
  48. // Debug Write the debug log.
  49. func (l *SystemLogger) Debug(msg string) {
  50. l.log(DebugLevel, msg)
  51. }
  52. // Trace Write the trace log.
  53. func (l *SystemLogger) Trace(msg string) {
  54. l.log(TraceLevel, msg)
  55. }
  56. // Info Write the info log.
  57. func (l *SystemLogger) Info(msg string) {
  58. l.log(InfoLevel, msg)
  59. }
  60. // Warning Write the warning log.
  61. func (l *SystemLogger) Warning(msg string) {
  62. l.log(WarningLevel, msg)
  63. }
  64. //Write the error log.
  65. func (l *SystemLogger) Error(msg string) {
  66. l.log(ErrorLevel, msg)
  67. }