基本用法
logger打印优先级如下
level | discription |
---|---|
DEBUG | Detailed information, typically of interest only when diagnosing problems. |
INFO | Confirmation that things are working as expected. |
WARNING | An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR | Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL | A serious error, indicating that the program itself may be unable to continue running. |
setLevel()函数可以更改logger的优先级。默认优先级为WARNING,意味着只有优先级不低于WARNING的消息才会被打印。
debug(),info(),warning,error(),critical()函数表示以DEBUG/INFO/WARNING/ERROR/CRITICAL等级来输出消息。
打印到控制台
示例如下:
import logging
def main():
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
if __name__ == '__main__':
main()
结果,只会在控制台打印
WARNING:root:And this, too
打印到文件
import logging
def main():
logging.basicConfig(filename='log.txt',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
if __name__ == '__main__':
main()
结果如下:
$ cat log.txt
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
多模块场景
main.py引用mylib模块。
main.py如下
import logging
import mylib
def main():
logging.basicConfig(filename='testlog.txt', level=logging.INFO)
#logging.basicConfig(filename='testlog.txt', level=logging.INFO, format='%(levelname)s:%(asctime)s:%(message)s', datefmt='%Y/%m/%d %I:%M:%S')
logging.info('Started')
mylib.do_something()
logging.info('Finished')
if __name__ == '__main__':
main()
mylib.py如下
import logging
def do_something():
logging.info('Hello, %s ', 'mylib')
结果如下:
Administrator@PublicPCfour ~
$ python3 main.py
Administrator@PublicPCfour ~
$ cat testlog.txt
INFO:root:Started
INFO:root:Hello, mylib
INFO:root:Finished
自定义log格式,添加日期时间
import logging
def main():
logging.basicConfig(filename='testlog.txt', level=logging.INFO, format='%(levelname)s:%(asctime)s:%(message)s', datefmt='%Y/%m/%d %I:%M:%S')
logging.info('Started')
logging.info('Finished')
if __name__ == '__main__':
main()
结果如下:
Administrator@PublicPCfour ~
$ python3 main.py
Administrator@PublicPCfour ~
$ cat testlog.txt
INFO:2019/08/13 12:43:24:Started
INFO:2019/08/13 12:43:24:Finished
高级用法
在模块中,常用方法是使用getLogger()来创建模块的logger。
logger = logging.getLogger(__name__)
logger配置方法有三种:
1)创建loggers,handlers, and formatters,使用setFormatter()函数将formatter绑定到handler,使用addHandler()将handler绑定到logger上.
2)创建配置文件,使用fileConfig()函数来加载配置。
3)创建配置的dict对象,通过dictConfig()函数来加载配置。
下面介绍前两种用法
使用方法1)
import logging
def main():
# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
if __name__ == '__main__':
main()
结果如下:
$ python3 testlog.py
2019-08-13 13:21:54,925 - simple_example - DEBUG - debug message
2019-08-13 13:21:54,925 - simple_example - INFO - info message
2019-08-13 13:21:54,935 - simple_example - WARNING - warn message
2019-08-13 13:21:54,935 - simple_example - ERROR - error message
2019-08-13 13:21:54,935 - simple_example - CRITICAL - critical message
将Handler的处理优先级修改为WARNING
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
结果如下:
$ python3 testlog.py
2019-08-13 13:23:27,551 - simple_example - WARNING - warn message
2019-08-13 13:23:27,551 - simple_example - ERROR - error message
2019-08-13 13:23:27,551 - simple_example - CRITICAL - critical message
使用方法2)
main.py如下:
import logging
import logging.config
def main():
logging.config.fileConfig('logging.conf')
# create logger
logger = logging.getLogger('simpleExample')
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
if __name__ == '__main__':
main()
logging.conf如下:
[loggers]
keys=root,simpleExample
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
结果如下:
$ python3 testlog.py
2019-08-13 13:49:03,070 - simpleExample - DEBUG - debug message
2019-08-13 13:49:03,070 - simpleExample - INFO - info message
2019-08-13 13:49:03,070 - simpleExample - WARNING - warn message
2019-08-13 13:49:03,070 - simpleExample - ERROR - error message
2019-08-13 13:49:03,070 - simpleExample - CRITICAL - critical message
将log输出到file filelog.txt中,修改logging.conf如下
[handler_consoleHandler]
class=FileHandler
level=DEBUG
formatter=simpleFormatter
args=('filelog.txt',)
运行main.py后,查看filelog.txt。其内容如下
$ cat filelog.txt
2019-08-13 14:01:26,052 - simpleExample - DEBUG - debug message
2019-08-13 14:01:26,052 - simpleExample - INFO - info message
2019-08-13 14:01:26,052 - simpleExample - WARNING - warn message
2019-08-13 14:01:26,052 - simpleExample - ERROR - error message
2019-08-13 14:01:26,052 - simpleExample - CRITICAL - critical message
使用配置文件控制logger的输出位置,优势在于,无需修改代码;同时维护简单。