python 的日志用起来很简单:
主要牵涉到3个模块:
5个日志等级:
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. |
默认的是 WARNING
例子1:import logging
logging.warning('Watch out!') #会打印到控制台
logging.info('I told you so') # 什么也不打印
输出为:
WARNING:root:Watch out!
例子2:输出日志到文件
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
输出为(文件example.log的内容):
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
例子3:日志大小/文件数设置
import logging
import logging.handlers
import glob
LOG_FILENAME = 'logging_rotatingfile_example.out'
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(
LOG_FILENAME, maxBytes=20, backupCount=5)
my_logger.addHandler(handler)# Log some messages
for i in range(20):
my_logger.debug('i = %d' % i)
# See what files are created
logfiles = glob.glob('%s*' % LOG_FILENAME)
for filename in logfiles:
print(filename)
上面例子设置了单个日志最大文件大小20Byte,备份文件数为5个,也就时当前日志一个文件,和5个备份文件
-----------------------------
下一篇介绍logging日志格式的设定。。。
阅读(996) | 评论(0) | 转发(0) |