logsettings.py 5.46 KB
Newer Older
1 2
"""Get log settings."""

3
import os
4 5
import platform
import sys
John Jarvis committed
6
from logging.handlers import SysLogHandler
7

8
LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
9

10

11 12
def get_logger_config(log_dir,
                      logging_env="no_env",
13 14 15
                      tracking_filename="tracking.log",
                      edx_filename="edx.log",
                      dev_env=False,
16
                      syslog_addr=None,
17
                      debug=False,
18
                      local_loglevel='INFO',
19 20
                      console_loglevel=None,
                      service_variant=None):
21

22 23 24
    """

    Return the appropriate logging config dictionary. You should assign the
25
    result of this to the LOGGING var in your settings. The reason it's done
26
    this way instead of registering directly is because I didn't want to worry
27
    about resetting the logging state if this is called multiple times when
28 29 30 31 32 33 34 35 36
    settings are extended.

    If dev_env is set to true logging will not be done via local rsyslogd,
    instead, tracking and application logs will be dropped in log_dir.

    "tracking_filename" and "edx_filename" are ignored unless dev_env
    is set to true since otherwise logging is handled by rsyslogd.

    """
37

38
    # Revert to INFO if an invalid string is passed in
39
    if local_loglevel not in LOG_LEVELS:
40 41
        local_loglevel = 'INFO'

42 43 44
    if console_loglevel is None or console_loglevel not in LOG_LEVELS:
        console_loglevel = 'DEBUG' if debug else 'INFO'

45 46 47 48 49
    if service_variant is None:
        # default to a blank string so that if SERVICE_VARIANT is not
        # set we will not log to a sub directory
        service_variant = ''

50
    hostname = platform.node().split(".")[0]
51 52
    syslog_format = ("[service_variant={service_variant}]"
                     "[%(name)s][env:{logging_env}] %(levelname)s "
53
                     "[{hostname}  %(process)d] [%(filename)s:%(lineno)d] "
54 55 56
                     "- %(message)s").format(service_variant=service_variant,
                                             logging_env=logging_env,
                                             hostname=hostname)
57

58 59 60
    handlers = ['console', 'local']
    if syslog_addr:
        handlers.append('syslogger-remote')
61

62
    logger_config = {
63
        'version': 1,
64
        'disable_existing_loggers': False,
65 66
        'formatters': {
            'standard': {
67 68
                'format': '%(asctime)s %(levelname)s %(process)d '
                          '[%(name)s] %(filename)s:%(lineno)d - %(message)s',
69
            },
70 71
            'syslog_format': {'format': syslog_format},
            'raw': {'format': '%(message)s'},
72
        },
73 74 75 76 77
        'filters': {
            'require_debug_false': {
                '()': 'django.utils.log.RequireDebugFalse',
            }
        },
78 79
        'handlers': {
            'console': {
80
                'level': console_loglevel,
81 82
                'class': 'logging.StreamHandler',
                'formatter': 'standard',
83
                'stream': sys.stderr,
84
            },
85 86 87 88 89
            'mail_admins': {
                'level': 'ERROR',
                'filters': ['require_debug_false'],
                'class': 'django.utils.log.AdminEmailHandler'
            },
90
        },
91 92 93 94 95
        'loggers': {
            'tracking': {
                'handlers': ['tracking'],
                'level': 'DEBUG',
                'propagate': False,
96
            },
97 98 99 100
            '': {
                'handlers': handlers,
                'level': 'DEBUG',
                'propagate': False
101
            },
102 103 104 105 106
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': True,
            },
107
        }
108
    }
John Jarvis committed
109 110 111 112 113 114 115 116 117
    if syslog_addr:
        logger_config['handlers'].update({
            'syslogger-remote': {
                'level': 'INFO',
                'class': 'logging.handlers.SysLogHandler',
                'address': syslog_addr,
                'formatter': 'syslog_format',
            },
        })
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

    if dev_env:
        tracking_file_loc = os.path.join(log_dir, tracking_filename)
        edx_file_loc = os.path.join(log_dir, edx_filename)
        logger_config['handlers'].update({
            'local': {
                'class': 'logging.handlers.RotatingFileHandler',
                'level': local_loglevel,
                'formatter': 'standard',
                'filename': edx_file_loc,
                'maxBytes': 1024 * 1024 * 2,
                'backupCount': 5,
            },
            'tracking': {
                'level': 'DEBUG',
                'class': 'logging.handlers.RotatingFileHandler',
                'filename': tracking_file_loc,
                'formatter': 'raw',
                'maxBytes': 1024 * 1024 * 2,
                'backupCount': 5,
            },
        })
    else:
141 142 143
        # for production environments we will only
        # log INFO and up
        logger_config['loggers']['']['level'] = 'INFO'
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        logger_config['handlers'].update({
            'local': {
                'level': local_loglevel,
                'class': 'logging.handlers.SysLogHandler',
                'address': '/dev/log',
                'formatter': 'syslog_format',
                'facility': SysLogHandler.LOG_LOCAL0,
            },
            'tracking': {
                'level': 'DEBUG',
                'class': 'logging.handlers.SysLogHandler',
                'address': '/dev/log',
                'facility': SysLogHandler.LOG_LOCAL1,
                'formatter': 'raw',
            },
        })

    return logger_config