在我的Phoenix / Ecto应用程序中,当我将日志级别设置为:debug
时,我看到Ecto发出的每个SQL查询的有用日志条目,如下所示:
[debug] QUERY OK source="users" db=1.9ms
SELECT u0."id", u0."full_name", u0."email", u0."uuid", u0."auth0_uid", u0."last_signed_in_at", u0."inserted_at", u0."updated_at" FROM "users" AS u0 WHERE (u0."id" = $1) LIMIT 1 [1]
[debug] QUERY OK source="projects" db=11.8ms
SELECT p0."id", p0."name", p0."uuid", p0."settings", p0."inserted_at", p0."updated_at" FROM "projects" AS p0 WHERE (p0."uuid" = $1) LIMIT 1 ["7qDjSk"]
[debug] QUERY OK source="project_admin_joins" db=1.9ms
SELECT p0."id", p0."project_id", p0."admin_id", p0."inserted_at", p0."updated_at", p0."project_id" FROM "project_admin_joins" AS p0 WHERE (p0."project_id" = $1) ORDER BY p0."project_id" [2]
但是我很想对这种格式进行一些调整:
如何自定义Ecto sql查询日志的格式?
答案 0 :(得分:1)
似乎没有自定义Ecto的日志记录格式的事情;相反,我需要禁用内置日志记录并编写自己的日志记录功能。 但这在Ecto v2和Ecto v3中的工作原理大不相同。
在config.exs
中,配置MyApp.Repo以使用新的自定义记录器功能。该函数可以存在于任何地方,但就我而言,我将其放在MyApp.Repo.log_query/2
中:
config :my_app, MyApp.Repo,
# ...
loggers: [{MyApp.Repo, :log_query, []}]
在lib/my_app/repo.ex
中,定义log_query
函数:(注意:在我的情况下,我已经硬编码了:debug
日志级别。)
...
require Logger
# Inspired by https://github.com/elixir-ecto/ecto/blob/v2.2.11/lib/ecto/log_entry.ex
def log_query(entry) do
Logger.log(:debug, fn ->
{ok, _} = entry.result
source = inspect(entry.source)
time_us = System.convert_time_unit(entry.query_time, :native, :microsecond)
time_ms = div(time_us, 100) / 10
# Strip out unnecessary quotes from the query for readability
query = Regex.replace(~r/(\d\.)"([^"]+)"/, entry.query, "\\1\\2")
params = inspect(entry.params, charlists: false)
"SQL query: #{ok} source=#{source} db=#{time_ms}ms #{query} params=#{params}"
end)
end
就是这样!确保正确设置了日志级别,重新启动应用程序,并且您应该看到所有以这种新格式而不是旧格式记录的Ecto查询。
Ecto v3鼓励您使用telemetry events而不是那些讨厌的旧配置文件。
在lib/my_app/application.ex
MyApp.Application.start/2
中,您需要设置遥测事件。在Supervisor.start_link/2
调用之前添加以下代码段:
# Subscribe to Ecto queries for logging
# See https://hexdocs.pm/ecto/Ecto.Repo.html#module-telemetry-events
# and https://github.com/beam-telemetry/telemetry
handler = &MyApp.Telemetry.handle_event/4
:ok = :telemetry.attach("my_app-ecto", [:my_app, :repo, :query], handler, %{})
然后定义您的遥测模块,该模块目前仅具有此一个事件处理程序。我将我的邮件保存在lib/my_app/telemetry.ex
中:
defmodule MyApp.Telemetry do
require Logger
# Thanks to https://hexdocs.pm/ecto/Ecto.Repo.html#module-telemetry-events
def handle_event([:my_app, :repo, :query], measurements, metadata, _config) do
Logger.log(:debug, fn ->
{ok, _} = metadata.result
source = inspect(metadata.source)
time = div(measurements.query_time, 100_000) / 10
# Strip out unnecessary quotes from the query for readability
query = Regex.replace(~r/(\d\.)"([^"]+)"/, metadata.query, "\\1\\2")
params = inspect(metadata.params, charlists: false)
"SQL query: #{ok} source=#{source} db=#{time}ms #{query} params=#{params}"
end)
end
end
在config/config.exs
中,配置MyApp.Repo以禁用标准的Ecto日志记录:
config :my_app, MyApp.Repo,
# ...
log: false
就是这样!确保正确设置了日志级别,重新启动应用程序,并且您应该看到所有以这种新格式而不是旧格式记录的Ecto查询。