python的logging模块输出error日志的堆栈信息

  • Post author:
  • Post category:python


1、logging error日志常规用法

import sys
import threading
import time
import logging
from logging.handlers import TimedRotatingFileHandler
import os
import shutil

if os.path.exists("./logs"):
    shutil.rmtree("./logs")
os.makedirs("./logs")


def init_log():
    logger = logging.getLogger()
    handler = TimedRotatingFileHandler(filename=os.path.join("./logs", "test.log"), when="MIDNIGHT")
    console_handler = logging.StreamHandler()
    handler.setLevel(logging.DEBUG)
    console_handler.setLevel(logging.DEBUG)
    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(process)d - %(thread)d - %(filename)s - %(funcName)s - %(lineno)d - %(message)s')
    handler.setFormatter(logging_format)
    console_handler.setFormatter(logging_format)
    logger.addHandler(handler)
    logger.addHandler(console_handler)
    logger.setLevel(logging.DEBUG)


init_log()
logger = logging.getLogger()

try:
    x = 1.0 / 0
except Exception as e:
    logger.error(e)

输出结果如下:


2020-11-26 10:14:51,036 – ERROR – 14704 – 12544 – logger_error.py – <module> – 40 – float division by zero

通过上述结果可以知道是发生了除零异常,具体是那段代码,还需要找一找。

2、logging error日志输出异常堆栈信息

import sys
import threading
import time
import logging
from logging.handlers import TimedRotatingFileHandler
import os
import shutil

if os.path.exists("./logs"):
    shutil.rmtree("./logs")
os.makedirs("./logs")


def init_log():
    logger = logging.getLogger()
    handler = TimedRotatingFileHandler(filename=os.path.join("./logs", "test.log"), when="MIDNIGHT")
    console_handler = logging.StreamHandler()
    handler.setLevel(logging.DEBUG)
    console_handler.setLevel(logging.DEBUG)
    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(process)d - %(thread)d - %(filename)s - %(funcName)s - %(lineno)d - %(message)s')
    handler.setFormatter(logging_format)
    console_handler.setFormatter(logging_format)
    logger.addHandler(handler)
    logger.addHandler(console_handler)
    logger.setLevel(logging.DEBUG)


init_log()
logger = logging.getLogger()

try:
    x = 1.0 / 0
except Exception as e:
    logger.error(e, exc_info=True, stack_info=True)

输出结果如下:

2020-11-26 10:17:08,394 - ERROR - 8712 - 12292 - logger_error.py - <module> - 40 - float division by zero
Traceback (most recent call last):
  File "C:/WorkDir/PythonWorkspace/PythonModule/python_logging/logger_error.py", line 38, in <module>
    x = 1.0 / 0
ZeroDivisionError: float division by zero
Stack (most recent call last):
  File "C:/WorkDir/PythonWorkspace/PythonModule/python_logging/logger_error.py", line 40, in <module>
    logger.error(e, exc_info=True, stack_info=True)

通过堆栈信息很容易就能定位到出现异常的代码段。



版权声明:本文为cxx654原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。