A middleware to log the requests and responses using loguru.

Related tags

Django django-loguru
Overview

Django Loguru

The extension was based on another one and added some extra flavours. One of the biggest problems with the apps is the logging and that can be messy sometimes.

Since this serves as a middleware, it only depends on django (including django rest framework).

Documentation: https://tarsil.github.io/django-loguru/

Table of Contents


  1. Requirements
  2. Installation
  3. Settings
  4. License

Requirements

  1. Python >= 3.7
  2. Django >= 3.1

Installation

  • pip install django-loguru
  • Add django_loguru to INSTALLED_APPS settings.
INSTALLED_APPS = [
    ...
    'django_loguru'
]
  • Add DJANGO_LOGURU_MIDDLEWARE to your settings.
{time} {message} ", 'LOG_USER': False } ">
DJANGO_LOGGING_MIDDLEWARE = {
    'DEFAULT_FORMAT': True,
    'MESSAGE_FORMAT': "
    
     {time}
     
    
     {message}
    ",
    'LOG_USER': False
}
  • Add django_loguru.middleware.DjangoLoguruMiddleware as the very last in the list of MIDDLEWARE.

The logs should be now activated for every request/response of you application.

If you desire to override what is shown on the screen.

from django_loguru.middleware import DjangoLoguruMiddleware

class MyCustomMiddleware(DjangoLoguruMiddleware):

    def __call__(self, request):
        """
        Code to be executed on every request/response call.
        """
        logger.info(f"URL: {request.get_raw_uri()}")
        logger.info(f"Method: {request.method}")
        ...
        ...

Settings

  1. DEFAULT_FORMAT - Default True and it will use the default MESSAGE_FORMAT.
  2. MESSAGE_FORMAT - Sets the format of the log messages. Defaults to {time} {message} . More information about your options on loguru docs.
  3. LOG_POST - Default to False and it won't show POST data.
  4. LOG_PUT - Default to False and it won't show PUT data.
  5. LOG_PATCH - Default to False and it won't show PATCH data.
  6. LOG_DELETE - Default to False and it won't show DELETE data.
  7. LOG_USER - Default to True and tells which user did the request/response.

License

MIT-License

You might also like...
A simple Blog Using Django Framework and Used IBM Cloud Services for Text Analysis and Text to Speech

ElhamBlog Cloud Computing Course first assignment. A simple Blog Using Django Framework and Used IBM Cloud Services for Text Analysis and Text to Spee

Simple API written in Python using FastAPI to store and retrieve Books and Authors.

Simple API made with Python FastAPI WIP: Deploy in AWS with Terraform Simple API written in Python using FastAPI to store and retrieve Books and Autho

A django model and form field for normalised phone numbers using python-phonenumbers

django-phonenumber-field A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonen

Quick example of a todo list application using Django and HTMX
Quick example of a todo list application using Django and HTMX

django-htmx-todo-list Quick example of a todo list application using Django and HTMX Background Modified & expanded from https://github.com/jaredlockh

A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a unique id.

Django-URL-Shortener A beginner django project and also my first Django project which involves shortening of a longer URL into a short one using a uni

A django model and form field for normalised phone numbers using python-phonenumbers

django-phonenumber-field A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonen

Basic Form Web Development using Python, Django and CSS

thebookrain Basic Form Web Development using Python, Django and CSS This is a basic project that contains two forms - borrow and donate. The form data

Vehicle registration using Python, Django and SQlite3

PythonCrud Cadastro de veículos utilizando Python, Django e SQlite3 Para acessar o deploy no Heroku:

A ToDO Rest API using Django, PostgreSQL and Docker

This Rest API uses PostgreSQL, Docker and Django to implements a ToDo application.

