From 0ef6054095e897a27269b3695fb16eb6dfbf6aea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Sat, 15 Jul 2023 23:00:17 -0300 Subject: [PATCH] Updated Debugging with `ksql.InjectLogger` (markdown) --- Debugging-with-`ksql.InjectLogger`.md | 38 +++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/Debugging-with-`ksql.InjectLogger`.md b/Debugging-with-`ksql.InjectLogger`.md index d44eb63..97385a9 100644 --- a/Debugging-with-`ksql.InjectLogger`.md +++ b/Debugging-with-`ksql.InjectLogger`.md @@ -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()) } -``` \ No newline at end of file +``` + +## 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. \ No newline at end of file