Skip to content

Commit 3a384df

Browse files
Merge pull request #60 from NYPL/no-double-logging
Don't add log handlers if they already exist
2 parents 2bfea10 + c20a11e commit 3a384df

5 files changed

Lines changed: 13 additions & 6 deletions

File tree

.python-version

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3.13.1
1+
3.13

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
# Changelog
2+
## v1.10.2 4/27/26
3+
- Prevent double logging in pytest using structlog
4+
25
## v1.10.1 4/14/26
36
- Add optional timeout param for OAuth2Client
47

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
44

55
[project]
66
name = "nypl_py_utils"
7-
version = "1.10.1"
7+
version = "1.10.2"
88
authors = [
99
{ name="Aaron Friedman", email="aaronfriedman@nypl.org" },
1010
]

src/nypl_py_utils/functions/log_helper.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,13 @@ def get_structlog(module):
2828
without binding it to others, use `logger = logger.bind(contextvar=0)`.
2929
"""
3030
logger = logging.getLogger(module)
31-
logger.addHandler(logging.StreamHandler(sys.stdout))
3231
logger.setLevel(os.environ.get('LOG_LEVEL', 'INFO').upper())
33-
logger.propagate = False # Prevents double logging
32+
33+
# We assume existing loggers will handle logging to stdout and that we
34+
# don't need to do anything. Otherwise, manually add a stdout handler.
35+
if not logger.hasHandlers():
36+
logger.propagate = False
37+
logger.addHandler(logging.StreamHandler(sys.stdout))
3438

3539
return structlog.wrap_logger(
3640
logger,

tests/test_log_helper.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@
1010

1111
@freeze_time('2023-01-01 19:00:00')
1212
class TestLogHelper:
13-
def test_json_logging(self, capsys):
13+
def test_json_logging(self, caplog):
1414
logger = create_log('test_structlog', json=True)
1515
logger.info('test', some="json")
16-
output = json.loads(capsys.readouterr().out)
16+
output = json.loads(caplog.records[0].msg)
1717
assert output.get("message") == 'test'
1818
assert output.get("some") == 'json'
1919
assert output.get('level') == 'info'

0 commit comments

Comments
 (0)