logger.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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) LogDebug(format string, args ...interface{}) {
  31. lw.WriteLog(3, "DEBUG:", format, args...)
  32. }
  33. func (lw LoggerWrapper) LogInfo(format string, args ...interface{}) {
  34. lw.WriteLog(3, "INFO:", format, args...)
  35. }
  36. func (lw LoggerWrapper) LogWarning(format string, args ...interface{}) {
  37. lw.WriteLog(3, "WARNING:", format, args...)
  38. }
  39. func (lw LoggerWrapper) LogError(format string, args ...interface{}) {
  40. lw.WriteLog(3, "ERROR:", format, args...)
  41. }
  42. /* Logger used internally in Muesli for tests. */
  43. type testLogger struct {
  44. last string
  45. repeat int
  46. test * testing.T
  47. }
  48. func (tl *testLogger) Log(level string, file string, line int, format string, args ...interface{}) {
  49. text1 := fmt.Sprintf("%s:%s:%d: ", level, file, line)
  50. text2 := fmt.Sprintf(format, args...)
  51. if format[len(format)-1] != '\n' {
  52. text2 = text2 + "\n"
  53. }
  54. out := text1 + text2
  55. if strings.Compare(out, tl.last) == 0 {
  56. tl.repeat++
  57. } else {
  58. if tl.repeat > 0 {
  59. if tl.test == nil {
  60. fmt.Printf("%s:%s:%d: Above message repeated %d times.",
  61. level, file, line, tl.repeat)
  62. } else {
  63. tl.test.Logf("%s:%s:%d: Above message repeated %d times.",
  64. level, file, line, tl.repeat)
  65. }
  66. }
  67. tl.last = out
  68. tl.repeat = 0
  69. if tl.test == nil {
  70. fmt.Printf("%s", out)
  71. } else {
  72. tl.test.Logf("%s", out)
  73. }
  74. }
  75. }
  76. /* Useful when logging. */
  77. func GetFunctionName(i interface{}) string {
  78. return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
  79. }