logger.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package muesli
  2. import (
  3. "fmt"
  4. "reflect"
  5. "runtime"
  6. "strings"
  7. "testing"
  8. )
  9. /** Logger interface that Muesli uses,to allow external logging packages to be used easly.*/
  10. type Logger interface {
  11. Log(level string, file string, line int, format string, args ...interface{})
  12. }
  13. func WriteLog(logger Logger, depth int, level string, format string, args ...interface{}) {
  14. if logger == nil {
  15. return
  16. }
  17. _, file, line, ok := runtime.Caller(depth)
  18. if !ok {
  19. file = "unknown"
  20. line = 0
  21. }
  22. logger.Log(level, file, line, format, args...)
  23. }
  24. type LoggerWrapper struct {
  25. Logger
  26. }
  27. func (lw LoggerWrapper) WriteLog(depth int, level string, format string, args ...interface{}) {
  28. WriteLog(lw.Logger, depth, level, format, args...)
  29. }
  30. func (lw LoggerWrapper) LogTrace(format string, args ...interface{}) {
  31. lw.WriteLog(3, "TRACE:", format, args...)
  32. }
  33. func (lw LoggerWrapper) LogDebug(format string, args ...interface{}) {
  34. lw.WriteLog(3, "DEBUG:", format, args...)
  35. }
  36. func (lw LoggerWrapper) LogInfo(format string, args ...interface{}) {
  37. lw.WriteLog(3, "INFO:", format, args...)
  38. }
  39. func (lw LoggerWrapper) LogWarning(format string, args ...interface{}) {
  40. lw.WriteLog(3, "WARNING:", format, args...)
  41. }
  42. func (lw LoggerWrapper) LogError(format string, args ...interface{}) {
  43. lw.WriteLog(3, "ERROR:", format, args...)
  44. }
  45. /* Logger used internally in Muesli for tests. */
  46. type testLogger struct {
  47. last string
  48. repeat int
  49. test * testing.T
  50. }
  51. func (tl *testLogger) Log(level string, file string, line int, format string, args ...interface{}) {
  52. text1 := fmt.Sprintf("%s:%s:%d: ", level, file, line)
  53. text2 := fmt.Sprintf(format, args...)
  54. if format[len(format)-1] != '\n' {
  55. text2 = text2 + "\n"
  56. }
  57. out := text1 + text2
  58. if strings.Compare(out, tl.last) == 0 {
  59. tl.repeat++
  60. } else {
  61. if tl.repeat > 0 {
  62. if tl.test == nil {
  63. fmt.Printf("%s:%s:%d: Above message repeated %d times.",
  64. level, file, line, tl.repeat)
  65. } else {
  66. tl.test.Logf("%s:%s:%d: Above message repeated %d times.",
  67. level, file, line, tl.repeat)
  68. }
  69. }
  70. tl.last = out
  71. tl.repeat = 0
  72. if tl.test == nil {
  73. fmt.Printf("%s", out)
  74. } else {
  75. tl.test.Logf("%s", out)
  76. }
  77. }
  78. }
  79. /* Useful when logging. */
  80. func GetFunctionName(i interface{}) string {
  81. return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
  82. }