-
Notifications
You must be signed in to change notification settings - Fork 0
Feat: Added support for switching to ECS conformant JSON logging. #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
0e8f972
Feat: Added support for switching to ECS conformant JSON logging.
buddemat 4bec1f3
Fix: Added missing dependency in pyproj.toml.
buddemat 3fa4f5a
Docs: Added ecs-logging as dependency in README.md
buddemat fd6a73f
Feat: Ensured that logging config is robust to lower/mixed case spell…
buddemat File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| """Configures logging for the `cadenzaanalytics` package. | ||
|
|
||
| The configured handler is attached to the root logger, and `disable_existing_loggers` is left `False`, so this | ||
| also governs log output from dependent packages (e.g. Flask, Werkzeug) and from analytics extensions built with | ||
| `cadenzaanalytics`, as long as their loggers propagate to root, which is the default in standard Python logging. | ||
| """ | ||
| import os | ||
| from logging.config import dictConfig | ||
| from typing import Any, Dict | ||
|
|
||
| import ecs_logging | ||
|
|
||
| from cadenzaanalytics.version import __version__ | ||
|
|
||
| _PLAIN_FORMATTER_CONFIG = { | ||
| 'format': '[%(asctime)s] [%(process)d] [%(levelname)s] [%(module)s] %(message)s', | ||
| 'datefmt': '%Y-%m-%d %H:%M:%S %z' | ||
| } | ||
|
|
||
|
|
||
| class CadenzaEcsFormatter(ecs_logging.StdlibFormatter): | ||
| """An `ecs_logging.StdlibFormatter` that additionally stamps every record with `service.name` | ||
| and `service.version`, identifying the `cadenzaanalytics` version that produced the log line.""" | ||
|
|
||
| def format_to_ecs(self, record) -> Dict[str, Any]: | ||
| result = super().format_to_ecs(record) | ||
| result.setdefault('service', {})['name'] = 'cadenzaanalytics' | ||
| result['service']['version'] = __version__ | ||
| return result | ||
|
|
||
|
|
||
| def configure_logging() -> None: | ||
| """Configure the root logger from the `CADENZAANALYTICS_LOG_LVL` and `CADENZAANALYTICS_LOG_FORMAT` | ||
| environment variables. | ||
|
|
||
| `CADENZAANALYTICS_LOG_LVL` sets the root log level (default `INFO`). | ||
| `CADENZAANALYTICS_LOG_FORMAT` selects the output format: `plain` (default) for a human-readable, | ||
| gunicorn-like line format, or `ecs` for Elastic Common Schema (ECS) conformant JSON, suited for | ||
| log aggregation in container deployments. | ||
|
|
||
| Raises | ||
| ------ | ||
| ValueError | ||
| If `CADENZAANALYTICS_LOG_FORMAT` is set to a value other than `plain` or `ecs`. | ||
| """ | ||
| log_format = os.environ.get('CADENZAANALYTICS_LOG_FORMAT', 'plain').lower() | ||
|
|
||
| if log_format == 'plain': | ||
| formatter_config = _PLAIN_FORMATTER_CONFIG | ||
| elif log_format == 'ecs': | ||
| formatter_config = {'()': CadenzaEcsFormatter} | ||
| else: | ||
| raise ValueError( | ||
| f'Invalid CADENZAANALYTICS_LOG_FORMAT "{log_format}". Supported values are "plain" and "ecs".' | ||
| ) | ||
|
|
||
| log_level = os.environ.get('CADENZAANALYTICS_LOG_LVL', 'INFO').upper() | ||
|
|
||
| dictConfig({ | ||
| 'disable_existing_loggers': False, | ||
| 'version': 1, | ||
| 'formatters': {'default': formatter_config}, | ||
| 'handlers': {'wsgi': { | ||
| 'class': 'logging.StreamHandler', | ||
| 'stream': 'ext://flask.logging.wsgi_errors_stream', | ||
| 'formatter': 'default' | ||
| }}, | ||
| 'root': { | ||
| 'level': log_level, | ||
| 'handlers': ['wsgi'] | ||
| }, | ||
| # gunicorn configures 'gunicorn.error'/'gunicorn.access' with its own handlers and | ||
| # propagate=False before this module is imported; re-pointing them at our own handler here | ||
| # keeps gunicorn's own logs in the same format, without requiring any gunicorn-side configuration. | ||
| 'loggers': { | ||
| 'gunicorn.error': {'level': log_level, 'handlers': ['wsgi'], 'propagate': False}, | ||
| 'gunicorn.access': {'level': log_level, 'handlers': ['wsgi'], 'propagate': False} | ||
| } | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| """Unit tests for logging configuration.""" | ||
| import json | ||
| import logging | ||
|
|
||
| import pytest | ||
| from cadenzaanalytics.logging_config import configure_logging | ||
|
|
||
|
|
||
| class TestLoggingConfig: | ||
| """Test suite for configure_logging.""" | ||
|
|
||
| def teardown_method(self): | ||
| """Reset logger state so tests don't leak configuration into one another.""" | ||
| for name in (None, 'gunicorn.error', 'gunicorn.access'): | ||
| logger = logging.getLogger(name) | ||
| logger.handlers = [] | ||
| logger.propagate = True | ||
|
|
||
| def test_invalid_log_format_raises(self, monkeypatch): | ||
| """An unsupported CADENZAANALYTICS_LOG_FORMAT value should raise a ValueError.""" | ||
| monkeypatch.setenv('CADENZAANALYTICS_LOG_FORMAT', 'bogus') | ||
| with pytest.raises(ValueError, match='CADENZAANALYTICS_LOG_FORMAT'): | ||
| configure_logging() | ||
|
|
||
| def test_ecs_format_produces_ecs_json(self, monkeypatch, capsys): | ||
| """The 'ecs' format should produce ECS-conformant JSON, stamped with the service name/version.""" | ||
| monkeypatch.setenv('CADENZAANALYTICS_LOG_FORMAT', 'ecs') | ||
| configure_logging() | ||
|
|
||
| logging.getLogger('some.dependency').warning('dependency warning') | ||
|
|
||
| record = json.loads(capsys.readouterr().err.strip()) | ||
| assert record['message'] == 'dependency warning' | ||
| # per the ECS logging spec, '@timestamp', 'log.level' and 'message' stay flat/dotted top-level keys | ||
| assert record['log.level'] == 'warning' | ||
| assert record['log']['logger'] == 'some.dependency' | ||
| assert record['service']['name'] == 'cadenzaanalytics' | ||
|
|
||
| def test_plain_format_is_not_json(self, monkeypatch, capsys): | ||
| """The default 'plain' format should produce a human-readable line, not JSON.""" | ||
| monkeypatch.delenv('CADENZAANALYTICS_LOG_FORMAT', raising=False) | ||
| configure_logging() | ||
|
|
||
| logging.getLogger('some.dependency').warning('dependency warning') | ||
|
|
||
| line = capsys.readouterr().err.strip() | ||
| assert 'dependency warning' in line | ||
| with pytest.raises(json.JSONDecodeError): | ||
| json.loads(line) | ||
|
|
||
| def test_log_level_is_case_insensitive(self, monkeypatch): | ||
| """CADENZAANALYTICS_LOG_LVL should be accepted regardless of case, since logging.setLevel() | ||
| only recognizes uppercase level names and would otherwise raise a ValueError.""" | ||
| monkeypatch.setenv('CADENZAANALYTICS_LOG_LVL', 'debug') | ||
| configure_logging() | ||
|
|
||
| assert logging.getLogger().getEffectiveLevel() == logging.DEBUG | ||
|
|
||
| def test_gunicorn_loggers_are_repointed_at_our_handler(self, monkeypatch, capsys): | ||
| """gunicorn attaches its own handlers to 'gunicorn.error'/'gunicorn.access' with propagate=False | ||
| before the app is imported; configure_logging() must re-point them at our own handler so gunicorn's | ||
| own log lines come out in the configured format too, without any gunicorn-side configuration.""" | ||
| gunicorn_access = logging.getLogger('gunicorn.access') | ||
| gunicorn_access.propagate = False | ||
| gunicorn_access.addHandler(logging.StreamHandler()) | ||
|
|
||
| monkeypatch.setenv('CADENZAANALYTICS_LOG_FORMAT', 'ecs') | ||
| configure_logging() | ||
|
|
||
| gunicorn_access.info('127.0.0.1 - - "GET / HTTP/1.1" 200 -') | ||
|
|
||
| record = json.loads(capsys.readouterr().err.strip()) | ||
| assert record['log']['logger'] == 'gunicorn.access' | ||
| assert record['service']['name'] == 'cadenzaanalytics' | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.