import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
上述没有指定输出到文件,则默认在终端输出。
日志记录到文件
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')
注意:在日志文件中会同时记录日志级别,所以默认显示如下:
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=debug
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level, ...)
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
日志格式
import logging
logging.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 logging
logging.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 logging
logging.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.
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')
日志中增加时间戳
import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')