Simplify logger feature

pull/40/head
Vinícius Garcia 2023-07-11 23:39:39 -03:00
parent d65216479a
commit 08247e5b82
2 changed files with 11 additions and 42 deletions

View File

@ -312,7 +312,7 @@ func TestInjectLogger(t *testing.T) {
var loggedQuery string
var loggedParams []interface{}
var loggedErr error
ctx := InjectLogger(ctx, "info", func(ctx context.Context, values LogValues) {
ctx := InjectLogger(ctx, func(ctx context.Context, values LogValues) {
loggedQuery = values.Query
loggedParams = values.Params
loggedErr = values.Err

View File

@ -2,7 +2,6 @@ package ksql
import (
"context"
"strings"
)
type loggerKey struct{}
@ -13,27 +12,19 @@ type LogValues struct {
Err error
}
type loggerFn func(ctx context.Context, query string, params []interface{}, err error)
func InjectLogger(
ctx context.Context,
level string,
logFn func(ctx context.Context, values LogValues),
) context.Context {
level = strings.ToLower(level)
if level != "info" {
// Default to the least verbose level:
level = "error"
}
return context.WithValue(ctx, loggerKey{}, logger{
level: level,
logFn: func(ctx context.Context, query string, params []interface{}, err error) {
logFn(ctx, LogValues{
Query: query,
Params: params,
Err: err,
})
},
})
return context.WithValue(ctx, loggerKey{}, loggerFn(func(ctx context.Context, query string, params []interface{}, err error) {
logFn(ctx, LogValues{
Query: query,
Params: params,
Err: err,
})
}))
}
func ctxLog(ctx context.Context, query string, params []interface{}, err *error) {
@ -42,27 +33,5 @@ func ctxLog(ctx context.Context, query string, params []interface{}, err *error)
return
}
if *err != nil {
l.(logger)._error(ctx, query, params, *err)
return
}
l.(logger)._info(ctx, query, params, nil)
}
type logger struct {
level string
logFn func(ctx context.Context, query string, params []interface{}, err error)
}
func (l logger) _info(ctx context.Context, query string, params []interface{}, err error) {
if l.level == "error" {
return
}
l.logFn(ctx, query, params, err)
}
func (l logger) _error(ctx context.Context, query string, params []interface{}, err error) {
l.logFn(ctx, query, params, err)
l.(loggerFn)(ctx, query, params, *err)
}