【python】通过loging模块将日志写入mysql数据库
2021/12/23 19:07:26
本文主要是介绍【python】通过loging模块将日志写入mysql数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
建立新的py文件,用于写DB日志写入
文件名dblog.py
# coding: utf-8 import logging import pymysql class DatabaseLogHandler(logging.Handler): def __init__(self, create='127.0.0.1', name='root', password='qwer1234!', createID='business', table='applist_log', port=3306): self.db = pymysql.connect( host=create, port=port, user=name, passwd=password, db=createID) # 连接地址,登陆名,密码,数据库标示 self.table = table # 表名 self.cursor = self.db.cursor() self.db.commit() logging.Handler.__init__(self) def emit(self, record): trace = None print(record) kwargs = { 'logger_name': record.name, 'level': record.levelname, 'level_no': record.levelno, 'msg': record.getMessage(), 'trace': trace, 'file_name': record.filename, 'func_name': record.funcName, # 'path_name': record.pathname, 'line_no': record.lineno } print(kwargs) keys = list(kwargs.keys()) for i in range(len(keys)): keys[i] = '`' + keys[i] + '`' keys = ','.join(keys) values = ','.join(['%s'] * len(kwargs)) sql_insert = f"INSERT INTO {self.table}({keys}) VALUES ({values})" self.db.ping(reconnect=True) # 测试数据库连接 try: self.cursor.execute(sql_insert, tuple(kwargs.values())) self.db.commit() except Exception as err: print('插入错误', err)
调用日志模块
from logging import getLogger,Formatter,StreamHandler,INFO from logging.handlers import TimedRotatingFileHandler from sys import stdout from config.dblog import DatabaseLogHandler # 设置日志配置 logger = getLogger('api_log') logger.setLevel(INFO) formatter = Formatter('%(asctime)s - %(name)s - %(levelname)s %(message)s') # 写日志到数据库中 dblog = DatabaseLogHandler() dblog.setFormatter(formatter) logger.addHandler(dblog) logger.info('日志的msg内容')
这篇关于【python】通过loging模块将日志写入mysql数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-18Mysql安装入门:新手必读指南
- 2024-11-18MySQL事务MVCC原理入门详解
- 2024-11-16MySQL资料:新手入门教程
- 2024-11-16MySQL资料:新手入门教程
- 2024-11-15MySQL教程:初学者必备的MySQL数据库入门指南
- 2024-11-15MySQL教程:初学者必看的MySQL入门指南
- 2024-11-04部署MySQL集群项目实战:新手入门教程
- 2024-11-04如何部署MySQL集群资料:新手入门指南
- 2024-11-02MySQL集群项目实战:新手入门指南
- 2024-11-02初学者指南:部署MySQL集群资料