python之打印日誌logging
阿新 • • 發佈:2017-08-13
gin print 單打 imp inf 多參數 level 簡單 pytho
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.
python之打印日誌logging