最佳实践是,在每个模块中,都有这样定义的记录器:
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')
并根据需要登录到loggerA
和loggerB
.
在主程序中,执行以下操作:
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.