首页 > 编程语言 >python logger 使用记录

python logger 使用记录

时间:2024-07-08 16:43:15浏览次数:10  
标签:info exception logging exc 记录 python import logger

1. 简单使用

import logging

# 基本设置
# 如果没有设置,则可以使用该设置用于显示
logging.basicConfig(level='DEBUG', datefmt='%Y-%m-%d %H:%M:%S',
                    format='%(asctime)s [%(name)s] %(levelname)s %(message)s')


logger = logging.getLogger('simple_use')

2. 为所有 logger 设置 level

2.1. 使用 disable
import logging

# 关闭所有 INFO 以及 INFO 以下的日志输出
logging.disable(logging.INFO)

# 取消上面的设置
logging.disable(logging.NOTSET)

2.2. 使用 root
import logging

logging.root.setLevel(logging.INFO)

设置 rootlogger 会影响到所有继承的 logger(基本代表了所有的 logger)。


2.3. 参考

Set global minimum logging level across all loggers in Python/Django - Stack Overflow


3. 错误信息追踪

3.1. exc_info 参数解释

关于 logger 的记录方法都带有参数 exc_info,该值默认为空,可为布尔值。官方解释为:

If exc_info does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) or an exception instance is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.

对于 sys.exc_info() 的解释为:

This function returns a tuple of three values that give information about the exception that is currently being handled. The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, “handling an exception” is defined as “executing an except clause.” For any stack frame, only information about the exception being currently handled is accessible.

If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback). Their meaning is: type gets the type of the exception being handled (a subclass of BaseException); value gets the exception instance (an instance of the exception type); traceback gets a traceback object which encapsulates the call stack at the point where the exception originally occurred.

简单来说,就是默认从当前环境的栈中自动读取(如果有错误),该方法会返回一个包含三个元素的元组,如果没有错误,三个元素皆为 None ;如果有则依次为:错误类型,错误对象,错误追踪对象。
比如:

import logging
import sys

try:
    1 / 0
except ZeroDivisionError:
    print(sys.exc_info())

输出为:

(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x000001A0FEE53608>)

如果该参数为 True,模块会自动调用 sys.exc_info() 方法获取错误信息,但有时候我们需要手动传入错误信息记录,因此,也可自己构造 exc_info 参数所需的信息,比如:

import logging

logging.basicConfig(level='DEBUG', datefmt='%Y-%m-%d %H:%M:%S',
                    format='%(asctime)s [%(name)s] %(levelname)s %(message)s')

try:
    1 / 0
except ZeroDivisionError as e:
    err = ValueError('The denominator cannot be 0!')
    logging.info('division wrong: ', 
                 exc_info=(ValueError, err, e.__traceback__))

输出为:

2020-10-21 15:19:28 [root] INFO division wrong: 
Traceback (most recent call last):
  File "D:/OneDrive/works-tmp/gyyenterprise/gyyspider/spiders/products/hc.py", line 13, in <module>
    1 / 0
ValueError: The denominator cannot be 0!

当然,如果不需要自定义错误信息,也可使用 logging.execption(e) 方法将捕获的错误传入直接记录。


4. 带有文件和屏幕双向输出的 logger

自定义格式(加入自定义的参数)- 文件和屏幕的双向输出:

import logging
import os
import time
import weakref

from lzz.settings import BASE_DIR

_handlers = weakref.WeakValueDictionary()


log_fmt = '%(asctime)s [%(name)s] %(levelname)s %(message)s'
date_fmt = '%Y-%m-%d %H:%M:%S'


def get_logger(name, level='DEBUG', folder=None, filename_fmt=None):
    formatter = logging.Formatter(
        fmt=log_fmt,
        datefmt=date_fmt,
    )
    logger = logging.getLogger(name)
    logger.setLevel(level)
    if 'stream' not in _handlers:
        stream = logging.StreamHandler()
        stream.setFormatter(formatter)
        _handlers['stream'] = stream
    logger.addHandler(_handlers['stream'])

    if folder:
        if 'file' not in _handlers:
            par = os.path.join(BASE_DIR, r'logs\upload\{}'.format(folder))
            if not os.path.exists(par):
                os.makedirs(par)
            filename = f"{time.strftime(filename_fmt or '%Y%m%d')}.log"
            path = os.path.join(par, filename)
            file_handler = logging.FileHandler(filename=path, encoding='utf-8')
            _handlers['file'] = file_handler
        logger.addHandler(_handlers['file'])

    return logger

