Skip to content

Commit

Permalink
Add LOG_BASE_FIELD and LOG_EXTRA_FIELDS
Browse files Browse the repository at this point in the history
  • Loading branch information
mfrata committed Mar 23, 2021
1 parent 99ad07a commit d1e7c00
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 6 deletions.
14 changes: 8 additions & 6 deletions lodge.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@ def _get_log_level_from_env_var(logger_name: str) -> str:

def _get_format():
DEFAULT_LOG_ENV = os.environ.get("LOG_ENV", "PROD")
BASE_STRUCTURED = {
"message": "%(message)s",
"timestamp": "%(asctime)s",
"level": "%(levelname)s",
}
LOG_BASE_FIELDS = eval(
os.environ.get(
"LOG_BASE_FIELDS",
'{"message":"%(message)s","timestamp":"%(asctime)s","level":"%(levelname)s",}'
)
)
LOG_EXTRA_FIELDS = eval(os.environ.get("LOG_EXTRA_FIELDS", '{}'))

if DEFAULT_LOG_ENV == "PROD":
log_format = json.dumps(BASE_STRUCTURED)
log_format = json.dumps({**LOG_BASE_FIELDS, **LOG_EXTRA_FIELDS})
else:
log_format = "%(asctime)s | %(levelname)s | %(name)s | %(message)s"

Expand Down
28 changes: 28 additions & 0 deletions test_lodge.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,31 @@ def test_set_format_on_dev(stream, monkeypatch):
assert log_entry_splitted[-1] == " Here goes a message\n"
assert log_entry_splitted[1] == " INFO "
assert log_entry_splitted[2] == " testlog "


def test_set_extra_fields_on_logging(stream, monkeypatch):
monkeypatch.setenv("LOG_EXTRA_FIELDS", '{"program":{"name":"testlog","version":"v1"}}')
with import_lodge() as lodge:
log = lodge.get_logger("testlog")
log.info("Logging with extra fields")

log_entry = stream.read()
log_structured = json.loads(log_entry)

assert log_structured["message"] == "Logging with extra fields"
assert "program" in log_structured.keys()
assert log_structured["program"]["name"] == "testlog"
assert log_structured["program"]["version"] == "v1"


def test_set_base_fields_on_logging(stream, monkeypatch):
monkeypatch.setenv("LOG_BASE_FIELDS", '{"message":"%(message)s","anotherField":"yes"}')
with import_lodge() as lodge:
log = lodge.get_logger("testlog")
log.info("Logging other base fields")

log_entry = stream.read()
log_structured = json.loads(log_entry)

assert log_structured["message"] == "Logging other base fields"
assert log_structured["anotherField"] == "yes"

0 comments on commit d1e7c00

Please sign in to comment.