summaryrefslogtreecommitdiff
path: root/ick2/logging.py
blob: 00a65ac40b4b0916fc3d7b287801328fb47d49be (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
58
59
60
61
62
63
64
65
66
67
68
69
# Copyright (C) 2017  Lars Wirzenius
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


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)