Django 1.2标准日志模块出现奇怪行为时的解决方案

news2024/10/10 4:47:57

在 Django 1.2 中,标准日志模块有时会出现意想不到的行为,例如日志消息未按预期记录、日志级别未正确应用或日志格式错乱等。这些问题可能源于日志配置不当、日志模块被多次初始化、或日志模块被其他包覆盖等原因。下面是一些常见问题的排查方法和解决方案。

在这里插入图片描述

1、问题背景

在 Django 1.2 中,使用标准日志模块记录信息时遇到了一个奇怪的问题。有时候它可以正常工作,而有时候它却无法记录信息。

2、解决方案

为了解决这个问题,我们采取了以下步骤:

  1. 首先,我们检查了代码结构。代码结构如下:
/mysite/ (Django root)
    my_logging.py (logging configuration)
    settings.py
    views.py (global views)
    data_objects.py (objects only containing data, similar to POJO)
    uploader/ (application)
        views.py (uploader views) --> This is where I have problems
  1. 接着,我们检查了 my_logging.py 的代码:
import logging
import logging.handlers
from django.conf import settings

is_initialized = False

def init_logger():
    """
    Initializes the logging for the application. Configure the root
    logger and creates the handlers following the settings. This function should
    not be used directly from outside the module and called only once.
    """
    # Create the logger
    server_logger = logging.getLogger()
    server_logger.setLevel(logging.DEBUG)

     # Set the logging format for files
    files_formatter = logging.Formatter(settings.LOGGING_FORMAT_FILE)

     # Rotating file handler for errors
    error_handler = logging.handlers.RotatingFileHandler(
        settings.LOGGING_ERROR_FILE,
        maxBytes=settings.LOGGING_ERROR_FILE_SIZE,
        backupCount=settings.LOGGING_ERROR_FILE_COUNT,
    )
    error_handler.setLevel(logging.WARNING)
    error_handler.setFormatter(files_formatter)

    # Rotating file handler for info
    info_handler = logging.handlers.RotatingFileHandler(
        settings.LOGGING_INFO_FILE,
        maxBytes=settings.LOGGING_INFO_FILE_SIZE,
        backupCount=settings.LOGGING_INFO_FILE_COUNT,
    )
    info_handler.setLevel(logging.INFO)
    info_handler.setFormatter(files_formatter)

    # Add the handlers to the logger
    server_logger.addHandler(info_handler)
    server_logger.addHandler(error_handler)

# Init once at first import
if not is_initialized:
    init_logger()
    is_initialized = True
  1. 然后,我们检查了 uploader/views.py 中的部分代码:
#...
import mysite.my_logging
import logging
#... 
# The messages in the following view are written correctly :
@login_required
def delete(request, file_id):
    """
    Delete the file corresponding to the given ID and confirm the deletion to
    the user.

    @param request: the HTTP request object
    @type request: django.http.HttpRequest
    @return: django.http.HttpResponse - the response to the client (html)
    """
    # Get the file object form the database and raise a 404 if not found
    f = get_object_or_404(VideoFile, pk=file_id)

    # TODO: check if the deletion is successful

    # Get the video directory
    dir_path = os.path.dirname(f.file.path)

    # Delete the file
    f.delete()

    try:
        # Delete the video directory recursively
        shutil.rmtree(dir_path)
        logging.info("File \"%(file)s\" and its directory have been deleted by %(username)s",{'file': f.title,'username': request.user.username})
        messages.success(request, _('The video file "%s" has been successfully deleted.') % f.title)
    except OSError:
        logging.warning("File \"%(id)d\" directory cannot be completely deleted. Some files may still be there.",{'id': f.id,})
        messages.warning(request, _("The video file \"%s\" has been successfully deleted, but not its directory. There should not be any problem but useless disk usage.") % f.title)

    return HttpResponseRedirect(reverse('mysite.uploader.views.list'))
#...
# The messages in the following view are NOT written at all:
@csrf_exempt
def get_thumblist(request,file_id):
    """
    This view can be called only by POST and with the id of a video
    file ready for the scene editor.

    @param request: the HTTP request object. Must have POST as method.
    @type request: django.http.HttpRequest
    @return: django.http.HttpResponse - the response to the client (json)
    """
    #TODO: Security, TEST

    logging.info("Demand of metadata for file %(id)d received.",{'id': file_id,})

    if request.method == 'POST':

        if file_id:

            # Get the video file object form the database and raise a 404 if not found
            vid = get_object_or_404(VideoFile, pk=file_id)

                # ...

                try:
                    # ... file operations
                except IOError:
                    logging.error("Error when trying to read index file for file %(id)d !",{'id': file_id,})
                except TypeError:
                    logging.error("Error when trying to parse index file JSON for file %(id)d !",{'id': file_id,})

                # ...

                logging.info("Returning metadata for file %(id)d.",{'id': file_id,})
                return HttpResponse(json,content_type="application/json")

            else:
                logging.warning("File %(id)d is not ready",{'id': file_id,})
                return HttpResponseBadRequest('file_not_ready')
        else:
            logging.warning("bad POST parameters")
            return HttpResponseBadRequest('bad_parameters')
    else:
        logging.warning("The GET method is not allowed")
        return HttpResponseNotAllowed(['POST'])
  1. 最后,我们检查了 settings.py 中的部分代码:
