summaryrefslogtreecommitdiff
path: root/qvisqve/log_setup.py
blob: e32137c5f9484fc06e2e4430aeb09ff8c458747f (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
# 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):
    for target in config.get('log', []):
        setup_logging_to_file(target, 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)