Pydantic
Pydantic Logfire has a Pydantic Validation plugin to instrument Pydantic Validation models. The plugin provides logs and metrics about model validation.
To enable the plugin, do one of the following:
- Set the
LOGFIRE_PYDANTIC_PLUGIN_RECORDenvironment variable toall. - Set
pydantic_plugin_recordinpyproject.toml, e.g:
[tool.logfire]
pydantic_plugin_record = "all"
- Call
logfire.instrument_pydanticwith the desired configuration, e.g:
import logfire
logfire.instrument_pydantic() # Defaults to record='all'
Note that if you only use the last option then only model classes defined and imported after calling logfire.instrument_pydantic
will be instrumented.
By default, third party modules are not instrumented by the plugin to avoid noise. You can enable instrumentation for those
using the include configuration.
import logfire
logfire.instrument_pydantic(include={'openai'})
You can also disable instrumentation for your own modules using the
exclude configuration.
import logfire
logfire.instrument_pydantic(exclude={'app.api.v1'})
If you want more granular control over the plugin, you can use the
plugin_settings class parameter in your Pydantic models.
from pydantic import BaseModel
from logfire.integrations.pydantic import PluginSettings
class Foo(BaseModel, plugin_settings=PluginSettings(logfire={'record': 'failure'})): ...
The record argument is used to configure what to record.
It can be one of the following values:
all: Send traces and metrics for all events. This is default value forlogfire.instrument_pydantic.failure: Send metrics for all validations and traces only for validation failures.metrics: Send only metrics.off: Disable instrumentation.
<!—
Sampling can be configured by trace_sample_rate key in
plugin_settings.
from pydantic import BaseModel
class Foo(BaseModel, plugin_settings={'logfire': {'record': 'all', 'trace_sample_rate': 0.4}}): ...
—>
Tags are used to add additional information to the traces, and metrics. They can be included by
adding the tags key in
plugin_settings.
from pydantic import BaseModel
class Foo(BaseModel, plugin_settings={'logfire': {'record': 'all', 'tags': ('tag1', 'tag2')}}): ...