11# Settings
22
33servicewright reads a small, fixed set of things off a settings object that ** you** own and
4- construct. It never loads a ` .env ` , never reads ` os.environ ` , and never defines a settings class
5- you have to inherit from.
4+ construct. The kernel never loads a ` .env ` , never reads ` os.environ ` , and never defines a class
5+ you have to inherit from: it checks shape, not ancestry. The ` settings ` extra ships that shape as
6+ ready-made [ pydantic-settings models] ( #shipped-models ) , so you do not have to transcribe it.
67
78## The protocol
89
@@ -24,21 +25,28 @@ Sentry for something else does not touch your settings class.
2425
2526## The sections
2627
28+ Each table lists the ** default** the built-in backend falls back to when the field is missing
29+ from your section. The [ shipped models] ( #shipped-models ) carry the same values, so a model of
30+ your own that uses them behaves exactly like the shipped one.
31+
2732### ` logging `
2833
29- | Field | Type | Meaning |
30- | --- | --- | --- |
31- | ` level ` | ` str ` | Root log level: ` DEBUG ` , ` INFO ` , ... |
32- | ` use_json ` | ` bool ` | JSON lines vs human-readable console output |
34+ | Field | Type | Default | Meaning |
35+ | --- | --- | --- | --- |
36+ | ` level ` | ` str ` | ` "INFO" ` | Root log level: ` DEBUG ` , ` INFO ` , ... |
37+ | ` use_json ` | ` bool ` | ` True ` | JSON lines vs human-readable console output |
3338
3439### ` metrics `
3540
36- | Field | Type | Meaning |
37- | --- | --- | --- |
38- | ` enabled ` | ` bool ` | Start a standalone exposition server |
39- | ` host ` | ` str ` | Bind host for that server |
40- | ` port ` | ` int ` | Bind port for that server |
41- | ` prefix ` | ` str \| None ` | Metric name prefix, for backends that use one |
41+ | Field | Type | Default | Meaning |
42+ | --- | --- | --- | --- |
43+ | ` enabled ` | ` bool ` | ` False ` | Start a standalone exposition server |
44+ | ` host ` | ` str ` | ` "0.0.0.0" ` | Bind host for that server |
45+ | ` port ` | ` int ` | ` 9090 ` | Bind port for that server |
46+ | ` prefix ` | ` str \| None ` | ` None ` | Metric name prefix, for backends that use one |
47+
48+ ` host ` and ` port ` are read only when ` enabled ` is true and have no backend fallback; their
49+ defaults are the shipped model's.
4250
4351!!! note
4452
@@ -49,24 +57,24 @@ Sentry for something else does not touch your settings class.
4957
5058### ` tracing `
5159
52- | Field | Type | Meaning |
53- | --- | --- | --- |
54- | ` service_name ` | ` str ` | Resource service name ( falls back to ` AppSpec.service_name ` ) |
55- | ` collector_url ` | ` str \| None ` | OTLP endpoint; ` None ` means no exporter |
56- | ` sample_ratio ` | ` float ` | Ratio for the parent-based sampler |
57- | ` insecure ` | ` bool ` | Plaintext OTLP connection |
58- | ` enable_console_exporter ` | ` bool ` | Also print spans to stdout |
59- | ` excluded_urls ` | ` str \| None ` | Comma-separated paths to skip |
60+ | Field | Type | Default | Meaning |
61+ | --- | --- | --- | --- |
62+ | ` service_name ` | ` str ` | ` "" ` | Resource service name; empty falls back to ` AppSpec.service_name ` |
63+ | ` collector_url ` | ` str \| None ` | ` None ` | OTLP endpoint; ` None ` means no exporter |
64+ | ` sample_ratio ` | ` float ` | ` 1.0 ` | Ratio for the parent-based sampler |
65+ | ` insecure ` | ` bool ` | ` True ` | Plaintext OTLP connection |
66+ | ` enable_console_exporter ` | ` bool ` | ` False ` | Also print spans to stdout |
67+ | ` excluded_urls ` | ` str \| None ` | ` None ` | Comma-separated paths to skip |
6068
6169### ` error_tracking `
6270
63- | Field | Type | Meaning |
64- | --- | --- | --- |
65- | ` dsn ` | ` str \| None ` | Reporting endpoint; ** empty means the concern is off** |
66- | ` environment ` | ` str ` | Environment tag |
67- | ` traces_sample_rate ` | ` float ` | Performance-trace sampling |
68- | ` profiles_sample_rate ` | ` float ` | Profiling sampling |
69- | ` debug ` | ` bool ` | SDK debug mode |
71+ | Field | Type | Default | Meaning |
72+ | --- | --- | --- | --- |
73+ | ` dsn ` | ` str \| None ` | ` None ` | Reporting endpoint; ** empty means the concern is off** |
74+ | ` environment ` | ` str ` | ` "" ` | Environment tag; empty falls back to ` settings.environment ` |
75+ | ` traces_sample_rate ` | ` float ` | ` 0.0 ` | Performance-trace sampling |
76+ | ` profiles_sample_rate ` | ` float ` | ` 0.0 ` | Profiling sampling |
77+ | ` debug ` | ` bool ` | ` False ` | SDK debug mode |
7078
7179### Narrowing a section
7280
@@ -111,59 +119,87 @@ Your code never has to check whether metrics are configured.
111119
112120Error tracking is special: the section may exist while ` dsn ` is empty, which also counts as off.
113121
114- ## With pydantic-settings
122+ ## Shipped models
123+
124+ Install the ` settings ` extra and the four sections plus the composite come as pydantic models,
125+ carrying the defaults above:
115126
116- Anything with the right attribute names works. A typical real service:
127+ ``` bash
128+ pip install " servicewright[settings]"
129+ ```
117130
118131``` python
119- from pydantic import BaseModel
120- from pydantic_settings import BaseSettings, SettingsConfigDict
132+ from pydantic_settings import SettingsConfigDict
121133
134+ from servicewright.adapters.settings import BaseServiceSettings
122135
123- class LoggingSettings (BaseModel ):
124- level: str = " INFO"
125- use_json: bool = True
126136
137+ class Settings (BaseServiceSettings ):
138+ model_config = SettingsConfigDict(env_file = " .env" )
139+
140+ app_version: str = " 1.4.0"
141+ database_dsn: str
142+ ```
143+
144+ ``` bash
145+ LOGGING__LEVEL=DEBUG TRACING__COLLECTOR_URL=otel:4317 python main.py
146+ ```
127147
128- class MetricsSettings (BaseModel ):
129- enabled: bool = False
130- host: str = " 0.0.0.0"
131- port: int = 9090
132- prefix: str | None = None
148+ ` BaseServiceSettings ` is a ` pydantic_settings.BaseSettings ` with ` env_nested_delimiter="__" ` , the
149+ four sections, ` environment ` (default ` "local" ` ), ` app_version ` (default ` "0.0.0" ` ) and a
150+ ` get_app_version() ` returning it. Your ` model_config ` is merged with the base one, so an
151+ ` env_file ` or an ` env_prefix ` of yours keeps the ` __ ` nesting.
133152
153+ ### What is on by default
134154
135- class TracingSettings (BaseModel ):
136- service_name: str = " "
137- collector_url: str | None = None
138- sample_ratio: float = 1.0
139- insecure: bool = True
140- enable_console_exporter: bool = False
141- excluded_urls: str | None = None
155+ | Section | Default | Why |
156+ | --- | --- | --- |
157+ | ` logging ` | ` LoggingSettings() ` — ` INFO ` , JSON | you want logs |
158+ | ` metrics ` | ` MetricsSettings() ` — sink on, exposition server off | inert until something records |
159+ | ` error_tracking ` | ` ErrorTrackingSettings() ` — no ` dsn ` , so off | switches on from ` ERROR_TRACKING__DSN ` alone |
160+ | ` tracing ` | ` None ` | a present section installs a tracer provider; ` TRACING__COLLECTOR_URL=... ` creates it |
142161
162+ A section typed ` TracingSettings | None ` is built from its nested variables the moment one is
163+ set, so ` TRACING__COLLECTOR_URL=otel:4317 ` is all it takes to switch tracing on.
143164
144- class Settings (BaseSettings ):
145- model_config = SettingsConfigDict(env_nested_delimiter = " __" , env_file = " .env" )
165+ A present section still activates its backend at bootstrap, which needs that backend's extra
166+ installed — ` observability ` for ` structlog ` and ` otel ` , ` metrics ` for ` prometheus ` . Otherwise set
167+ the section to ` None ` or select another backend in [ ` ObsConfig ` ] ( observability.md ) . The ` settings `
168+ extra itself pulls in nothing but pydantic-settings.
146169
147- app_version: str = " 0.0.0"
148- environment: str = " local"
170+ ### Validation instead of silent fallbacks
149171
150- logging: LoggingSettings = LoggingSettings()
151- metrics: MetricsSettings = MetricsSettings()
152- tracing: TracingSettings | None = None
153- error_tracking: None = None
172+ The models validate what the backends assume: the log level must be one of ` LogLevelStr `
173+ (case-insensitively, so ` LOGGING__LEVEL=debug ` is fine while ` warn ` is a load-time error rather
174+ than a silent ` INFO ` ), the sample ratios are bounded to ` [0, 1] ` , the metrics port to a port.
154175
155- def get_app_version (self ) -> str :
156- return self .app_version
157- ```
176+ ### Disabling and narrowing
158177
159- ``` bash
160- LOGGING__LEVEL=DEBUG METRICS__PORT=9100 python main.py
178+ Exactly as with a hand-written class: a section annotated ` None ` is off, a section model can be
179+ subclassed to narrow or extend it, and a default can be replaced:
180+
181+ ``` python
182+ from typing import Literal
183+
184+ from servicewright.adapters.settings import BaseServiceSettings, LoggingSettings, TracingSettings
185+
186+
187+ class StrictLogging (LoggingSettings ):
188+ level: Literal[" INFO" , " WARNING" , " ERROR" ] = " INFO"
189+
190+
191+ class Settings (BaseServiceSettings ):
192+ logging: StrictLogging = StrictLogging()
193+ tracing: TracingSettings = TracingSettings(sample_ratio = 0.1 ) # on, sampling 10 %
194+ metrics: None = None # off
161195```
162196
163- !!! note
197+ ### Writing your own
164198
165- servicewright never imports pydantic. The example above works because the attributes line up,
166- not because of any integration.
199+ Anything with the right attribute names still works — a frozen dataclass, a plain class, a
200+ pydantic-settings class of your own; [ Your first service] ( ../getting-started/first-service.md )
201+ shows the smallest one. The kernel never imports pydantic: the models live in
202+ ` servicewright.adapters.settings ` , behind their extra, like every other binding.
167203
168204## What is * not* in settings
169205
0 commit comments