通过file_fdw读取PostgreSQL日志文件PG9.1新增

PG9.4官方英文文档:

关于file_fdw:http://www.postgresql.org/docs/9.4/static/file-fdw.html

关于日志配置http://www.postgresql.org/docs/9.4/static/runtime-config-logging.html


1、 配置postgresql.conf文件中关于日志的参数

log_destination='csvlog'#生成日csv格式的日志文件
logging_collector=on
log_directory='pg_log'#日志文件存储在./data/pg_log目录
log_filename='postgresql-%Y-%m-%d'#定义日志文件名字为postgresql-2013-12-17.csv
log_truncate_on_rotation=off
log_rotation_age=1d#设置日志文件生成的频率为1天
log_rotation_size=0
log_error_verbosity=verbose#设置日志文件中的错误信息为详细
log_statement=all#设置所有语句均计入日志

2、配置file_fdw并创建外部表

检查pg安装目录的lib/postgresql目录下是否存在file_fdw.so文件,确保安装时已经编译安装了file_fdw组件。

以下需要以数据库postgres用户连接到postgres数据库进行操作:

创建扩展:

postgres=#createextensionfile_fdw;

创建外部服务:

postgres=#createserverpglogFOREIGNDATAWRAPPERfile_fdw;

创建外部表:

postgres=#CREATEFOREIGNTABLEpglog(
log_timetimestamp(3)withtimezone,user_nametext,database_nametext,process_idinteger,connection_fromtext,session_idtext,session_line_numbigint,command_tagtext,session_start_timetimestampwithtimezone,virtual_transaction_idtext,transaction_idbigint,error_severitytext,sql_state_codetext,messagetext,detailtext,hinttext,internal_querytext,internal_query_posinteger,contexttext,querytext,query_posinteger,locationtext,application_nametext
)SERVERpglog
OPTIONS(filename'/user/data/pg_log/postgresql-2013-12-17.csv',format'csv');

注意:以上filename中的文件路径要求是绝对路径

可以用以下sql删除外部表:

postgres=#dropforeigntablepglog;

3、使用外部表读取日志信息

postgres=#selectlog_time,connection_from,user_name,database_name,query,application_namefrompglogwherequeryisnotnull;

实际应用中可以根据需要为sql语句添加过滤条件

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...