在 Postgres 日志记录机制中更改定界符和换行符
Change delimiter and newline character in Postgres logging mechanism
我在 postgres 中启用了登录。它记录在 CSV 中。第九列是实际执行的查询。我想 运行 一个 cut
命令来提取第 9 列,但问题是查询中的逗号和换行符会破坏解析器。有什么办法可以改变分隔符和换行符吗?
正如 PostgreSQL Manual 中所建议的,您可以使用 postgres 来解析它自己的日志:
- 创建临时 table;
- 将日志文件导入其中;
- select 需要数据。
这是一个简单的 bash 脚本来自动执行该过程。
#!/usr/bin/env bash
psql -t << EOF
CREATE TEMPORARY TABLE postgres_log
(
log_time timestamp(3) with time zone,
user_name text,
database_name text,
process_id integer,
connection_from text,
session_id text,
session_line_num bigint,
command_tag text,
session_start_time timestamp with time zone,
virtual_transaction_id text,
transaction_id bigint,
error_severity text,
sql_state_code text,
message text,
detail text,
hint text,
internal_query text,
internal_query_pos integer,
context text,
query text,
query_pos integer,
location text,
application_name text,
PRIMARY KEY (session_id, session_line_num)
);
COPY postgres_log FROM '' WITH csv;
SELECT query from postgres_log;
EOF
您可以运行它为:./fetch-queries.sh /full/path/to/logfile.csv
我在 postgres 中启用了登录。它记录在 CSV 中。第九列是实际执行的查询。我想 运行 一个 cut
命令来提取第 9 列,但问题是查询中的逗号和换行符会破坏解析器。有什么办法可以改变分隔符和换行符吗?
正如 PostgreSQL Manual 中所建议的,您可以使用 postgres 来解析它自己的日志:
- 创建临时 table;
- 将日志文件导入其中;
- select 需要数据。
这是一个简单的 bash 脚本来自动执行该过程。
#!/usr/bin/env bash
psql -t << EOF
CREATE TEMPORARY TABLE postgres_log
(
log_time timestamp(3) with time zone,
user_name text,
database_name text,
process_id integer,
connection_from text,
session_id text,
session_line_num bigint,
command_tag text,
session_start_time timestamp with time zone,
virtual_transaction_id text,
transaction_id bigint,
error_severity text,
sql_state_code text,
message text,
detail text,
hint text,
internal_query text,
internal_query_pos integer,
context text,
query text,
query_pos integer,
location text,
application_name text,
PRIMARY KEY (session_id, session_line_num)
);
COPY postgres_log FROM '' WITH csv;
SELECT query from postgres_log;
EOF
您可以运行它为:./fetch-queries.sh /full/path/to/logfile.csv