Comments
  • AttributeError: 'WSGIRequest' object has no attribute 'get_raw_uri'

    AttributeError: 'WSGIRequest' object has no attribute 'get_raw_uri'

    After the installation and setup of this addon I've try to visit my /admin page and got an error:

    Internal Server Error: /admin/
    Traceback (most recent call last):
      File ".../lib/python3.10/site-packages/django/core/handlers/exception.py", line 47,
            in inner response = get_response(request)
      File ".../lib/python3.10/site-packages/django_loguru/middleware.py", line 25,
            in __call__ logger.info(f"URL: {request.get_raw_uri()}")
    AttributeError: 'WSGIRequest' object has no attribute 'get_raw_uri'
    

    UPDATED

    As far as I investigate the issue, I found the news in Django 4.0 Deprecated Features:

    The undocumented HttpRequest.get_raw_uri() method is removed. The HttpRequest.build_absolute_uri() method may be a suitable alternative.

    Well, I fixed line 25 and changed get_raw_uri to build_absolute_uri. Then I saw a next Error Traceback:

    Internal Server Error: /admin/
    Traceback (most recent call last):
      File ...lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner
        response = get_response(request)
      File ".../lib/python3.10/site-packages/django_loguru/middleware.py", line 29, in __call__
        logger.info(f"Data: {request.method.GET}")
    AttributeError: 'str' object has no attribute 'GET'
    

    Seems reasonable, because according to docs HttpRequest.method is a string type. Propably HttpRequest.GET was meant there. Which is returns QueryDict.

    I corrected lines 28-41 to my liking, but I don't know what the author would like to put there. Therefore, I did not create a Pull Request, limiting myself to this comment.

    opened by trankov 2
Owner
Tiago Silva
Entrepreneur, fully minded and dedicated software engineer with strong backend background and leadership skills.
Tiago Silva
Django-fast-export - Utilities for quickly streaming CSV responses to the client

django-fast-export Utilities for quickly streaming CSV responses to the client T

Matthias Kestenholz 4 Aug 24, 2022
Django Persistent Filters is a Python package which provide a django middleware that take care to persist the querystring in the browser cookies.

Django Persistent Filters Django Persistent Filters is a Python package which provide a django middleware that take care to persist the querystring in

Lorenzo Prodon 2 Aug 5, 2022
A simple Django middleware for Duo V4 2-factor authentication.

django-duo-universal-auth A lightweight middleware application that adds a layer on top of any number of existing authentication backends, enabling 2F

Adam Angle 1 Jan 10, 2022
Inject an ID into every log message from a Django request. ASGI compatible, integrates with Sentry, and works with Celery

Django GUID Now with ASGI support! Django GUID attaches a unique correlation ID/request ID to all your log outputs for every request. In other words,

snok 300 Dec 29, 2022
With Django Hijack, admins can log in and work on behalf of other users without having to know their credentials.

Django Hijack With Django Hijack, admins can log in and work on behalf of other users without having to know their credentials. Docs 3.x docs are avai

null 1.2k Jan 5, 2023
Yet another Django audit log app, hopefully the simplest one.

django-easy-audit Yet another Django audit log app, hopefully the easiest one. This app allows you to keep track of every action taken by your users.

Natán 510 Jan 2, 2023
Django GUID attaches a unique correlation ID/request ID to all your log outputs for every request.

Django GUID Now with ASGI support! Django GUID attaches a unique correlation ID/request ID to all your log outputs for every request. In other words,

snok 300 Dec 29, 2022
Book search Django web project that uses requests python library and openlibrary API.

Book Search API Developer: Vladimir Vojtenko Book search Django web project that uses requests python library and openlibrary API. #requests #openlibr

null 1 Dec 8, 2021
A prettier way to see Django requests while developing

A prettier way to see Django requests while developing

Adam Hill 35 Dec 2, 2022
Stream Framework is a Python library, which allows you to build news feed, activity streams and notification systems using Cassandra and/or Redis. The authors of Stream-Framework also provide a cloud service for feed technology:

Stream Framework Activity Streams & Newsfeeds Stream Framework is a Python library which allows you to build activity streams & newsfeeds using Cassan

Thierry Schellenbach 4.7k Jan 2, 2023