Skip to content

Commit 665b758

Browse files
feat(observability): let the structlog sink rename the event key, add processors and pick the stream (#114)
1 parent c74a507 commit 665b758

10 files changed

Lines changed: 250 additions & 14 deletions

File tree

‎docs/adapters/observability-backends.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,49 @@ Because contextvars merging is in the chain, anything bound into the
156156
{"event": "Request finished", "request_id": "9f2c...", "status_code": 200, "level": "info"}
157157
```
158158

159+
### Event key, extra processors, stream
160+
161+
A log pipeline that reads a line's text from `message` (ELK does) needs nothing but the
162+
environment:
163+
164+
```bash
165+
LOGGING__EVENT_KEY=message
166+
```
167+
168+
```json
169+
{"message": "Request finished", "request_id": "9f2c...", "status_code": 200, "level": "info"}
170+
```
171+
172+
The rest goes through the sink's constructor, via
173+
[instance injection](../concepts/observability.md#instance-injection):
174+
175+
```python
176+
import sys
177+
178+
import structlog
179+
180+
from servicewright.adapters.observability import StructlogLoggingSink
181+
182+
observability = ObservabilityManager(
183+
ObsConfig(logging="structlog"),
184+
logging=StructlogLoggingSink(
185+
event_key="message",
186+
extra_processors=[structlog.processors.CallsiteParameterAdder()],
187+
stream=sys.stdout,
188+
),
189+
)
190+
```
191+
192+
- `event_key` renames `event` right before the JSON renderer, for structlog lines and standard
193+
library records alike. Left `None`, it is `settings.logging.event_key`, and `"event"` for a
194+
settings section without that field. Console output keeps `event`, which is what the console
195+
renderer reads. The text replaces a field of the same name: with `event_key="message"`,
196+
`log.info("Order placed", message="draft")` renders `"message": "Order placed"` and the
197+
`draft` is gone.
198+
- `extra_processors` run on every line after `ExtraAdder` and before the redactor, so whatever
199+
they add is redacted like the rest of the payload.
200+
- `stream` is where the lines go. `None`, the default, is stderr.
201+
159202
## stdlib (logging)
160203

161204
```python

‎docs/agents.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ installed and raise (or degrade) at construction instead.
318318
| `servicewright.adapters.apscheduler4` (and `.apscheduler3`) | `SchedulerEntrypoint`, `SchedulerPlugin`, `ScheduledJob`, `ScheduledJobFunc`, `SchedulerJobMetricsRecorder`, `SchedulerError`, `DuplicateScheduleError` |
319319
| `servicewright.adapters.dishka` | `DishkaContainer`, `DishkaScope` |
320320
| `servicewright.adapters.settings` | `BaseServiceSettings`, `LoggingSettings`, `MetricsSettings`, `TracingSettings`, `ErrorTrackingSettings` |
321-
| `servicewright.adapters.observability` | ABCs `MetricsSink`, `TracingSink`, `ErrorTrackingSink`, `LoggingSink`; backends `PrometheusMetricsSink`, `OtelTracingSink`, `SentryErrorTrackingSink`, `StructlogLoggingSink`, `StdlibLoggingSink` (each imported lazily on first access) |
321+
| `servicewright.adapters.observability` | ABCs `MetricsSink`, `TracingSink`, `ErrorTrackingSink`, `LoggingSink`; backends `PrometheusMetricsSink`, `OtelTracingSink`, `SentryErrorTrackingSink`, `StructlogLoggingSink`, `StdlibLoggingSink` (each imported lazily on first access). `StructlogLoggingSink(*, event_key=None, extra_processors=(), stream=None)`: `event_key` renames `event` in JSON output only and defaults to `settings.logging.event_key` (`LOGGING__EVENT_KEY=message` for ELK), `extra_processors` run after `ExtraAdder` and before the redactor, `stream=None` is stderr |
322322
| `servicewright.adapters.warmers` | `RedisWarmer`, `PostgresWarmer`, `KafkaProducerWarmer` — all `(client, …, timeout=10.0, priority=0, raise_on_failure=True)`; the package and the submodules both export them, extra or no extra, and `PostgresWarmer` is the only one that needs its SDK (`PostgresWarmupError` at construction without it) |
323323
| `servicewright.adapters.health.postgres` / `.redis` | `PostgresHealthCheck(session_maker, timeout=5.0)`, `RedisHealthCheck(client, timeout=5.0)` — import from the submodule, not the package |
324324
| `servicewright.testing` | `FakeContainer`, `FakeScope`, `FakeSettings`, `FakeEntrypoint` |

‎docs/concepts/observability.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,11 @@ adapter's own request logs. Those go *through* the standard library logger, not
164164
With the logging concern switched off, the root logger is left untouched and request lines follow
165165
whatever your application configured.
166166

167+
The structlog sink writes the text of a line under `event`. For a pipeline that reads it from
168+
`message`, as ELK does, set `LOGGING__EVENT_KEY=message`. The sink's constructor also takes extra
169+
structlog processors, which run before the redactor, and the stream to write to, stderr by
170+
default. See [structlog](../adapters/observability-backends.md#event-key-extra-processors-stream).
171+
167172
Correlation is automatic: the transports bind `request_id` / `user_id` / `tenant_id` / `trace_id`
168173
into the [context store](context.md) and push them into structlog contextvars and OTel Baggage.
169174

‎docs/concepts/settings.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ your own that uses them behaves exactly like the shipped one.
3535
| --- | --- | --- | --- |
3636
| `level` | `str` | `"INFO"` | Root log level: `DEBUG`, `INFO`, ... |
3737
| `use_json` | `bool` | `True` | JSON lines vs human-readable console output |
38+
| `event_key` | `str` | `"event"` | Key of a line's text in JSON output, `"message"` for ELK; read by the structlog backend only, console output keeps `event` |
3839

3940
### `metrics`
4041

‎docs/operations/checklist.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ to a failure someone has already had.
104104
below `1` will show up as latency.
105105
- [ ] The image runs as a non-root user.
106106
- [ ] API and worker are separate deployments built from the same spec, if they scale differently.
107-
- [ ] Logs go to stdout as JSON and the collector parses them.
107+
- [ ] Logs go out as JSON (to stderr by default) and the collector parses them, the key of the text
108+
included (`LOGGING__EVENT_KEY`).
108109

109110
## Before the first real traffic
110111

‎docs/operations/kubernetes.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,11 +226,16 @@ observability and shutdown stay identical because they come from the same spec.
226226

227227
## Logging
228228

229-
Ship JSON to stdout and let your collector do the rest:
229+
Ship JSON lines and let your collector do the rest:
230230

231231
```python
232232
LoggingSettings(level="INFO", use_json=True)
233233
```
234234

235+
The logging sinks write to stderr, which the container runtime collects like stdout. If your
236+
collector reads stdout only, give the structlog sink `stream=sys.stdout`. If it reads a line's text
237+
from `message`, set `LOGGING__EVENT_KEY=message`. See
238+
[structlog](../adapters/observability-backends.md#event-key-extra-processors-stream).
239+
235240
Every line carries `request_id` (or `job_id` / `run_id`) automatically, so a single grep spans the
236241
API request and the work it triggered. See [Request context](../concepts/context.md).

‎servicewright/adapters/observability/_logging/structlog.py‎

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from __future__ import annotations
1212

1313
import logging
14-
from typing import TYPE_CHECKING, Any
14+
from typing import TYPE_CHECKING, Any, TextIO
1515

1616
from ..base import LoggingSink
1717

@@ -21,16 +21,39 @@
2121
raise ImportError("structlog logging requires servicewright[observability]; install it.") from exc
2222

2323
if TYPE_CHECKING:
24+
from collections.abc import Sequence
25+
2426
from ....core.contracts.observability import Redactor
2527
from ....core.observability.config import ObsSetupContext
2628

2729

2830
class StructlogLoggingSink(LoggingSink):
29-
"""structlog backend driven by ``settings.logging`` (level, JSON or console)."""
31+
"""structlog backend driven by ``settings.logging`` (level, JSON or console).
32+
33+
Args:
34+
event_key: Key that holds a line's text in JSON output, for a log pipeline that reads
35+
it from somewhere other than ``event`` (``"message"`` for ELK). ``None`` (the
36+
default) takes ``settings.logging.event_key``, and ``"event"`` when the section has
37+
no such field. Console output always keeps ``event``, which is what the console
38+
renderer reads. The text replaces a field of the same name on the line.
39+
extra_processors: structlog processors run on every line, structlog-native and stdlib
40+
alike, after ``ExtraAdder`` and before the redactor, so whatever they add is
41+
redacted like the rest of the payload.
42+
stream: Where the lines are written. ``None`` (the default) is stderr.
43+
"""
3044

3145
backend = "structlog"
3246

33-
def __init__(self) -> None:
47+
def __init__(
48+
self,
49+
*,
50+
event_key: str | None = None,
51+
extra_processors: Sequence[structlog.typing.Processor] = (),
52+
stream: TextIO | None = None,
53+
) -> None:
54+
self._event_key = event_key
55+
self._extra_processors = tuple(extra_processors)
56+
self._stream = stream
3457
self._handler: logging.Handler | None = None
3558

3659
def setup(self, ctx: ObsSetupContext) -> None:
@@ -41,6 +64,7 @@ def setup(self, ctx: ObsSetupContext) -> None:
4164

4265
level = _coerce_level(getattr(logging_settings, "level", "INFO"))
4366
use_json = bool(getattr(logging_settings, "use_json", True))
67+
event_key = self._event_key if self._event_key is not None else getattr(logging_settings, "event_key", "event")
4468

4569
shared_processors: list[Any] = [
4670
structlog.contextvars.merge_contextvars,
@@ -52,9 +76,10 @@ def setup(self, ctx: ObsSetupContext) -> None:
5276
# — the FastAPI access log's method/path/status, a failing warmer's name — since those
5377
# are all emitted as ``logger.info(..., extra={...})``.
5478
structlog.stdlib.ExtraAdder(),
79+
*self._extra_processors,
5580
]
56-
# After ExtraAdder on purpose: a recovered field is payload like any other and must face
57-
# the redactor, or a secret passed through ``extra`` would bypass it.
81+
# After ExtraAdder and the caller's processors on purpose: a recovered or added field is payload
82+
# like any other and must face the redactor, or a secret passed through ``extra`` would bypass it.
5883
if ctx.redactor is not None:
5984
shared_processors.append(_redaction_processor(ctx.redactor))
6085
shared_processors.extend(
@@ -65,6 +90,9 @@ def setup(self, ctx: ObsSetupContext) -> None:
6590
)
6691

6792
renderer = structlog.processors.JSONRenderer() if use_json else structlog.dev.ConsoleRenderer()
93+
# JSON only, since ConsoleRenderer reads ``event``; and right before the renderer, since the
94+
# processors ahead of it may read ``event`` too.
95+
rename = [structlog.processors.EventRenamer(event_key)] if use_json and event_key != "event" else []
6896

6997
structlog.configure(
7098
processors=[*shared_processors, structlog.stdlib.ProcessorFormatter.wrap_for_formatter],
@@ -74,10 +102,10 @@ def setup(self, ctx: ObsSetupContext) -> None:
74102
)
75103

76104
formatter = structlog.stdlib.ProcessorFormatter(
77-
processors=[structlog.stdlib.ProcessorFormatter.remove_processors_meta, renderer],
105+
processors=[structlog.stdlib.ProcessorFormatter.remove_processors_meta, *rename, renderer],
78106
foreign_pre_chain=shared_processors,
79107
)
80-
handler = logging.StreamHandler()
108+
handler = logging.StreamHandler(self._stream)
81109
handler.setFormatter(formatter)
82110

83111
root = logging.getLogger()

‎servicewright/adapters/settings/models.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ class LoggingSettings(BaseModel):
5252

5353
level: LogLevelStr = Field(default="INFO", description="Root log level; case-insensitive on input")
5454
use_json: bool = Field(default=True, description="JSON lines (True) or human-readable console output")
55+
event_key: str = Field(
56+
default="event",
57+
min_length=1,
58+
description="Key of a line's text in JSON output; read by the structlog backend, console output keeps 'event'",
59+
)
5560

5661
@field_validator("level", mode="before")
5762
@classmethod

0 commit comments

Comments
 (0)