繁体   English   中英

如何将调用 class 名称发送到 Python 中的记录器 class >

[英]How to send calling class name to logger class in Python >

我是 Python 的新手,并试图在我的代码中实现记录器。 我创建了一个 python 文件:setup_logger.py

import logging

CLASS_NAME = ''

# Create and configure logger
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
logging.basicConfig(filename='/Users/bobby/Desktop/lumberjack.log', level=logging.DEBUG, format=LOG_FORMAT)
logger = logging.getLogger()

我在另一个 python 文件中使用此记录器配置:GetLogger.py 如下

from LoggerLevels.setup_logger import logger

if __name__ == '__main__':
    logger.error('This is a basic log error message')
    logger.info('This is a warning message')

日志在文件中打印为:

2020-06-17 14:54:47,161 - root - ERROR - This is a basic log error message
2020-06-17 14:54:47,161 - root - INFO - This is a warning message

但我看到 class 名称打印为root 我知道这是由于setup_logger.py文件中的设置。 无论如何我可以发送将消息记录到我的文件中的当前 class 名称吗? 例如:我正在使用GetLogger.py文件中的记录器 object。 无论如何我可以将消息记录为

2020-06-17 14:54:47,161 - GetLogger - ERROR - This is a basic log error message
2020-06-17 14:54:47,161 - GetLogger - INFO - This is a warning message

谁能让我知道我怎样才能做到这一点?

利用:

LOG_FORMAT = '%(asctime)s - %(module)s - %(levelname)s - %(message)s'

如果这对您不起作用,您可以尝试%(filename)s或使用setLoggerClass方法创建自定义 class。

这是一个建议,供您参考。

logger_format = '%(asctime)s [%(className)s] %(funcName)s | %(message)s (%(name)s)'
extra_dict = {'className': 'NameOfClass'}
logger = logging.getLogger('logger_name')

def callLogger():
    logger.debug('log message', extra=extra_dict)

callLogger()

结果将是:

2021-02-21 17:08:34,066 [NameOfClass] 呼叫记录器 | 日志消息(logger_name)

当我们在不同的 class 中使用相同的记录器时,这种方式也是可行的。

如果您在每个 class 中使用不同的记录器,您有更简单的方法,例如:

# put the (%(name)s) to position of name of class
logger_format = '%(asctime)s [%(name)s] %(funcName)s | %(message)s'

# name the logger name as class name
logger = logging.getLogger('NameOfClass')

def callLogger():
    logger.debug('log message')

callLogger()

结果将是:

2021-02-21 17:08:34,066 [NameOfClass] 呼叫记录器 | 日志消息

参考Python官方文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM