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

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)

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

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python logging模块是一个非常强大的日志记录模块,可以帮助你记录程序运行时产生的各种日志信息。下面是Python logging的一些用法: #### 1. 基本用法 使用Python logging最基本的方法是使用`logging`模块中的`basicConfig()`方法,来配置日志记录器的格式和级别: ```python import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(message)s') ``` 在这个例子中,我们指定了日志记录器的级别为DEBUG,格式为`%(asctime)s %(levelname)s:%(message)s`。使用`basicConfig()`方法只需要在程序开始时调用一次即可。 如果你想记录某一级别以上的日志信息,可以将`level`参数设置为相应级别,例如`logging.WARNING`、`logging.ERROR`等。 #### 2. 记录日志 使用Python logging模块记录日志非常简单,只需要调用相应级别的方法即可,例如: ```python logging.debug('Debugging information') logging.info('Informational message') logging.warning('Warning') logging.error('Error occurred') logging.critical('Critical error') ``` #### 3. 使用不同的日志记录器 在一个Python程序中,你可以使用不同的日志记录器来记录不同的日志信息。例如,你可以为某一个模块或者某一部分程序代码使用一个独立的日志记录器,这样可以更好地管理日志信息。 ```python import logging logger1 = logging.getLogger('module1') logger2 = logging.getLogger('module2') logger1.debug('Debugging information') logger2.error('Error occurred') ``` 在这个例子中,我们为两个不同的模块创建了两个不同的日志记录器,分别是`logger1`和`logger2`。然后,我们分别使用这两个日志记录器来记录不同的日志信息。 #### 4. 日志输出到文件 除了将日志输出到控制台,你还可以将日志输出到文件中。使用Python logging模块输出日志到文件也非常简单,只需要将`basicConfig()`方法中的`filename`参数设置为你想要输出日志的文件名即可: ```python import logging logging.basicConfig(filename='example.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(message)s') logging.debug('Debugging information') ``` 在这个例子中,我们将日志输出到了名为`example.log`的文件中。 #### 5. 记录异常信息 当程序遇到异常时,你可以使用Python logging模块来记录异常信息,例如: ```python import logging try: # 这里是你的程序代码 pass except Exception as e: logging.exception("Exception occurred") ``` 在这个例子中,我们使用`logging.exception()`方法来记录异常信息,这个方法会记录完整的异常堆栈信息,非常方便排查问题。 #### 6. 使用日志回滚 当日志文件变得过大时,你可能需要使用日志回滚来分割日志文件。Python logging模块提供了多种日志回滚方式,例如按文件大小回滚、按时间回滚等。 ```python import logging from logging.handlers import RotatingFileHandler handler = RotatingFileHandler('example.log', maxBytes=10000, backupCount=5) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s:%(message)s', handlers=[handler]) ``` 在这个例子中,我们使用`RotatingFileHandler`来实现按文件大小回滚日志。`maxBytes`参数指定了每个日志文件的最大大小(这里是10KB),`backupCount`参数指定了最多保存多少个回滚日志文件(这里是5个)。 #### 7. 配置日志记录器 你可以使用Python logging模块中的`Logger`类来创建和配置日志记录器,例如: ```python import logging logger = logging.getLogger('my_logger') logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s %(levelname)s:%(message)s') file_handler = logging.FileHandler('my.log') file_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.debug('Debugging information') ``` 在这个例子中,我们使用`getLogger()`方法创建了一个名为`my_logger`的日志记录器,然后通过`setLevel()`方法来设置日志记录器的级别为DEBUG。接着,我们使用`Formatter`类来定义日志的格式,然后创建了一个`FileHandler`来将日志输出到`my.log`文件中,并使用`setFormatter()`方法来设置日志的格式。最后,我们使用`addHandler()`方法将`FileHandler`添加到`my_logger`日志记录器中,从而实现了将日志输出到文件中。 以上就是Python logging模块的一些基本用法,你可以根据需要来选择和使用相应的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值