Skip to content

Commit 7e268c4

Browse files
authored
Configure Context Variables processor by default (#43)
The new default "go-to" processors builder function now configures the [`merge_contextvars()` processor](https://www.structlog.org/en/stable/contextvars.html): it's a good default value to have, but it's not really part of the "GCP-specific" processors and is separated from them. Fix: #33 Fix: #34
1 parent f2cfaca commit 7e268c4

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

structlog_gcp/base.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import structlog.contextvars
12
import structlog.processors
23
from structlog.typing import Processor
34

@@ -21,6 +22,7 @@ def build_processors(
2122

2223
procs: list[Processor] = []
2324

25+
procs.append(structlog.contextvars.merge_contextvars)
2426
procs.extend(build_gcp_processors(service, version))
2527
procs.append(structlog.processors.JSONRenderer())
2628

tests/test_log.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,13 +150,40 @@ def test_extra_labels(stdout: T_stdout, logger: WrappedLogger) -> None:
150150
assert msg == expected
151151

152152

153+
def test_contextvars_supported(stdout: T_stdout, logger: WrappedLogger) -> None:
154+
structlog.contextvars.bind_contextvars(
155+
request_id="1234",
156+
)
157+
158+
logger.info("test")
159+
msg = json.loads(stdout())
160+
161+
expected = {
162+
"logging.googleapis.com/sourceLocation": {
163+
"file": "/app/test.py",
164+
"function": "test:test123",
165+
"line": "42",
166+
},
167+
"message": "test",
168+
"request_id": "1234",
169+
"severity": "INFO",
170+
"time": "2023-04-01T08:00:00.000000Z",
171+
}
172+
assert msg == expected
173+
174+
153175
def test_core_processors_only(stdout: T_stdout, mock_logger_env: None) -> None:
154176
processors = structlog_gcp.build_gcp_processors()
155177
processors.append(structlog.processors.KeyValueRenderer())
156178

157179
structlog.configure(processors=processors)
158180
logger = structlog.get_logger()
159181

182+
# This will not be logged as the contextvars processor is not configured in the "core" processors.
183+
structlog.contextvars.bind_contextvars(
184+
request_id="1234",
185+
)
186+
160187
logger.info("test")
161188
msg = stdout().strip()
162189

0 commit comments

Comments
 (0)