在Django中记录web服务请求

时间:2021-03-07 20:28:10

I have created a REST web service using Django. This web service has a log file. I'd like to log all web service (http) requests in the log file. However, the web service request handling is done by Django, I only setup url-request handlers mapping and create the request handlers (views in Django nomenclature). Is there a way to log all requests in a central point, without needing to log each request in its associated request handler (view)?

我已经使用Django创建了一个REST web服务。这个web服务有一个日志文件。我想在日志文件中记录所有web服务(http)请求。但是,web服务请求处理是由Django完成的,我只设置url请求处理程序映射并创建请求处理程序(Django命名法中的视图)。是否有一种方法可以将所有请求记录在一个中心点,而不需要在关联的请求处理程序(视图)中记录每个请求?

Thanks in advance.

提前谢谢。

1 个解决方案

#1


2  

Yes Django has a built in signals framework.

是的,Django有一个内置的信号框架。

It allows you to register a function to be called everytime a request starts.

它允许您在每次请求启动时注册要调用的函数。

This documenation page explains how to do it step by step

这个文档化页面解释了如何一步一步地完成它

Using the decorator method:

使用装饰方法:

from django.core.signals import request_started
from django.dispatch import receiver

@receiver(request_started)
def my_callback(sender, **kwargs):
    # log the request here
    pass

Where should this code live? You can put signal handling and registration code anywhere you like. However, you’ll need to make sure that the module it’s in gets imported early on so that the signal handling gets registered before any signals need to be sent. This makes your app’s models.py a good place to put registration of signal handlers.

这段代码应该放在哪里?您可以在任何您喜欢的地方放置信号处理和注册码。但是,您需要确保在早期导入它所在的模块,以便在需要发送任何信号之前注册信号处理。这是你的应用的模型。py是放置信号处理程序注册的好地方。

#1


2  

Yes Django has a built in signals framework.

是的,Django有一个内置的信号框架。

It allows you to register a function to be called everytime a request starts.

它允许您在每次请求启动时注册要调用的函数。

This documenation page explains how to do it step by step

这个文档化页面解释了如何一步一步地完成它

Using the decorator method:

使用装饰方法:

from django.core.signals import request_started
from django.dispatch import receiver

@receiver(request_started)
def my_callback(sender, **kwargs):
    # log the request here
    pass

Where should this code live? You can put signal handling and registration code anywhere you like. However, you’ll need to make sure that the module it’s in gets imported early on so that the signal handling gets registered before any signals need to be sent. This makes your app’s models.py a good place to put registration of signal handlers.

这段代码应该放在哪里?您可以在任何您喜欢的地方放置信号处理和注册码。但是,您需要确保在早期导入它所在的模块,以便在需要发送任何信号之前注册信号处理。这是你的应用的模型。py是放置信号处理程序注册的好地方。