Skip to content

feat(logger): add OpenTelemetry-compatible log emission - #759

Open
Abhijeet Prasad (AbhiPrasad) wants to merge 2 commits into
mainfrom
abhi-logs
Open

Abhijeet Prasad (AbhiPrasad) wants to merge 2 commits into
mainfrom
abhi-logs

Conversation

@AbhiPrasad

@AbhiPrasad Abhijeet Prasad (AbhiPrasad) commented Sep 10, 2026

Copy link
Copy Markdown
Member

resolves https://linear.app/braintrustdata/issue/SDK-341/add-logging-api-to-python-sdk

AI Summary

Add first-class log emission to the project logger so applications can create independent type="log" rows without constructing spans manually.

  • Add Logger.emit_log(body, level, metadata).
  • Add trace(), debug(), info(), warn(), error(), and fatal() convenience methods.
  • Map the six base OpenTelemetry severities to context.otel.log.
  • Add SpanTypeAttribute.LOG.
  • Populate error from string bodies emitted at error or fatal severity.
  • Support named Python format parameters while retaining the original template and parameter values in metadata.

Usage

Emit directly or use a severity helper:

logger.error(
    "Payment failed",
    metadata={"payment_id": "pay_123"},
)

logger.emit_log(
    body="Retrying payment",
    level="info",
    metadata={"attempt": 2},
)

Log methods also accept named str.format parameters:

logger.info(
    "User {user_id} paid {amount:.2f}",
    user_id="user_123",
    amount=12.5,
    metadata={"source": "checkout"},
)

The row stores the rendered message in output:

User user_123 paid 12.50

It also retains the stable template and its parameters for querying and grouping:

{
    "source": "checkout",
    "braintrust.template": "User {user_id} paid {amount:.2f}",
    "braintrust.template.parameter.user_id": "user_123",
    "braintrust.template.parameter.amount": 12.5,
}

Missing parameters remain as placeholders, and malformed templates fall back to the original body so formatting errors do not disrupt application code. Bodies may remain non-string JSON values when no template parameters are supplied.

Trace correlation

Each log has a unique row ID and span ID unless it is correlated with an active span. A logger seeds one baseline trace ID when it is created, so consecutive unscoped logs from that logger remain grouped without grouping logs from separate logger instances.

helper -> emit_log -> type="log" row
                     |-- active span
                     |     trace_id = active trace_id
                     |     span_id  = active span_id
                     |
                     `-- no active span
                           trace_id = logger baseline trace_id
                           span_id  = newly generated span_id

This works with both native Braintrust spans and active OpenTelemetry spans through the existing context manager abstraction.

Testing

  • pytest src/braintrust/test_logger.py (209 passed)
  • nox -s test_types
  • nox -s pylint
  • OTel active-span correlation coverage
  • Ruff formatting and checks

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 10, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-14T15:27:44.810452Z fd6b734 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Add `Logger.emit_log()` so applications can emit independent `type="log"`
rows without constructing spans manually. Correlate rows with the active
Braintrust or OpenTelemetry context when available.

Seed each logger with a baseline trace ID for unscoped logs. This keeps
consecutive logs from one logger together while preserving unique row and span
IDs, and avoids grouping logs emitted by separate logger instances.

Map the six base OpenTelemetry severities into `context.otel.log` and add
`trace()`, `debug()`, `info()`, `warn()`, `error()`, and `fatal()` helpers.

    logger.error("Payment failed", metadata={"payment_id": "pay_123"})

    helper -> emit_log -> `type="log"` row
                         |-- active span: reuse trace/span IDs
                         `-- no span: reuse logger trace, generate span ID
Allow `emit_log()` and severity helpers to interpolate named parameters with
Python format strings. Preserve the original template and parameter values in
`braintrust.template` metadata so repeated messages remain queryable by their
stable structure.

Missing placeholders and malformed templates remain unchanged so logging does
not disrupt application code.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: fd6b7345e4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "Codex (@codex) review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "Codex (@codex) address that feedback".

)
rendered_metadata["braintrust.template"] = body
try:
rendered_body = body.format_map(_LogTemplateParameters(parameters))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve formatting for missing fields with format specs

When an omitted placeholder has a conversion or format specifier, such as logger.info("{user} owes {amount:.2f}", user="alice"), __missing__ supplies the string "{amount}", formatting that string as a float raises, and this broad fallback restores the entire original template. Consequently even supplied parameters are left uninterpolated, contrary to the documented behavior that only missing parameters remain as placeholders. Preserve the missing field's conversion/specifier instead of abandoning all rendering.

Useful? React with 👍 / 👎.

if parameters:
if not isinstance(body, str):
raise TypeError("Log body must be a string when template parameters are provided")
rendered_metadata = dict(metadata) if metadata is not None else {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize supported metadata before adding template attributes

When a caller combines template parameters with Pydantic-style metadata accepted by the rest of the logger API, this direct conversion can raise TypeError: an object implementing the supported model_dump() or dict() protocol is not necessarily iterable. The same metadata works when no template parameters are supplied because the normal event sanitizer handles those protocols, so logger.info("User {id}", metadata=model, id=...) unexpectedly emits no log. Retain the Metadata input contract and normalize it before merging the template attributes.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant