jsonrpc_log.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package jsonrpclite
  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. type RpcLogger interface {
  25. Debug(msg string) //Write the debug log.
  26. Trace(msg string) //Write the trace log.
  27. Info(msg string) //Write the info log.
  28. Warning(msg string) //Write the warning log.
  29. Error(msg string) //Write the error log.
  30. }
  31. var logger = newConsoleLogger()
  32. //SetRpcLogger call this method to register custom logger into the JsonRpcLite
  33. func SetRpcLogger(l RpcLogger) {
  34. logger = l
  35. }
  36. //Default logger for print log on console.
  37. type rpcConsoleLogger struct {
  38. locker *sync.Mutex
  39. }
  40. //Create the default console logger.
  41. func newConsoleLogger() RpcLogger {
  42. l := new(rpcConsoleLogger)
  43. l.locker = new(sync.Mutex)
  44. return l
  45. }
  46. //Write the log by different level.
  47. func (l *rpcConsoleLogger) log(level LogLevel, msg string) {
  48. defer func() {
  49. var p = any(recover())
  50. if p != nil {
  51. l.locker.Unlock()
  52. }
  53. }()
  54. now := time.Now()
  55. timeStr := now.Format("2006-01-02 15:04:05.000000000")
  56. l.locker.Lock()
  57. fmt.Println(levels[level] + "- [" + timeStr + "] " + msg)
  58. l.locker.Unlock()
  59. }
  60. // Debug Write the debug log.
  61. func (l *rpcConsoleLogger) Debug(msg string) {
  62. l.log(DebugLevel, msg)
  63. }
  64. // Trace Write the trace log.
  65. func (l *rpcConsoleLogger) Trace(msg string) {
  66. l.log(TraceLevel, msg)
  67. }
  68. // Info Write the info log.
  69. func (l *rpcConsoleLogger) Info(msg string) {
  70. l.log(InfoLevel, msg)
  71. }
  72. // Warning Write the warning log.
  73. func (l *rpcConsoleLogger) Warning(msg string) {
  74. l.log(WarningLevel, msg)
  75. }
  76. //Write the error log.
  77. func (l *rpcConsoleLogger) Error(msg string) {
  78. l.log(ErrorLevel, msg)
  79. }