# ---------------------------------------
# Logging settings
# ---------------------------------------

#: Minimum level for logging messages. If logging.NOTSET, logging is disabled
LOGGING_MIN_LEVEL = logging.DEBUG

#: Error logging file path. Can be relative to the root of the project or absolute.
LOGGING_ERROR_FILE = os.path.join(DIRNAME,"log/error.log")

#: Size (in bytes) of the error files
LOGGING_ERROR_FILE_SIZE = 10485760 # 10 MiB

#: Number of backup error logging files
LOGGING_ERROR_FILE_COUNT = 5

#: Info logging file path. Can be relative to the root of the project or absolute.
LOGGING_INFO_FILE = os.path.join(DIRNAME,"log/info.log")

#: Size (in bytes) of the info files
LOGGING_INFO_FILE_SIZE = 10485760 # 10 MiB

#: Number of backup error info files
LOGGING_INFO_FILE_COUNT = 5

#: Format for the log files
LOGGING_FORMAT_FILE = "%(asctime)s:%(name)s:%(levelname)s:%(message)s"
  1. 通过对以上代码的检查,我们发现问题出现在 uploader/views.py 中的 get_thumblist 函数中。该函数中使用 logging.info('Demand of metadata for file %(id)d received.') 语句记录信息,但由于没有使用 logger 对象,导致信息没有被记录下来。

  2. 为了解决这个问题,我们将 get_thumblist 函数中的 logging.info('Demand of metadata for file %(id)d received.') 语句改为 logger.info('Demand of metadata for file %(id)d received.'),其中 logger 是一个 logging.getLogger() 函数返回的日志对象。

  3. 修改后的代码如下:

