logger.go 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. package gorm
  2. import (
  3. "database/sql/driver"
  4. "fmt"
  5. "log"
  6. "os"
  7. "reflect"
  8. "regexp"
  9. "strconv"
  10. "time"
  11. "unicode"
  12. )
  13. var (
  14. defaultLogger = Logger{log.New(os.Stdout, "\r\n", 0)}
  15. sqlRegexp = regexp.MustCompile(`\?`)
  16. numericPlaceHolderRegexp = regexp.MustCompile(`\$\d+`)
  17. )
  18. func isPrintable(s string) bool {
  19. for _, r := range s {
  20. if !unicode.IsPrint(r) {
  21. return false
  22. }
  23. }
  24. return true
  25. }
  26. var LogFormatter = func(values ...interface{}) (messages []interface{}) {
  27. if len(values) > 1 {
  28. var (
  29. sql string
  30. formattedValues []string
  31. level = values[0]
  32. currentTime = "\n\033[33m[" + NowFunc().Format("2006-01-02 15:04:05") + "]\033[0m"
  33. source = fmt.Sprintf("\033[35m(%v)\033[0m", values[1])
  34. )
  35. messages = []interface{}{source, currentTime}
  36. if level == "sql" {
  37. // duration
  38. messages = append(messages, fmt.Sprintf(" \033[36;1m[%.2fms]\033[0m ", float64(values[2].(time.Duration).Nanoseconds()/1e4)/100.0))
  39. // sql
  40. for _, value := range values[4].([]interface{}) {
  41. indirectValue := reflect.Indirect(reflect.ValueOf(value))
  42. if indirectValue.IsValid() {
  43. value = indirectValue.Interface()
  44. if t, ok := value.(time.Time); ok {
  45. formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05")))
  46. } else if b, ok := value.([]byte); ok {
  47. if str := string(b); isPrintable(str) {
  48. formattedValues = append(formattedValues, fmt.Sprintf("'%v'", str))
  49. } else {
  50. formattedValues = append(formattedValues, "'<binary>'")
  51. }
  52. } else if r, ok := value.(driver.Valuer); ok {
  53. if value, err := r.Value(); err == nil && value != nil {
  54. formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
  55. } else {
  56. formattedValues = append(formattedValues, "NULL")
  57. }
  58. } else {
  59. formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
  60. }
  61. } else {
  62. formattedValues = append(formattedValues, "NULL")
  63. }
  64. }
  65. // differentiate between $n placeholders or else treat like ?
  66. if numericPlaceHolderRegexp.MatchString(values[3].(string)) {
  67. sql = values[3].(string)
  68. for index, value := range formattedValues {
  69. placeholder := fmt.Sprintf(`\$%d([^\d]|$)`, index+1)
  70. sql = regexp.MustCompile(placeholder).ReplaceAllString(sql, value+"$1")
  71. }
  72. } else {
  73. formattedValuesLength := len(formattedValues)
  74. for index, value := range sqlRegexp.Split(values[3].(string), -1) {
  75. sql += value
  76. if index < formattedValuesLength {
  77. sql += formattedValues[index]
  78. }
  79. }
  80. }
  81. messages = append(messages, sql)
  82. messages = append(messages, fmt.Sprintf(" \n\033[36;31m[%v]\033[0m ", strconv.FormatInt(values[5].(int64), 10)+" rows affected or returned "))
  83. } else {
  84. messages = append(messages, "\033[31;1m")
  85. messages = append(messages, values[2:]...)
  86. messages = append(messages, "\033[0m")
  87. }
  88. }
  89. return
  90. }
  91. type logger interface {
  92. Print(v ...interface{})
  93. }
  94. // LogWriter log writer interface
  95. type LogWriter interface {
  96. Println(v ...interface{})
  97. }
  98. // Logger default logger
  99. type Logger struct {
  100. LogWriter
  101. }
  102. // Print format & print log
  103. func (logger Logger) Print(values ...interface{}) {
  104. logger.Println(LogFormatter(values...)...)
  105. }