Overview
How to log source file name and line number in Python
#!/usr/bin/env python
import logging
logging.basicConfig(
format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d:%H:%M:%S',
level=logging.DEBUG
)
logger = logging.getLogger(__name__)
logger.debug("This is a debug log")
logger.info("This is an info log")
logger.critical("This is critical")
logger.error("An error occurred")
将上面代码保存为 foo.py
文件运行:
$ python foo.py
2017-06-06:17:07:02,158 DEBUG [log.py:11] This is a debug log
2017-06-06:17:07:02,158 INFO [log.py:12] This is an info log
2017-06-06:17:07:02,158 CRITICAL [log.py:13] This is critical
2017-06-06:17:07:02,158 ERROR [log.py:14] An error occurred
在模块中使用 logging
参考 《Python3 Cookbook》
"""
filename: somemodule.py
"""
import logging
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
def egg():
log.warning('RUN HERE')
运行:
$ python
>>> import egg
>>> import logging
>>> FORMAT = '%(levelname)-8s [%(filename)s:%(funcName)s:%(lineno)d] %(message)s'
>>> logging.basicConfig(format=FORMAT, level=logging.INFO)
>>> egg()
WARNING [somemodule.py:egg:13] RUN HERE
>>>
可以看到,如果使用 logging 来做 debug/info/warning/etc… 输出的话,只需要对 format 格式指定输出 %(funcName)s
就等效于 C语言的 __FUNCTION__
,指定 %(lineno)d
就等效于 C 语言的 __LINE__
,非常方便。
注:
-
在模块中使用了
log.addHandler(logging.NullHandler())
,意味着调用方如果没有配置(最小配置仅需 import 即可) logging,那么该模块内的log.<info|debug|warning|etc...>(...)
将不会输出。
(上面的使用示范是 import 了 logging,并且做了格式的配置。) -
模块的输出 level 和调用方一致(即默认
WARNING
及以上),由待用方控制;因为上面示范配置的level
为INFO
,所以有内容输出。