5. 参考

  1. Python logging同时输出到屏幕和文件
  2. 如何添加自定义字段到Python日志格式字符串?
  3. python logging模块使用教程
  4. traceback --- Print or retrieve a stack traceback — Python 3.7.3 文档
  5. 模块 logging --- Python 的日志记录工具 — Python 3.7.3 文档

标签:info,exception,logging,exc,记录,python,import,logger
From: https://www.cnblogs.com/kingron/p/18290266

相关文章

  • 【融合ChatGPT等AI模型】Python-GEE遥感云大数据分析、管理与可视化及多领域案例实践
    随着航空、航天、近地空间遥感平台的持续发展,遥感技术近年来取得显著进步。遥感数据的空间、时间、光谱分辨率及数据量均大幅提升,呈现出大数据特征。这为相关研究带来了新机遇,但同时也带来巨大挑战。传统的工作站和服务器已无法满足大区域、多尺度海量遥感数据处理需求。为解......
  • Python热门面试题三
    Python中的pass语句有什么作用?在Python中,pass语句是一个空操作(NOP,nooperation);它什么也不做,只作为一个占位符。其主要作用是在语法上需要语句的地方,但程序执行时又不需要执行任何操作时使用。pass语句可以用在函数的定义中、条件语句的分支里、循环结构中或者任何需要语......
  • 利用Python进行数据分析PDF下载经典数据分享推荐
    本书由Pythonpandas项目创始人WesMcKinney亲笔撰写,详细介绍利用Python进行操作、处理、清洗和规整数据等方面的具体细节和基本要点。第2版针对Python3.6进行全面修订和更新,涵盖新版的pandas、NumPy、IPython和Jupyter,并增加大量实际案例,可以帮助你高效解决一系列数据分析问题。......
  • Elasticsearch:Node.js ECS 日志记录 - Pino
    在我的上一篇文章“Beats:使用Filebeat从Python应用程序中提取日志”里,我详述了如何使用Python来生成日志,并使用Filebeat来收集日志到Elasticsearch中。在今天的文章中,我来详细描述如何使用Node.js来生成ECS相兼容的日子。ECS相兼容的日志符合易于Elasticsear......
  • python+anaconda环境搭建
    一:下载安装1、安装anacondaanaconda官网2、安装pycharmpycharm官网二:配置环境1、找到anaconda安装位置在系统环境变量中添加如下信息打开DOS框,输入conda--version,出现如下信息说明配置成功三:创建虚拟环境1、打开DOS框;输入(name表示自己虚拟环境的名称;version表示......
  • python爬虫——爬取12306火车票信息
    前提准备:requests、pandas、threading等第三方库的导入(未下载的先进行下载)导入库代码fromthreadingimportThread#多线程库importrequestsimportpandasaspdimportjson#json库完整步骤1.在网页找到需要的数据(1)任意输入出发地——目的地——日期,点击......
  • 大意了,数据库数据无了,记录一下通过ibdata1恢复数据的过程
    前言最近在做自己的个人博客,然后有一个功能是记录每天发表的文章数量,结果当天发布的文章却没有记录到,因为我部署java到docker时添加文章也会造成时间会少8小时,马上联想到了是docker的mysql容器的时区问题,从网上找了修改容器内的时区,为了一劳永逸,直接把容器删了重新设置时区,结......
  • python:使用matplotlib库绘制图像(一)
    作者是跟着http://t.csdnimg.cn/4fVW0学习的,matplotlib系列文章是http://t.csdnimg.cn/4fVW0的自己学习过程中整理的详细说明版本,对小白更友好哦!一、Matplotlib图像基础1.1 基本绘图实例:sin、cos函数图代码详解:1.frompylabimport*:导入pylab库中所有函数和变量。pyla......
  • 人脸识别与美颜算法实战:基于Python、机器学习与深度学习
    代码和pdf书等:GitHub-guozhe1992/read引言与基础知识:介绍人脸识别与美颜算法的基本概念、应用场景以及Python编程和机器学习的基础知识。视频图像处理技术:详细讲解基于Anaconda和PyCharm的环境搭建,以及视频图像处理的基础技术,如图像读取、显示、保存和格式转换等。抖音特效......
  • python模型文件转换,将.pth转换为.onnx
    为了方便在C#项目中引用onnx文件,于是需要将pth模型文件转换为onnx类型。转换的模型项目地址是:https://github.com/xuebinqin/U-2-Net,以下为python的示例代码:1importtorch2importsys3importos4model_dir=os.path.join(os.path.dirname(__file__),'model')5sys......