I have followed this guide to create a custom backend logger, it works and I have altered it to write the logs to a file.
The problem is, I also want errors to be logged, for instance:
Call Function.
iex(1)> Test.execute_test(55)
Get Error.
** (MatchError) no match of right hand side value: nil
(___ 0.1.0) lib/___/contexts/___/test.ex:64: Test.execute_test/1
Returned in Console.
iex(1)> [debug] QUERY OK source="test" db=24.5ms idle=49.2ms
SELECT r0."id", r0."test", r0."inserted_at", r0."updated_at" FROM "test" AS r0 WHERE (r0."id" = $1) [55]
I would want that match error to be appended to my log file.
But in the log file all I get is this:
2022-07-18T14:56:39.400Z erl_level=:debug ansi_color=:cyan application=:ecto_sql domain=[:elixir] file=“lib/ecto/adapters/sql.ex” function=“log/4” gl=#PID<0.66.0> line=934 mfa={Ecto.Adapters.SQL, :log, 4} module=Ecto.Adapters.SQL pid=#PID<0.1057.0> time=1658152599400628 [debug] QUERY OK source=“test” db=24.5ms idle=49.2ms
SELECT r0.“id”, r0.“rule”, r0.“mfd”, r0.“inserted_at”, r0.“updated_at” FROM “test” AS r0 WHERE (r0.“id” = $1) [55]
The metadata and the ecto query.
Here is the config:
config :logger,
backends: [
:console,
{Test.LogBackend, :log_backend}
],
level: :debug,
compile_time_purge_matching: [
[level_lower_than: :info]
]
# Our Console Backend-specific configuration
config :logger, :console,
format: {Test.LogFormatter, :format},
metadata: [:request_id]
config :logger, :log_backend,
level: :debug,
handle_otp_reports: :true,
handle_sasl_reports: :true,
metadata: [:mfa, :file, :line, :crash_reason]
I’m not sure where or how / which config option I need to be able to receive the error and append it to the file.
The function for writing to file:
def handle_event({level, _group_leader, {Logger, message, timestamp, metadata}}, %{level: min_level}=state) do
message = Test.LogFormatter.format(level, message, timestamp, metadata)
{:ok, file} = File.open(Path.expand("logs/#{Date.utc_today() |> Date.to_string()}.txt"), [:append])
IO.binwrite(file, message)
File.close(file)
end