Login

Logging Middleware

Author:
Magus
Posted:
September 28, 2007
Language:
Python
Version:
.96
Score:
8 (after 8 ratings)

This is a simple Logging Middleware that uses the python logging functions.

Simply drop this snippet in a file in your project such as logmw.py (don't try to call it logging.py though), then add the class to MIDDLEWARE_CLASSES in your settings file. (for instance, 'mysite.logmw.LoggingMiddleware')

Updated 8/25/08: added PhonyLogger class that swallows log messages when logging is disabled, so code doesn't have to care if it's on or not (thanks to goodness for suggesting the idea, though I missed it before)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from datetime import datetime
import logging

logger = None


class PhonyLogger(object):

    def debug(self, *args, **kwargs):
        pass

    def info(self, *args, **kwargs):
        pass

    def warning(self, *args, **kwargs):
        pass

    def error(self, *args, **kwargs):
        pass

    def critical(self, *args, **kwargs):
        pass


class LoggingMiddleware(object):
    """
    Basic logging middleware. If settings.LOG_ENABLED is set, adds a logger
    instance as request.logger

    Logging can be used as:

        request.logger.[debug, info, warning, error and critical]

    Ex: request.logger.info("This is an info message")

    Requires LOG_ENABLED settings value.

    If settings.LOG_ENABLED is True, requires LOG_FILE value.

    LOG_NAME is optional, and will specify a name for this logger
    instance (not shown in default format string)
    """

    def process_request(self, request):
        from django.conf import settings
        enabled = getattr(settings, 'LOG_ENABLED', False)
        logfile = getattr(settings, 'LOG_FILE', None)
        if not enabled or not logfile:
            request.logger = PhonyLogger()
            return

        global logger
        if logger is None:
            logging.basicConfig(
                level=logging.DEBUG,
                format='%(asctime)s - %(levelname)s - %(message)s',
                datefmt='%Y-%m-%d %X',
                filename=settings.LOG_FILE,
                filemode='a')
            logger = logging.getLogger(getattr(settings, 'LOG_NAME', 'django'))
            logger.setLevel(logging.DEBUG)

        request.logger = logger

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

aaloy (on September 29, 2007):

I have added minor lines to log also to the django console when I'm developping. This middleware makes logging much clearer. Thank you!

#

goodness (on June 2, 2008):

Hmm, I'm not sure I fully understand how people use this. If I set LOG_ENABLED, then all my logging statements now cause errors? I modified the code a little bit to stick a class with empty methods in request.logger. So something like:

        class EmptyLogger():
            def log(self, level, msg, *args, **kwargs):
                pass
            def info(self, msg, *args, **kwargs):
                pass
            def debug(self, msg, *args, **kwargs):
                pass
            def warning(self, msg, *args, **kwargs):
                pass
            def error(self, msg, *args, **kwargs):
                pass
            def critical(self, msg, *args, **kwargs):
                pass
        if logger is None:
            logger = EmptyLogger()
        request.logger = logger

#

Please login first before commenting.