gpt4 book ai didi

python 记录.Logger : overriding makeRecord

转载 作者:行者123 更新时间:2023-12-05 07:33:05 24 4
gpt4 key购买 nike

我有一个格式化程序,它需要记录中的特殊属性“user_id”,但并不总是存在(有时我使用特殊的日志记录将其添加到记录中。过滤器)。我试图像这样覆盖 logging.Logger 的 makeRecord 方法:

import logging

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)-15s user_id=%(user_id)s %(filename)s:%(lineno)-15s: %(message)s')


class OneTestLogger(logging.Logger):
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
rv = logging.Logger.makeRecord(self, name, level, fn, lno,
msg, args, exc_info,
func, extra)
rv.__dict__.setdefault('user_id', 'master')
return rv


if __name__ == '__main__':

logger = OneTestLogger('main')
print logger
logger.info('Starting test')

但这似乎不起作用,而且我不断得到:

<main.MyLogger instance at 0x7f31a6a5b638>

No handlers could be found for logger "main"

我做错了什么?谢谢。

最佳答案

遵循 Logging Cookbook 中提供的指南.只是第一部分,我没有实现 Filter(它也没有出现在下面的引用中)。

This has usually meant that if you need to do anything special with a LogRecord, you’ve had to do one of the following.

  1. Create your own Logger subclass, which overrides Logger.makeRecord(), and set it using setLoggerClass() before any loggers that you care about are instantiated.

我简化了您的示例,只是添加了“主机名”:

import logging
from socket import gethostname

logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(hostname)s - %(message)s')

class NewLogger(logging.Logger):
def makeRecord(self, *args, **kwargs):
rv = super(NewLogger, self).makeRecord(*args, **kwargs)
# updating the rv value of the original makeRecord
# my idea is to use the same logic than a decorator by
# intercepting the value return by the original makeRecord
# and expanded with what I need
rv.__dict__['hostname'] = gethostname()
# by curiosity I am checking what is in this dictionary
# print(rv.__dict__)
return rv

logging.setLoggerClass(NewLogger)

logger = logging.getLogger(__name__)
logger.info('Hello World!')

请注意,此代码适用于 python 2.7

关于 python 记录.Logger : overriding makeRecord,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50823062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com