import logginglogging.warning('Watch out!')# will print a message to the consolelogging.info('I told you so')# will not print anything
上述没有指定输出到文件,则默认在终端输出。
日志记录到文件
import logginglogging.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')
注意:在日志文件中会同时记录日志级别,所以默认显示如下:
DEBUG:root:This message should go to the log file
INFO:root:So should this
WARNING:root:And this, too
如果希望通过命令行参数来设置日志级别,例如--log=INFO,则可以使用如下方法获取参数:
getattr(logging, loglevel.upper())
以下是一个案例:
# assuming loglevel is bound to the string value obtained from the# command line argument. Convert to upper case to allow the user to# specify --log=DEBUG or --log=debugnumeric_level =getattr(logging, loglevel.upper(), None)ifnotisinstance(numeric_level, int):raiseValueError('Invalid log level: %s'% loglevel)logging.basicConfig(level=numeric_level, ...)
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
日志格式
import logginglogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)logging.debug('This message should appear on the console')logging.info('So should this')logging.warning('And this, too')
在日志中显示时间
import logginglogging.basicConfig(format='%(asctime)s%(message)s')logging.warning('is when this event was logged.')
则日志如下:
2010-12-12 11:41:42,612 is when this event was logged.
默认时间格式是ISO8601,即类似如上。如果需要控制日期格式,可以使用basicconfig:
import logginglogging.basicConfig(format='%(asctime)s%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')logging.warning('is when this event was logged.')
则日志内容如下:
12/12/2010 11:46:36 AM is when this event was logged.
模块话日志
logging通过调用Logger累的方法来实现,所以创建logger对象:
logger = logging.getLogger(__name__)
配置Logging
import logging# create loggerlogger = logging.getLogger('simple_example')logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# add formatter to chch.setFormatter(formatter)# add ch to loggerlogger.addHandler(ch)# 'application' codelogger.debug('debug message')logger.info('info message')logger.warn('warn message')logger.error('error message')logger.critical('critical message')
import logginglogging.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')
日志中增加时间戳
import logginglogging.basicConfig(format='%(asctime)s%(message)s')logging.warning('is when this event was logged.')