1package mssql 2 3import ( 4 "context" 5 6 "github.com/denisenkom/go-mssqldb/msdsn" 7) 8 9const ( 10 logErrors = uint64(msdsn.LogErrors) 11 logMessages = uint64(msdsn.LogMessages) 12 logRows = uint64(msdsn.LogRows) 13 logSQL = uint64(msdsn.LogSQL) 14 logParams = uint64(msdsn.LogParams) 15 logTransaction = uint64(msdsn.LogTransaction) 16 logDebug = uint64(msdsn.LogDebug) 17 logRetries = uint64(msdsn.LogRetries) 18) 19 20// Logger is an interface you can implement to have the go-msqldb 21// driver automatically log detailed information on your behalf 22type Logger interface { 23 Printf(format string, v ...interface{}) 24 Println(v ...interface{}) 25} 26 27// ContextLogger is an interface that provides more information 28// than Logger and lets you log messages yourself. This gives you 29// more information to log (e.g. trace IDs in the context), more 30// control over the logging activity (e.g. log it, trace it, or 31// log and trace it, depending on the class of message), and lets 32// you log in exactly the format you want. 33type ContextLogger interface { 34 Log(ctx context.Context, category msdsn.Log, msg string) 35} 36 37// optionalLogger implements the ContextLogger interface with 38// a default "do nothing" behavior that can be overridden by an 39// optional ContextLogger supplied by the user. 40type optionalLogger struct { 41 logger ContextLogger 42} 43 44// Log does nothing unless the user has specified an optional 45// ContextLogger to override the "do nothing" default behavior. 46func (o optionalLogger) Log(ctx context.Context, category msdsn.Log, msg string) { 47 if nil != o.logger { 48 o.logger.Log(ctx, category, msg) 49 } 50} 51 52// loggerAdapter converts Logger interfaces into ContextLogger 53// interfaces. It provides backwards compatibility. 54type loggerAdapter struct { 55 logger Logger 56} 57 58// Log passes the message to the underlying Logger interface's 59// Println function, emulating the orignal Logger behavior. 60func (la loggerAdapter) Log(_ context.Context, category msdsn.Log, msg string) { 61 62 // Add prefix for certain categories 63 switch category { 64 case msdsn.LogErrors: 65 msg = "ERROR: " + msg 66 case msdsn.LogRetries: 67 msg = "RETRY: " + msg 68 } 69 70 la.logger.Println(msg) 71} 72