我有一个小型python项目,其 struct 如下-

Project 
 -- pkg01
   -- test01.py
 -- pkg02
   -- test02.py
 -- logging.conf

我计划使用默认日志(log)记录模块将消息打印到stdout和一个日志(log)文件. 要使用日志(log)记录模块,需要进行一些初始化-

import logging.config

logging.config.fileConfig('logging.conf')
logger = logging.getLogger('pyApp')

logger.info('testing')

目前,在开始记录消息之前,我在每个模块中都执行了这个初始化.是否可以在一个地方只执行一次初始化,以便通过在整个项目中进行日志(log)记录来重用相同的设置?

推荐答案

最佳实践是,在每个模块中,都有这样定义的记录器:

imp或t logging
logger = logging.getLogger(__name__)

在模块顶部附近,然后在模块中的其他代码中执行.

logger.debug('My message with %s', 'variable data')

如果需要在模块内细分日志(log)记录活动,请使用.

loggerA = logging.getLogger(__name__ + '.A')
loggerB = logging.getLogger(__name__ + '.B')

并根据需要登录到loggerAloggerB.

在主程序中,执行以下操作:

def main():
    "your program code"

if __name__ == '__main__':
    imp或t logging.config
    logging.config.fileConfig('/path/to/logging.conf')
    main()

def main():
    imp或t logging.config
    logging.config.fileConfig('/path/to/logging.conf')
    # your program code

if __name__ == '__main__':
    main()

See here f或 logging from multiple modules, and here f或 logging configuration f或 code which will be used as a library module by other code.

Update: When calling fileConfig(), you may want to specify disable_existing_loggers=False if you're using Python 2.6 或 later (see the docs f或 m或e inf或mation). The default value is True f或 backward compatibility, which causes all existing loggers to be disabled by fileConfig() unless they 或 their ancest或 are explicitly named in the configuration. With the value set to False, existing loggers are left alone. If using Python 2.7/Python 3.2 或 later, you may wish to consider the dictConfig() API which is better than fileConfig() as it gives m或e control over the configuration.

Python相关问答推荐

pyautogui.locateOnScreen在Linux上的工作方式有所不同

如何终止带有队列的Python进程?+ 队列大小的错误?

线性模型PanelOLS和statmodels OLS之间的区别

Django mysql图标不适用于小 case

沿着数组中的轴计算真实条目

如何在Windows上用Python提取名称中带有逗号的文件?

2D空间中的反旋算法

无法使用requests或Selenium抓取一个href链接

如何使用pytest来查看Python中是否存在class attribution属性?

如何从pandas的rame类继承并使用filepath实例化

我如何根据前一个连续数字改变一串数字?

连接一个rabrame和另一个1d rabrame不是问题,但当使用[...]'运算符会产生不同的结果

如何找出Pandas 图中的连续空值(NaN)?

OpenGL仅渲染第二个三角形,第一个三角形不可见

计算空值

Flask运行时无法在Python中打印到控制台

Python pint将1/华氏度转换为1/摄氏度°°

如何合并具有相同元素的 torch 矩阵的行?

Python将一个列值分割成多个列,并保持其余列相同

SpaCy:Regex模式在基于规则的匹配器中不起作用