1 import logging 2 3 4 # 簡單打印日志舉例 5 logging.basicConfig(level=logging.DEBUG) # 設置日志級別,WARN 6 logging.warning('Watch out!') # will print a message to the console 7 logging.info('I told you so') # will not print anything 8 9 10 # 打印日志到文件,注意要新起一個文件,否則不能保存文件 11 def log_to_file(logs_dir="D:\\test_data\\logs\\log_DEBUG.txt"): 12 logging.basicConfig(filename=logs_dir, level=logging.DEBUG) 13 logging.debug('This message should go to the log file') 14 logging.info('So should this') 15 logging.warning('And this, too') 16 17 18 log_to_file() 19 20 # 多參數日志 21 logging.warning('%s before you %s', 'Look', 'leap!') 22 23 # 日志中打印時間 24 logging.basicConfig(format='%(asctime)s %(message)s') 25 logging.warning('is when this event was logged.') 26 27 # 指定時間格式 28 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %I:%M:%S %p') 29 logging.warning('is when this event was logged.')
注意:logging的參數設置只在第一次運行之前有效,只能設置一次,后續設置無效。
指定時間格式運行結果:
1 # 指定時間格式 2 2017-08-12 10:47:07 PM is when this event was logged.