Python logging 模块 捕获异常,并保存为 logging 文件

____tz_zs

 

logging模块简单使用 basicConfig

.

#!/usr/bin/python2.7
# -*- coding:utf-8 -*-

"""
@author:    tz_zs
"""
import logging
import time
import traceback
import sys

logging.basicConfig(level=logging.DEBUG,
                    format='asctime:        %(asctime)s \n'  # 时间
                           'filename_line:  %(filename)s_[line:%(lineno)d] \n'  # 文件名_行号
                           'level:          %(levelname)s \n'  # log级别
                           'message:        %(message)s \n',  # log信息
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    filename=sys.path[1] + '/output/test_try_logging.log',  # sys.path[1]获取当前的工作路径
                    # stream=sys.stdout,
                    filemode='w')  # 如果模式为'a',则为续写(不会抹掉之前的log)
i = 0
while i < 3:
    i += 1
    time.sleep(1)
    try:
        a = 1 / 0
    except ZeroDivisionError, e:
        # traceback.format_exc()为详细情况
        logging.debug("%s____%s\n"
                      "traceback.format_exc():____%s" % (ZeroDivisionError, e, traceback.format_exc()))
        continue
    except BaseException, e:
        logging.debug("%s____%s" % (BaseException, e))
        continue

 

·

 

log文件

asctime:        Mon, 02 Jul 2018 16:28:56 
filename_line:  test_try_logging.py_[line:31] 
level:          DEBUG 
message:        ____integer division or modulo by zero
traceback.format_exc():____Traceback (most recent call last):
  File "/home/zmate/PycharmProjects/ZM_Lab_AI_research/development/test/test_try_logging.py", line 27, in 
    a = 1 / 0
ZeroDivisionError: integer division or modulo by zero
 

asctime:        Mon, 02 Jul 2018 16:28:57 
filename_line:  test_try_logging.py_[line:31] 
level:          DEBUG 
message:        ____integer division or modulo by zero
traceback.format_exc():____Traceback (most recent call last):
  File "/home/zmate/PycharmProjects/ZM_Lab_AI_research/development/test/test_try_logging.py", line 27, in 
    a = 1 / 0
ZeroDivisionError: integer division or modulo by zero
 

asctime:        Mon, 02 Jul 2018 16:28:58 
filename_line:  test_try_logging.py_[line:31] 
level:          DEBUG 
message:        ____integer division or modulo by zero
traceback.format_exc():____Traceback (most recent call last):
  File "/home/zmate/PycharmProjects/ZM_Lab_AI_research/development/test/test_try_logging.py", line 27, in 
    a = 1 / 0
ZeroDivisionError: integer division or modulo by zero

·

参考文章:

  • python logging 日志配置

 

 

 

logging模块更多高级用法:


http://www.liujiangblog.com/course/python/71

1、日志级别

级别    级别数值    使用时机
DEBUG    10    详细信息,常用于调试。
INFO    20    程序正常运行过程中产生的一些信息。
WARNING    30    警告用户,虽然程序还在正常工作,但有可能发生错误。
ERROR    40    由于更严重的问题,程序已不能执行一些功能了。
CRITICAL    50    严重错误,程序已不能继续运行。
默认级别是WARNING,表示只有WARING和比WARNING更严重的事件才会被记录到日志内,低级别的信息会被忽略。

源码中等级的对应关系:

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

 

2、Python 的 logging 模块主要包括:

Loggers:记录器,提供应用程序代码能直接使用的接口;

Handlers:处理器,将记录器产生的日志发送至目的地;

Filters:过滤器,提供更好的粒度控制,决定哪些日志会被输出;

Formatters:格式化器,设置日志内容的组成结构和消息字段。

.

import logging


def log_client(file_name):
    # logging.basicConfig(level=logging.WARNING,
    #                     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
    #                     datefmt='%a, %d %b %Y %H:%M:%S',
    #                     # filename=sys.path[1] + '/output/log/get_market_quote_data_from_net.log',
    #                     filename='output/log/%s.log' % __file__.split("/")[-1].split(".")[0],
    #                     filemode='a')
    # 创建logger记录器
    logger = logging.getLogger(file_name)
    logger.setLevel(logging.DEBUG)
    # 创建handler处理器
    handler = logging.FileHandler(filename='output/log/%s.log' % file_name, mode='a')
    handler.setLevel(logging.WARNING)
    # 创建formatter格式化器
    formatter = logging.Formatter(fmt='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
    handler.setFormatter(formatter)
    # 添加handler
    logger.addHandler(handler)
    return logger

.

你可能感兴趣的:(#,综合)