Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Support outputting structured logs in addition to standard logs #8607

Merged
merged 23 commits into from
Oct 29, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2db1099
Remove the structured logging configuration code.
clokep Oct 21, 2020
509594f
Remove an unnecessary return value.
clokep Oct 20, 2020
99f50ec
Rework structured logging to use the Python standard library logging …
clokep Oct 21, 2020
fcb74ae
Pipe through the server_name properly.
clokep Oct 21, 2020
24a9882
Use a standard library logger.
clokep Oct 21, 2020
4462758
Update synmark for the changes.
clokep Oct 21, 2020
24ab2df
Update logging format
clokep Oct 26, 2020
5fbc11c
Fix-up formatting using __all__.
clokep Oct 26, 2020
b2fc88b
Do not build an unnecessary set.
clokep Oct 26, 2020
650bb09
Stop using the DEBUG decorators.
clokep Oct 26, 2020
7115697
Raise an error if structured is in the logging config.
clokep Oct 26, 2020
e855dbb
__all__ takes strings, not objects.
clokep Oct 26, 2020
7071d89
Update the sample config.
clokep Oct 26, 2020
6b785c1
Revamp tests a bit to avoid impacting other tests.
clokep Oct 26, 2020
8d51476
Abstract handling of loggers in tests.
clokep Oct 27, 2020
7fb5505
Add a test for including additional structured data.
clokep Oct 27, 2020
11a488c
Lint.
clokep Oct 27, 2020
a19c967
Fix test after rename.
clokep Oct 27, 2020
e98a6d1
Add an upgrade note.
clokep Oct 27, 2020
babdd5b
Rework the code to load logging configs.
clokep Oct 28, 2020
10738cc
Convert legacy drain configurations to standard library handler configs.
clokep Oct 28, 2020
f801d71
Add back a JSON formatter without time.
clokep Oct 28, 2020
1c0181a
Fix type hints.
clokep Oct 28, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions synapse/config/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import synapse
from synapse.app import _base as appbase
from synapse.logging.context import LoggingContextFilter
from synapse.logging.filter import MetadataFilter
from synapse.util.versionstring import get_version_string

from ._base import Config, ConfigError
Expand Down Expand Up @@ -199,12 +200,14 @@ def _setup_stdlib_logging(config, log_config, logBeginner: LogBeginner) -> None:
# filter options, but care must when using e.g. MemoryHandler to buffer
# writes.

log_filter = LoggingContextFilter(request="")
log_context_filter = LoggingContextFilter(request="")
log_metadata_filter = MetadataFilter({"server_name": config.server_name})
old_factory = logging.getLogRecordFactory()

def factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
log_filter.filter(record)
log_context_filter.filter(record)
log_metadata_filter.filter(record)
return record

logging.setLogRecordFactory(factory)
Expand Down
47 changes: 32 additions & 15 deletions synapse/logging/_terse_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,32 +18,49 @@
"""
import json
import logging
from typing import Optional

_encoder = json.JSONEncoder(ensure_ascii=False, separators=(",", ":"))

# The properties of a standard LogRecord.
_LOG_RECORD_ATTRIBUTES = {
"args",
"asctime",
"created",
"exc_info",
# exc_text isn't a public attribute, but is used to cache the result of formatException.
"exc_text",
"filename",
"funcName",
"levelname",
"levelno",
"lineno",
"message",
"module",
"msecs",
"msg",
"name",
"pathname",
"process",
"processName",
"relativeCreated",
"stack_info",
"thread",
"threadName",
}

class TerseJsonFormatter:
def __init__(
self, *args, include_time: bool = True, metadata: Optional[dict] = None
):
self.include_time = include_time
self.metadata = metadata or {}

class TerseJsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
event = {
"log": record.getMessage(),
"namespace": record.name,
"level": record.levelname,
"time": round(record.created, 2),
}

# We want to include the timestamp when forwarding over the network, but
# exclude it when we are writing to stdout. This is because the log ingester
clokep marked this conversation as resolved.
Show resolved Hide resolved
# (e.g. logstash, fluentd) can add its own timestamp.
if self.include_time:
event["time"] = round(record.created, 2)

# Add the metadata information to the event (e.g. the server_name).
event.update(self.metadata)
# Add any extra attributes to the event.
extra_attributes = set(record.__dict__.keys()) - _LOG_RECORD_ATTRIBUTES
clokep marked this conversation as resolved.
Show resolved Hide resolved
for key in extra_attributes:
event[key] = getattr(record, key)

return _encoder.encode(event)
33 changes: 33 additions & 0 deletions synapse/logging/filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
# Copyright 2020 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging

from typing_extensions import Literal


class MetadataFilter(logging.Filter):
"""Logging filter that adds constant values to each record.

Args:
metadata: Key-value pairs to add to each record.
"""

def __init__(self, metadata: dict):
self._metadata = metadata

def filter(self, record: logging.LogRecord) -> Literal[True]:
for key, value in self._metadata.items():
setattr(record, key, value)
clokep marked this conversation as resolved.
Show resolved Hide resolved
return True
5 changes: 3 additions & 2 deletions tests/logging/test_terse_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def test_log_output(self):
output = StringIO()

handler = logging.StreamHandler(output)
handler.setFormatter(TerseJsonFormatter(metadata={"server_name": "foo"}))
handler.setFormatter(TerseJsonFormatter())

logger = logging.getLogger()
logger.addHandler(handler)
Expand All @@ -51,7 +51,8 @@ def test_log_output(self):
"time",
"level",
"namespace",
"server_name",
# Added via LoggingContextFilter, configured in tests.test_utils.logging_setup.setup_logging.
"request",
]
self.assertCountEqual(log.keys(), expected_log_keys)
self.assertEqual(log["log"], "Hello there, wally!")