数据库
首页 > 数据库> > 【python】通过loging模块将日志写入mysql数据库

【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内容')

标签:keys,name,python,self,db,record,mysql,import,loging
来源: https://blog.csdn.net/wangteng13/article/details/122110701