如何覆盖日志记录模块的方法

问题描述 投票:3回答:2

我想计算logger.infologger.error被击中的次数。我打算覆盖日志记录的默认方法错误,任何人都可以建议我如何做到这一点?需要帮助来覆盖错误方法,以便每次代码命中它都会计算值和增量计数器。

python django
2个回答
7
投票

您可以首先通过从logging.Logger派生来实现自己的记录器类,您可以在其中覆盖您定位的方法。然后使用logging.setLoggerClass将记录器类传递给日志记录系统。使用此设置,从logging.getLogger实例化的记录器对象将属于您的类。

根据请求更新示例代码:

import logging
import threading

class MyLogger(logging.Logger):

    def __init__(self, name, level = logging.NOTSET):
        self._count = 0
        self._countLock = threading.Lock()       

        return super(MyLogger, self).__init__(name, level)        

    @property
    def warnCount(self):
        return self._count

    def warning(self, msg, *args, **kwargs):
        self._countLock.acquire()
        self._count += 1
        self._countLock.release()

        return super(MyLogger, self).warning(msg, *args, **kwargs)

logging.setLoggerClass(MyLogger)
logging.basicConfig()


'''testing below'''

logger = logging.getLogger('loggerX')
assert isinstance(logger, MyLogger)

logger.warning('1st warning')
logger.warning('2nd warning')
print logger.warnCount

0
投票

如果您计划覆盖默认日志记录模块,则必须覆盖logging.Handler类。 logging.Handler类有一个名为emit(self, record)的函数,当我们在Django视图中使用日志功能时将调用它,如下所示,

# import the logging library
import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

def my_view(request, arg1, arg):
    ...
    if bad_mojo:
        # Log an error message
        logger.error('Something went wrong!')

压倒logging.Handler

根据我的具体要求,我通过创建ErrorLog的对象在数据库中记录消息,但是你想要做控制台,打印甚至是你做的电子邮件。通过在数据库中执行错误日志,您可以计算logger.infologger.errors

import logging
import traceback


class ErrorLogHandler(logging.Handler):

def emit(self, record):
    '''this each method called when a log creates '''
    from ..models.error_log import ErrorLog
    # for more info you can use this thing from record object
    # print('levelname', record.levelname)
    # print('filename', record.filename)
    # print('funcName', record.funcName)
    # print('lineno', record.lineno)
    # print('module', record.module)
    # print('args', record.args)
    # print('exc_info', record.exc_info)
    # print('msg', record.msg)

    trace = None
    user_master = None

    if record.exc_info:
        trace = traceback.format_exc()

    if record.args and type(record.args) == dict:
        user_master = record.args.get('user_master')

    kwargs = {
        'logger_name': record.name,
        'level': record.levelname,
        'message': record.msg,
        'function_name': record.funcName,
        'file_name': record.filename,
        'trace': trace,
        'user_master': user_master
    }

    ErrorLog.objects.create(**kwargs)

settings.py中,您必须覆盖日志记录的设置

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(asctime)s %(message)s'
        },
    },
    'handlers': {  # this will handle (called) log initialize
        'db_log': {
            'level': 'INFO',
            'class': 'servicesApp.logging.handler.ErrorLogHandler'
        },
    },
    'loggers': {
        'db': {  # for django app logs
            'handlers': ['db_log'],
            'level': 'INFO'
        },
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.