Skip to content

Commit

Permalink
feat: fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pquadri committed Mar 27, 2024
1 parent 64192c3 commit ef8d7af
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
19 changes: 13 additions & 6 deletions remote_log_formatter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@
from datetime import datetime


class SimpleFormatter(logging.Formatter):
def __init__(
self, fmt=None, datefmt=None, style="%", validate=True, *, defaults=None
) -> None:
if fmt is None:
fmt = "%(asctime)s | %(levelname)s | %(message)s | %(pathname)s:%(lineno)s"
super(SimpleFormatter, self).__init__(fmt, datefmt, style, validate)


class JSONFormatter(logging.Formatter):
def __init__(self, *args, **kwargs) -> None:
super(JSONFormatter, self).__init__(*args, **kwargs)
Expand Down Expand Up @@ -67,12 +76,12 @@ def setup_logging(json: bool = True) -> None:
LOG_CONFIG = dict(
version=1,
disable_existing_loggers=False,
remote={
root={
"level": "INFO",
"handlers": ["console"],
},
loggers={
"remote": {
"root": {
"level": "INFO",
"handlers": ["console"],
"propagate": True,
Expand All @@ -87,14 +96,12 @@ def setup_logging(json: bool = True) -> None:
},
formatters={
"generic": {"class": "remote_log_formatter.JSONFormatter"},
"simple": {
"format": "%(asctime)s | %(levelname)s | %(message)s | %(pathname)s:%(lineno)s ",
},
"simple": {"class": "remote_log_formatter.SimpleFormatter"},
},
)

logging.config.dictConfig(LOG_CONFIG)


def get_logger(name="remote") -> logging.Logger:
def get_logger(name: str = "remote") -> logging.Logger:
return logging.getLogger(name)
5 changes: 5 additions & 0 deletions remote_log_formatter/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from remote_log_formatter import get_logger, setup_logging

setup_logging(json=False)
logger = get_logger(__package__)
logger.info("foo")
6 changes: 3 additions & 3 deletions tests/test_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import pytest

from remote_log_formatter import JSONFormatter, SimpleFormatter
from remote_log_formatter import get_logger as _logger
from remote_log_formatter import setup_logging as _setup

Expand Down Expand Up @@ -51,7 +52,7 @@ def test_json_logger(
assert caplog.records
r = caplog.records[0]

data = json.loads(logger_json.handlers[0].format(r))
data = json.loads(JSONFormatter().format(r))
assert data == {
"datetime": data["datetime"],
"level": "INFO",
Expand Down Expand Up @@ -89,8 +90,7 @@ def test_plain_logger(
logger_plain.info(message)
assert caplog.records
r = caplog.records[0]

data = logger_plain.handlers[0].format(r)
data = SimpleFormatter().format(r)

_ts, level, message, path = data.split("|")
assert message.strip() == expected
Expand Down

0 comments on commit ef8d7af

Please sign in to comment.