Skip to content

Support custom formatter for LoggingIntegration #1352

@bityob

Description

@bityob

Problem Statement

We use in our code custom formatter for all our logging, and we want Sentry to use it with BreadcrumbHandler.

Currently there is no such option, and the default logging.Formatter is being used.

(
In the meantime in our code, we have two optional workarounds, but there are a bit hacky.

import sentry_sdk.integrations.logging as sentry_logging
import sentry_sdk

from src import CustomFormatter

SENTRY_DSN = "..."


class BreadcrumbHandlerWithCustomFormatter(sentry_logging.BreadcrumbHandler):
    def __init__(self, level):
        super(BreadcrumbHandlerWithCustomFormatter, self).__init__(level)
        self.setFormatter(CustomFormatter())

sentry_logging.BreadcrumbHandler = BreadcrumbHandlerWithCustomFormatter

sentry_sdk.init(
    dsn=SENTRY_DSN,
    integrations=[
        sentry_logging.LoggingIntegration(),
    ],
)
from sentry_sdk.integrations.logging import LoggingIntegration
import sentry_sdk

from src import CustomFormatter

SENTRY_DSN = "..."

log_integ = LoggingIntegration()
log_integ._breadcrumb_handler.setFormatter(CustomFormatter)

sentry_sdk.init(
    dsn=SENTRY_DSN,
    integrations=[
        log_integ,
    ],
)

Solution Brainstorm

I think there are two possible options how to support it.

First, add an optional argument for LoggingIntegration to specify a formatter -

class LoggingIntegration(Integration):
    identifier = "logging"

    def __init__(self, level=DEFAULT_LEVEL, event_level=DEFAULT_EVENT_LEVEL, formatter=None):
        # type: (Optional[int], Optional[int], Optional[logging.Formatter]) -> None
        self._handler = None
        self._breadcrumb_handler = None

        if level is not None:
            self._breadcrumb_handler = BreadcrumbHandler(level=level)
           if formatter:
               self._breadcrumb_handler.setFormatter(formatter())

Second option is to provide a set method for LoggingIntegration after initialization to update the formatter (like setFormatter).

I'll be happy to provide a PR for this if you agree,

Thanks.

Metadata

Metadata

Assignees

No one assigned
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions