bllendev / kalibre

ebook management django software - inspired by the original Calibre
https://kalibre-bllendev.herokuapp.com/
6 stars 0 forks source link

logging - setup middleware logging and exception handling #161

Closed bllendev closed 1 year ago

bllendev commented 1 year ago
  1. Implementing the Logging Decorator in Middleware Middleware in Django allows you to process requests and responses globally. You can implement the logging functionality in middleware rather than using decorators.

Here's how you can structure a middleware class to handle logging:


import logging

logger = logging.getLogger(__name__)

class LoggingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        logger.info(f"Entering view {request.path}")

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        logger.info(f"Exiting view {request.path}")

        return response

class LoggingMiddleware:
    ...

    def process_exception(self, request, exception):
        """Handle exceptions and log them."""
        logger.error(f"Exception occurred in view {request.path}: {str(exception)}")
        # If you return None, Django will continue processing 
        # this exception, so other middlewares' process_exception 
        # and the default exception handler will still execute.
        return None
bllendev commented 1 year ago

redundant logging, closing for now