summaryrefslogtreecommitdiff
path: root/ick2/logging.py
blob: 729778d18ee9c2af0c5fd170a4be22be44b347eb (plain)
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
# Copyright (C) 2017  Lars Wirzenius


import slog


def drop_get_message(log_obj):
    # These are useless and annoying in gunicorn log messages.
    if 'getMessage' in log_obj:
        del log_obj['getMessage']
    return log_obj


# We are probably run under gunicorn, which sets up logging via the
# logging library. Hijack that so actual logging happens via the slog
# library. For this, we need to know the logger names gunicorn uses.
gunicorn_loggers = ['gunicorn.access', 'gunicorn.error']


# This sets up a global log variable that doesn't actually log
# anything anywhere. This is useful so that code can unconditionally
# call log.log(...) from anywhere. See setup_logging() for setting up
# actual logging to somewhere persistent.

log = slog.StructuredLog()
log.add_log_writer(slog.NullSlogWriter(), slog.FilterAllow())
log.add_log_massager(drop_get_message)
slog.hijack_logging(log, logger_names=gunicorn_loggers)


def setup_logging(config):
    if 'log' in config:
        assert isinstance(config['log'], list)
        for target in config.get('log', []):
            setup_logging_to_target(target)


def setup_logging_to_target(target):
    rule = get_filter_rules(target)
    if 'filename' in target:
        setup_logging_to_file(target, rule)
    else:
        raise Exception('Do not understand logging target %r' % target)


def get_filter_rules(target):
    if 'filter' in target:
        return slog.construct_log_filter(target['filter'])
    return slog.FilterAllow()


def setup_logging_to_file(target, rule):
    writer = slog.FileSlogWriter()
    writer.set_filename(target['filename'])
    if 'max_bytes' in target:
        writer.set_max_file_size(target['max_bytes'])
    log.add_log_writer(writer, rule)