#...
import mysite.my_logging
import logging
logger = logging.getLogger('MySite.views')
#... 
# The messages in the following view are written correctly :
@login_required
def delete(request, file_id):
    """
    Delete the file corresponding to the given ID and confirm the deletion to
    the user.

    @param request: the HTTP request object
    @type request: django.http.HttpRequest
    @return: django.http.HttpResponse - the response to the client (html)
    """
    # Get the file object form the database and raise a 404 if not found
    f = get_object_or_404(VideoFile, pk=file_id)

    # TODO: check if the deletion is successful

    # Get the video directory
    dir_path = os.path.dirname(f.file

以上方法可以帮助解决 Django 1.2 中标准日志模块的异常行为问题。通过合理配置和调整日志模块,可以确保日志记录功能稳定、可靠地运行。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2201024.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

力扣21~25题

21题(简单): 分析: 按要求照做就好了,这种链表基本操作适合用c写,python用起来真的很奇怪 python代码: # Definition for singly-linked list. # class ListNode: # def __init__(self, v…

二、MySQL的数据目录

文章目录 1. MySQL8的主要目录结构1.1 数据库文件的存放路径1.2 相关命令目录1.3 配置文件目录 2. 数据库和文件系统的关系2.1 查看默认数据库2.2 数据库在文件系统中的表示2.3 表在文件系统中的表示2.3.1 InnoDB存储引擎模式2.3.2 MyISAM存储引擎模式 2.4 小结 1. MySQL8的主要…

宝塔docker中如何修改应用配置文件参数

今天在宝塔docker安装了kkfileview,相修改应用里的application.properties,却找不到在哪,如何修改? 下面教大家应用找文件修改。 docker安装好对应容器后,是这样 在这里是找不到对应修改的地方,其实docker…

Linux WIFI 驱动实验

直接参考【正点原子】I.MX6U嵌入式Linux驱动开发指南V1.81 本文仅作为个人笔记使用,方便进一步记录自己的实践总结。 WIFI 的使用已经很常见了,手机、平板、汽车等等,虽然可以使用有线网络,但是有时候很多设备存在布线困难的情况&…

Windows10的MinGW安装和VS Code配置C/C++编译环境

1. MinGW下载安装 首先需要说明的是VS Code是一个编辑器,而不是编译器。‌ 编辑器和编译器是有很明显的区别 1.1 编辑器和编译器区别 编辑器‌是一种用于编写和编辑文本的应用软件,主要用于编写程序的源代码。编辑器提供基本的文本编辑功能,…

面试题:Redis(三)

1. 面试题 背景 问题,上面业务逻辑你用java代码如何写? 2. 缓存双写一致性谈谈你的理解? 3. 双检加锁策略 多个线程同时去查询数据库的这条数据,那么我们可以在第一个查询数据的请求上使用一个 互斥锁来锁住它。 其他的线程走到这…

内核编译 设备驱动 驱动程序

内核编译 一、内核编译的步骤 编译步骤: (linux 内核源码的顶层目录下操作 ) 1. 拷贝默认配置到 .config cp config_mini2440_td35 .config 2. make menuconfig 内核配置 make menuconfig 3. make uImage make u…

docker-compose无法切换用户

问题描述 jupyter:image: flink:1.19-pyprivileged: trueuser: rootports:- "9999:8888"volumes:- /data/docker_data/jupyter:/workcommand: sh -c "cd / && jupyter notebook --ip 0.0.0.0 --port 8888 --allow-root --NotebookApp.passwordsha1:658…

循环神经网络-LSTM网络

文章目录 前言一、LSTM网络简介二、LSTM的门结构1.遗忘门2.输入门3.输出门 三、总结 前言 循环神经网络(Recurrent Neural Networks,RNN)是一种特殊的神经网络,具有能够处理序列数据的能力,然而,RNN在处理…

团员申请书怎么写?这里归纳了一些模板

团员申请书怎么写?随着社会的快速发展和时代的进步,越来越多的青年人意识到加入团组织的重要性。作为新时代的青年,我们应当积极响应国家的号召,参与到团组织的建设中来。而想要成为共青团员,首先需要撰写一份规范的团…

新手一次过软考高级(系统架构设计师)秘笈,请收藏!

软考系统架构设计师是高级科目之一,也是比较有难度的科目,但是只要你把该掌握的知识掌握熟练,技能水平达到要求,那还是考可以拿下证书的。 系统架构设计师适合人群:适合熟悉开发过程与方法、数据库、信息安全的技术人员…

NLP: SBERT介绍及sentence-transformers库的使用

1. Sentence-BERT Sentence-BERT(简写SBERT)模型是BERT模型最有趣的变体之一,通过扩展预训练的BERT模型来获得固定长度的句子特征,主要用于句子对分类、计算两个句子之间的相似度任务。 1.1 计算句子特征 SBERT模型同样是将句子标记送入预训练的BERT模型…

OmniH2O——通用灵巧且可全身远程操作并学习的人形机器人(其前身H2O是HumanPlus的重要参考)

前言 由于我司一直在针对各个工厂、公司、客户特定的业务场景,做解决方案或定制开发,所以针对每一个场景,我们都会反复考虑用什么样的机器人做定制开发 于此,便不可避免的追踪国内外最前沿的机器人技术进展,本来准备…

数据库管理-第249期 23ai:全球分布式数据库-请求路由与查询过程(20241008)

数据库管理249期 2024-10-08 数据库管理-第249期 23ai:全球分布式数据库-请求路由与查询过程(20241008)1 客户端应用请求路由1.1 分片键1.2 Oracle连接驱动 2 查询过程和查询协调器2.1 指定一致性级别2.2 高可用与性能 总结 数据库管理-第249…

拍立淘API接口以图搜商品列表功能实现技术分享item_search_img|返回商品列表商品id商品价格url

开发背景 在电商平台的快速发展中,用户对于商品搜索的效率和准确性提出了越来越高的要求。传统的基于关键词的搜索方式,虽然在一定程度上满足了用户的需求,但在面对复杂的商品信息和多样化的用户搜索意图时,仍存在诸多局限性。为…

PyTorch搭建GNN(GCN、GraphSAGE和GAT)实现多节点、单节点内多变量输入多变量输出时空预测

目录 I. 前言II. 数据集说明III. 模型3.1 GCN3.2 GraphSAGE3.3 GAT IV. 训练与测试V. 实验结果 I. 前言 前面已经写了很多关于时间序列预测的文章: 深入理解PyTorch中LSTM的输入和输出(从input输入到Linear输出)PyTorch搭建LSTM实现时间序列…

IO相关,标准输入输出及错误提示

一、IO简介 1.1 IO的过程 操作系统的概念:向下统筹控制硬件,向上为用户提供接口。 操作系统的组成 内核 外壳(shell) linux的五大功能:进程管理、内存管理、文件管理、设备管理、网络管理。 最早接触的IO&#xf…

01背包,CF 1974E - Money Buys Happiness

目录 一、题目 1、题目描述 2、输入输出 2.1输入 2.2输出 3、原题链接 二、解题报告 1、思路分析 2、复杂度 3、代码详解 一、题目 1、题目描述 2、输入输出 2.1输入 2.2输出 3、原题链接 1974E - Money Buys Happiness 二、解题报告 1、思路分析 问我们能够到达…

docker简述

1.安装dockers,配置docker软件仓库 安装,可能需要开代理,这里我提前使用了下好的包安装 启动docker systemctl enable --now docker查看是否安装成功 2.简单命令 拉取镜像,也可以提前下载使用以下命令上传 docker load -i imag…

深度学习笔记(持续更新)

注:本文所有深度学习内容都是基于PyTorch,PyTorch作为一个开源的深度学习框架,具有可以动态计算图、拥有简洁易用的API、支持GPU加速等特点,在计算机视觉、自然语言处理、强化学习等方面有广泛应用。 使用matplotlib绘图&#xff…