From 72a9253f17cbe74b58d79922fa404f1d37681bac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Sat, 15 Jul 2023 22:47:41 -0300 Subject: [PATCH] Created Debugging with `ksql.InjectLogger` (markdown) --- Debugging-with-`ksql.InjectLogger`.md | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Debugging-with-`ksql.InjectLogger`.md diff --git a/Debugging-with-`ksql.InjectLogger`.md b/Debugging-with-`ksql.InjectLogger`.md new file mode 100644 index 0000000..a1ad4b4 --- /dev/null +++ b/Debugging-with-`ksql.InjectLogger`.md @@ -0,0 +1,43 @@ +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. + +This is particularly useful when debugging and/or trying to understand how KSQL creates some queries. + +The example below illustrates how this can be done: + +> 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) + +```golang + // After we inject a logger, all subsequent queries + // will use this logger. + // + // You can also inject the ksql.ErrorLogger if you only + // care about these logs when a query error happens. + ctx = ksql.InjectLogger(ctx, ksql.Logger) + + // This logs: {"query":"CREATE TABLE IF NOT EXISTS users (\n\t id INTEGER PRIMARY KEY,\n\t\tage INTEGER,\n\t\tname TEXT\n\t)","params":null} + _, err = db.Exec(ctx, `CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY, + age INTEGER, + name TEXT + )`) + if err != nil { + panic(err.Error()) + } + + // This logs: {"query":"INSERT INTO `users` (`name`, `age`) VALUES (?, ?)","params":["Alison",22]} + var alison = User{ + Name: "Alison", + Age: 22, + } + err = db.Insert(ctx, UsersTable, &alison) + if err != nil { + panic(err.Error()) + } + + // This logs: {"query":"SELECT `id`, `name`, `age` FROM users LIMIT 10","params":null} + var users []User + err = db.Query(ctx, &users, "FROM users LIMIT 10") + if err != nil { + panic(err.Error()) + } +``` \ No newline at end of file