logging

日志的主要作用是程序调试、数据分析。 日志有五个级别,代表问题的严重程度

python有个日志相关的logging模块,用法:

输出到屏幕

import logging
logging.warning('Watch out!')  # 输出到屏幕
logging.info('I told you so')  # 不打印

因为logging模块默认的日志级别是warning,所以info级别的日志不会输出到屏幕。也就是说输出的日志级别要高于设置的日志级别才会输出日志

输出到文件

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'

将在'example.log' 日志文件中看到

DEBUG:root:This message should be go to the log file
INFO:root:So should this
WARNING:root:And this, too

定义日志格式

import logging
logging.warning('%s before you %s', 'Look', 'leap!')

会显示

WARNING:root:Look before you leap!

定义时间

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.

更多日志格式参考

多个输出目的地 (输出到屏幕和文件)

可以同时输出到文件和屏幕、或输出到多个文件,并且可以设置不同的级别,总之可以弄的很复杂。

一个同时输出日志到文件和控制台的例子

logger = logging.getLogger(__name__)   # 获取logger对象
logger.setLevel(logging.DEBUG)         # 设置全局的日志级别

# 创建基于控制台handler
console = logging.StreamHandler()
console.setLevel(logging.INFO)         # 设置控制台的日志级别

# 创建基于文件handler
fh = logging.FileHandler(log)
fh.setLevel(logging.WARNING)           # 设置日志文件级别

# 定义格式
formatter = logging.Formatter(
    '%(asctime)s  - %(levelname)s - %(lineno)d - %(filename)s - %(message)s')

# 应用格式 console.setFormatter(formatter) fh.setFormatter(formatter)
# 添加到logger logger.addHandler(console) logger.addHandler(fh)

这样日志文件和控制台都有日志:

2017-04-29 22:51:56,235  - ERROR - 30 - database.py - ORA-12170: TNS: 连接超时
2017-04-30 00:10:01,568  - ERROR - 30 - database.py - ORA-12170: TNS:Connect timeout occurred
2017-04-30 00:13:57,726  - ERROR - 30 - database.py - ORA-12170: TNS: 连接超时
2017-04-30 00:15:34,416  - ERROR - 30 - database.py - ORA-12170: TNS:Connect timeout occurred

 

posted @ 2017-04-30 15:16  opss  阅读(356)  评论(0编辑  收藏  举报