Skip to content

Commit 329bff4

Browse files
committed
fix(logging): default the osw handler to stderr, not stdout
- stdout is the JSON-RPC channel of an MCP stdio server - redirect_stdout does not reach a StreamHandler bound at construction - refs #170
1 parent 4b341f2 commit 329bff4

2 files changed

Lines changed: 13 additions & 3 deletions

File tree

‎src/osw/__init__.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,9 @@ def enable_logging(level=None, stream=None) -> logging.Handler:
133133
a level name or number. Defaults to the environment variable, then to
134134
DEFAULT_LOG_LEVEL.
135135
stream
136-
where to write. Defaults to sys.stdout, which is where the print calls
137-
this replaced used to go.
136+
where to write. Defaults to sys.stderr, so stdout stays free for a
137+
program's own output. Anything speaking a protocol over stdout, such as
138+
an MCP stdio server, depends on that.
138139
139140
Returns
140141
-------
@@ -145,7 +146,7 @@ def enable_logging(level=None, stream=None) -> logging.Handler:
145146
if level is None:
146147
level = _parse_level(os.environ.get(LOG_LEVEL_ENV_VAR, ""))
147148
_detach()
148-
handler = _DefaultHandler(sys.stdout if stream is None else stream)
149+
handler = _DefaultHandler(sys.stderr if stream is None else stream)
149150
handler.setFormatter(logging.Formatter(LOG_FORMAT))
150151
handler.set_name(_DEFAULT_HANDLER_NAME)
151152
_logger.addHandler(handler)

‎tests/test_logging_setup.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
"""
77

88
import logging
9+
import sys
910
from contextlib import contextmanager
1011

1112
import pytest
@@ -136,6 +137,14 @@ def test_enable_logging_does_not_stack_handlers(osw_logger):
136137
assert len(osw_default_handlers(osw_logger)) == 1
137138

138139

140+
def test_the_default_handler_writes_to_stderr(osw_logger):
141+
"""stdout carries a program's own output, and a protocol for anything that
142+
speaks one over it, e.g. an MCP stdio server, so osw keeps off it."""
143+
handler = osw.enable_logging()
144+
145+
assert handler.stream is sys.stderr
146+
147+
139148
def test_the_osw_logger_always_propagates(osw_logger):
140149
"""Propagation is what carries the records to the application's handlers,
141150
so osw never switches it off. Not writing twice is the handler's job."""

0 commit comments

Comments
 (0)