作为数据库清理工作的一部分,我正在对现有数据库表的使用量和用户进行审计。使用日志文件似乎是获取此数据的一种自然方式。我们为性能报告运行了pgBadger,但我所描述的使用情况报告并不存在。谁知道有什么工具(pgBadger或其他工具)可以从日志中提取表和用户信息,以便我可以计算其中的汇总统计信息?我喜欢利用现有的工具,而不是使用我自己的日志解析器。
发布于 2018-09-13 11:38:36
我写了一个粗俗的日志解析器。
import re
import psqlparse
import json
statement_re = r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC:[^:]*:(?P<user>\w+)@(?P<db>\w+):.*statement:\s+(?P<stmt>.*)"
log_re = r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"
def parse_logs(log_file):
with open(log_file, 'r') as f:
state = 'looking'
info = None
for line in f:
if state == 'found':
if re.match(log_re, line) is None:
info['stmt'].append(line.strip())
else:
info['stmt'] = "\n".join(info['stmt']).strip()
try:
parsed_stmt = psqlparse.parse(info['stmt'])[0]
info['stmt_type'] = str(type(parsed_stmt)).split(".")[-1][0:-6].lower()
info['tables'] = list(parsed_stmt.tables())
except:
pass
print(json.dumps(info))
state = 'looking'
if state == 'looking':
m = re.match(statement_re, line)
if m is not None:
stmt = m.group('stmt')
if stmt not in {'BEGIN', 'COMMIT', 'ROLLBACK', 'SELECT 1'} and 'show' not in stmt:
info = {'user': m.group('user'), 'stmt': [stmt]}
state = 'found'
parse_logs('postgresql.log')
https://stackoverflow.com/questions/52170914
复制相似问题