Updated Debugging with ksql.InjectLogger (markdown)

Vinícius Garcia 2023-07-15 23:00:17 -03:00
parent 1a7c423711
commit 0ef6054095

@ -1,10 +1,22 @@
It is possible to inject a logger on the context used by the KSQL functions to make KSQL log all the queries sent to the database.
When debugging it is sometimes useful to be able to see the exact query that is being sent to the database, for that KSQL allows you to inject a logger into the context used by the KSQL methods. This causes KSQL to log all the queries sent to the database.
This is particularly useful when debugging and/or trying to understand how KSQL creates some queries.
You can either decide to use one of the two built-in loggers, by using:
The example below illustrates how this can be done:
- `ctx = ksql.InjectLogger(ctx, ksql.Logger)`
- `ctx = ksql.InjectLogger(ctx, ksql.ErrorLogger)`
> Note: The example below is a snippet from a more complete example that can be found [here](https://github.com/VinGarcia/ksql/blob/master/examples/logging_queries/main.go)
Or you can create your own, by passing a custom function to InjectLogger, e.g.:
```golang
ctx := InjectLogger(ctx, func(ctx context.Context, values LogValues) {
fmt.Println("the values are:", values.Query, values.Params, values.Err)
})
```
The short example below illustrates how this can be done,
a more complete example is available on [this file][logging_queries_example].
[logging_queries_example]: https://github.com/VinGarcia/ksql/blob/master/examples/logging_queries/main.go
```golang
// After we inject a logger, all subsequent queries
@ -40,4 +52,20 @@ err = db.Query(ctx, &users, "FROM users LIMIT 10")
if err != nil {
panic(err.Error())
}
```
```
## Why Injecting in the context?
The choice of injecting this logger on the context instead of
just adding it as a config argument to the KSQL client, is that
it gives the user a more fine grained control over what is
logged and where.
For example we often just want to see the logs of a single query
when debugging and this technique allows the user to inject
the logger right before the function that is failing.
Another use-case is the possibility of having different loggers
for different parts of your system: for routine queries, you might
just want to log if an error happens, but for more sensitive parts you
might prefer to always log the query even when there are no errors.