python之打印日志logging

 

 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.

 

posted @ 2017-08-12 23:03  星瑞  阅读(2966)  评论(0编辑  收藏  举报