Hi! Is it possible to use the Log module to get logs about queries/database access? Something like the Active Record logs, but only using the crystal-pg driver.
Seems like it, but this is leveraged to the crystal-db shard: crystal-db/src/db/statement.cr at e88604bf4af26aac8dc276473f2d1c1a22468203 · crystal-lang/crystal-db · GitHub
How to use it? No idea, but I could figure it out for you ;)
It depends on how exactly you want logging to work. The easiest way to see only db logs is via like:
Log.setup("db.*", :debug)
Otherwise if you want/need more control you can do something like:
Log.setup do |c|
backend = Log::IOBackend.new
c.bind "*", :warn, backend # Log all logs >= warn by default
c.bind "db.*", :debug, backend # => log >= debug for `db.*` logs only
# ...
end
This is how I do it in my open source IT substrate platform (not released yet, soon):
require "opentelemetry"
# Instrument DB::BeginTransaction#transaction
module DB::BeginTransaction
def transaction(& : Transaction -> T) : T? forall T
OpenTelemetry.trace "db.transaction" do |_span|
previous_def do |txn|
yield txn
end
end
end
end
Basically reopen the transaction method from crystal db library. Here using open telemetry, but you can adapt the code for adding logger message.
EDIT: this is not per query, but per transaction; for query, I think you could reopen statement methods.
What @Blacksmoke16 shared is the way to use the built-in Log.
@anykeyh pretty cool you are working with opentelemetry.
To inject additional code around statements crystal-db provides a solution already DB::Statement - db 0.14.0
In most drivers creating a transaction sends a statement so that should cover it also.
Why is the transaction count more meaningful than the queries count to you?