跨多个文件共享Python记录器

And*_*rew 7 python logging

我有一个Python应用程序,其文件结构类似于以下内容:

/Project
    file1.py
    file2.py
    file3.py
    ...
Run Code Online (Sandbox Code Playgroud)

该应用程序正在CentOS 6环境中运行,因此正在使用Python 2.6。

我感兴趣的是建立一种通用的日志记录机制,其中每个文件的日志语句都将写入磁盘上的同一日志文件。这些python文件通常是从命令行执行的,彼此之间有些独立。我测试了以下文档中的一个建议(在此处链接):

log = logging.getLogger(__name__)
Run Code Online (Sandbox Code Playgroud)

我发现,所有日志行都将被列为from __main__,而不管log语句来自哪个文件。换句话说,我无法确定给定日志行来自哪个文件。

我希望可以得到一个日志文件,其内容类似于以下内容:

2017-01-17 10:48:47,446 - file1 - DEBUG - this is from file1
2017-01-17 10:48:47,447 - file2 - DEBUG - this is from file2
2017-01-17 10:48:47,447 - fiel3 - DEBUG - this is from file3
Run Code Online (Sandbox Code Playgroud)

在上面,我将执行:

log.debug("this is from file1")
Run Code Online (Sandbox Code Playgroud)

file1.py和其他文件类似的日志行,替换日志声明适当的文字。

我目前正在使用以下设置日志记录:

########################################
# Setup Logging
########################################
LOG_FILENAME = 'app.log'
# Set up a specific logger with our desired output level
log = logging.getLogger('Logger')
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
              LOG_FILENAME, maxBytes=200000000, backupCount=5)
handler.setFormatter(formatter)
log.addHandler(handler)
########################################
Run Code Online (Sandbox Code Playgroud)

此设置非常适合从一个python源进行日志记录,但用处不大,因为我现在正尝试从多个python源进行日志记录

我已经阅读了在多个模块中使用Python登录;它有很好的答案,但是由于我项目中文件的独立性,__name__无法按所述使用。

xjc*_*jcl 2

最佳方法

不要尝试将记录器名称设置为文件名,只需指定%(module)s!

formatter = logging.Formatter('%(asctime)s - %(module)s - %(levelname)s - %(message)s')
                                             ^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

这将避免打印__main__并很好地为您提供:

2020-11-06 23:19:03,827 - file2 - INFO - This is from file2
2020-11-06 23:19:03,827 - file3 - INFO - This is from file3
2020-11-06 23:19:03,827 - file1 - INFO - This is from file1
Run Code Online (Sandbox Code Playgroud)

享受!



PS:我对您将RotatingFileHandler 相同文件附加到每个记录器而不是一次附加到根记录器感到有点紧张。一般来说,我不建议将日志记录设置代码复制到每个源代码文件和记录器,而是在单独的文件中配置根记录器一次。