Logging Middleware

 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. Mail logged errors to administrators by jmillikin 5 years, 10 months ago
  2. Log Django exceptions to Apache error log in mod_wsgi by simon 4 years, 7 months ago
  3. Request time logging middleware by mpasternacki 4 years, 4 months ago
  4. Log to syslog by fylb 4 years, 2 months ago
  5. Extensible exception handling middleware by kcarnold 6 years, 1 month 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

#

(Forgotten your password?)