github.com/Accefy/pop@v0.0.0-20230428174248-e9f677eab5b9/logger.go (about) 1 package pop 2 3 import ( 4 "fmt" 5 stdlog "log" 6 "os" 7 8 "github.com/fatih/color" 9 "github.com/gobuffalo/pop/v6/logging" 10 ) 11 12 // Debug mode, to toggle verbose log traces 13 var Debug = false 14 15 // Color mode, to toggle colored logs 16 var Color = true 17 18 // SetLogger overrides the default logger. 19 func SetLogger(logger func(level logging.Level, s string, args ...interface{})) { 20 log = logger 21 } 22 23 // SetLogger overrides the default logger. 24 func SetTxLogger(logger func(level logging.Level, anon interface{}, s string, args ...interface{})) { 25 txlog = logger 26 } 27 28 var defaultStdLogger = stdlog.New(os.Stderr, "[POP] ", stdlog.LstdFlags) 29 30 var log = func(lvl logging.Level, s string, args ...interface{}) { 31 txlog(lvl, nil, s, args...) 32 } 33 34 var txlog = func(lvl logging.Level, anon interface{}, s string, args ...interface{}) { 35 if !Debug && lvl <= logging.Debug { 36 return 37 } 38 if lvl == logging.SQL { 39 if len(args) > 0 { 40 xargs := make([]string, len(args)) 41 for i, a := range args { 42 switch a.(type) { 43 case string: 44 xargs[i] = fmt.Sprintf("%q", a) 45 default: 46 xargs[i] = fmt.Sprintf("%v", a) 47 } 48 } 49 s = fmt.Sprintf("%s - %s | %s", lvl, s, xargs) 50 } else { 51 s = fmt.Sprintf("%s - %s", lvl, s) 52 } 53 54 connID := "" 55 txID := 0 56 extra := "" 57 switch typed := anon.(type) { 58 case *Connection: 59 connID = typed.ID 60 if typed.TX != nil { 61 txID = typed.TX.ID 62 } 63 64 extra = printStats(&typed.Store) 65 case *Tx: 66 txID = typed.ID 67 case store: 68 if t, ok := typed.(*Tx); ok { 69 txID = t.ID 70 } 71 72 extra = printStats(&typed) 73 } 74 75 s = fmt.Sprintf("%s (conn=%v, tx=%v%v)", s, connID, txID, extra) 76 } else { 77 s = fmt.Sprintf(s, args...) 78 s = fmt.Sprintf("%s - %s", lvl, s) 79 } 80 81 if Color { 82 s = color.YellowString(s) 83 } 84 85 defaultStdLogger.Println(s) 86 } 87 88 // printStats returns a string represent connection pool information from 89 // the given store. 90 func printStats(s *store) string { 91 if db, ok := (*s).(*dB); ok { 92 s := db.Stats() 93 return fmt.Sprintf(", maxconn: %d, openconn: %d, in-use: %d, idle: %d", s.MaxOpenConnections, s.OpenConnections, s.InUse, s.Idle) 94 } 95 96 return "" 97 }