Skip to content

Pydantic

Logfire has a Pydantic plugin to instrument Pydantic models. The plugin provides logs and metrics about model validation.

To enable the plugin, do one of the following:

  • Set the LOGFIRE_PYDANTIC_PLUGIN_RECORD environment variable to all.
  • Set pydantic_plugin_record in pyproject.toml, e.g:
[tool.logfire]
pydantic_plugin_record = "all"
import logfire

logfire.configure(pydantic_plugin=logfire.PydanticPlugin(record='all'))

Note that if you only use the last option then only models defined and imported after calling logfire.configure will be instrumented.

Third party modules

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.configure(pydantic_plugin=logfire.PydanticPlugin(record='all', include={'openai'}))

You can also disable instrumentation for your own modules using the exclude configuration.

import logfire

logfire.configure(pydantic_plugin=logfire.PydanticPlugin(record='all', exclude={'app.api.v1'}))

Model configuration

If you want more granular control over the plugin, you can use the plugin_settings class parameter in your Pydantic models.

from logfire.integrations.pydantic import PluginSettings
from pydantic import BaseModel


class Foo(BaseModel, plugin_settings=PluginSettings(logfire={'record': 'failure'})):
    ...

Record

The record is used to configure what to record. It can be one of the following values:

  • off: Disable instrumentation. This is default value.
  • all: Send traces and metrics for all events.
  • failure: Send metrics for all validations and traces only for validation failures.
  • metrics: Send only metrics.

Tags

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')}}
):