logger.go 1.9 KB

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