import logging logging.warning('Watch out!') logging.info('I told you so') # will not print anything
1
WARNING:root:Watch out!
Logging to a file
主要说明如何将日志打印到文件中,以及如何刷新日志(不保留原有的日志).
1 2 3 4 5 6 7 8
import logging # set filename and log level logging.basicConfig(filename='example.log',level=logging.DEBUG) # If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the filemode argument, # logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG) logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too')
Logging variable data
主要说明日志输出是可以使用变量的
1 2
import logging logging.warning('%s before you %s', 'Look', 'leap!')
Changing the format of displayed messages
主要说明如何改变日志输出格式以及是时间输出格式如何改变
1 2 3 4 5 6 7 8 9 10
import logging # you can use 'format=' to formulate what you want output 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')
# detefmt can formulate format of date logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') logging.warning('is when this event was logged.')