qustavo / sqlhooks

Attach hooks to any database/sql driver
MIT License
652 stars 44 forks source link

how to log sql when sql execute failed? #32

Closed song-without-words closed 4 years ago

qustavo commented 4 years ago

Did you try implementing the on OnErrorer1 interface?

song-without-words commented 4 years ago

thanks for your response. it worked!

song-without-words commented 4 years ago

Sorry, now i have a new problem. Sometimes error log will print twice and i can't find the reason.

qustavo commented 4 years ago

can u send the code

song-without-words commented 4 years ago
func (h *Hooks) OnError(ctx context.Context, err error, query string, args ...interface{}) error {

begin := ctx.Value("begin").(time.Time)
var traceLog string
res := ctx.Value("traceLog")
if res != nil {
    traceLog = res.(string)
} else {
    traceLog, _ = shortid.Generate()
}
l := clog.NewWithCtx(traceLog)
l.Info("SQL | %10s | %s %v", utils.FormatDuration(time.Since(begin)), query, args)
return err
}

then error sql will log twice.

qustavo commented 4 years ago

could you just try to print a single like in the OnError hook? so that we can be sure that the problem is with the hook and not with your logger?

song-without-words commented 4 years ago

thanks for your response. now i think the problem is not with the hook. i use sqlx, then whatever sql is right or wrong, sqlx throws a driver.ErrSkip error and OnError func will exec, so if sql is right, it will print twice.Do you know how to solve it? error: driver: skip fast-path; continue as if unimplemented

qustavo commented 4 years ago

can you fmt.Printf("error: %+v (%T)", err, err) on the hook. If the errors are different you can act differently depending on the error you get

song-without-words commented 4 years ago

thanks for your response, but unfortunately, the errors is the same. error: driver: skip fast-path; continue as if unimplemented (*errors.errorString)