Login

Logging to rotating files

Author:
davidfung
Posted:
August 14, 2013
Language:
Python
Version:
1.5
Tags:
settings logging
Score:
0 (after 0 ratings)

It took me some time to figure out how to set up logging in Django. What I want to do is to log to a pair of rotating files each 1MB in size.

What I come up with is this code segment in the settings.py file.

 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
64
# In settings.py

U_LOGFILE_NAME = r'/path/to/log.txt'
U_LOGFILE_SIZE = 1 * 1024 * 1024
U_LOGFILE_COUNT = 2
U_LOGFILE_APP1 = 'app1'
U_LOGFILE_APP2 = 'app2'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            #'datefmt' : "%d/%b/%Y %H:%M:%S"
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'logfile': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': U_LOGFILE_NAME,
            'maxBytes': U_LOGFILE_SIZE,
            'backupCount': U_LOGFILE_COUNT,
            'formatter': 'standard',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        U_LOGFILE_APP1: {
            'handlers': ['logfile'],
            'level': 'DEBUG',
            'propagate': True,
        },
        U_LOGFILE_APP2: {
            'handlers': ['logfile'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

# Usage:

import os
log = logging.getLogger(__name__)
log.debug("debug")
log.info("info")
log.warn("warn")
log.error("error")

More like this

  1. Log all interaction with user to the DB by inuwashi 4 years, 5 months ago
  2. Logging Middleware by Magus 7 years, 9 months ago
  3. Reusable Logging by mihasya 6 years, 4 months ago
  4. User Profile minimal code by Natim 3 years, 11 months ago
  5. Generic markup converter by ubernostrum 8 years, 3 months ago

Comments

Please login first before commenting.