loguru icon indicating copy to clipboard operation
loguru copied to clipboard

Sentry integration

Open fratambot opened this issue 3 years ago • 1 comments

I recently started to use loguru and it's amazing ! But sentry too is amazing !

It would be nice to have some integration, at least at the documentation level.

After crawling the web for hours I ended up with this setup which seems to work:

In my main app (FastApi), where I initialize sentry, I have:

import logging
from logger import logger
from sentry_sdk.integrations.logging import (
    LoggingIntegration,
    BreadcrumbHandler,
    EventHandler,
)

#...

dsn = os.environ.get("SENTRY_DSN")
if dsn is not None:
    sentry_sdk.init(
        dsn,
        environment=os.environ.get("SENTRY_ENVIRONMENT", "local"),
        integrations=[
            LoggingIntegration(level=None, event_level=logging.WARNING)
        ],
        traces_sample_rate=0.05,
    )

    # If Sentry is present, we add its handlers to our logger (loguru)
    logger.add(BreadcrumbHandler(level=logging.DEBUG), level=logging.DEBUG)
    logger.add(EventHandler(level=logging.ERROR), level=logging.ERROR)

else:
    logger.warning("SENTRY_DSN not found. Sentry won't be initialized")

In my logger.py I have:

# Logging
import logging
import sys
import os
import sentry_sdk.integrations.logging

from loguru import logger


LOG_LEVEL = logging.getLevelName(os.environ.get("LOG_LEVEL", "DEBUG"))
JSON_LOGS = True if os.environ.get("JSON_LOGS", "0") == "1" else False


class InterceptHandler(logging.Handler):
    def emit(self, record):
        try:
            level = logger.level(record.levelname).name
        except ValueError:
            level = record.levelno

        frame, depth = logging.currentframe(), 2
        while frame.f_code.co_filename in (logging.__file__, sentry_sdk.integrations.logging.__file__):
            frame = frame.f_back
            depth += 1

        msgs_to_filter = ["GET /status"]  # healthcheck calls

        for msg in msgs_to_filter:
            if msg not in record.getMessage():

                logger.opt(depth=depth, exception=record.exc_info).log(
                    level, record.getMessage()
                )


def setup_logging():
    logging.captureWarnings(True)
    logging.root.handlers = [InterceptHandler()]
    logging.root.setLevel(LOG_LEVEL)

    for name in logging.root.manager.loggerDict.keys():
        logging.getLogger(name).handlers = []
        logging.getLogger(name).propagate = True

    logger.configure(handlers=[{"sink": sys.stdout, "serialize": JSON_LOGS}])


setup_logging()

I hope some clear documentation on loguru/sentry integration might come out from this draft in order to help future users of both !

fratambot avatar Sep 16 '21 15:09 fratambot

Hi @fratambot, thanks for sharing a this code snippet!

I'm not familiar with Sentry so it's hard for me to produce appropriate documentation.

Your solution looks somehow similar to this one shared in another ticket: https://github.com/getsentry/sentry-python/issues/653#issuecomment-788854865

It seems combining BreadcrumbHandler, EventHandler and LoggingIntegration is the way to go.

Delgan avatar Sep 24 '21 16:09 Delgan

Hello @Delgan The sentry-python package now has a loguru integration so this issue doesn't seem quite relevant, at least not the suggested snippet.

Would it be useful for the Loguru docs to reference the sentry integration in the "Code snippets and recipes"? I'm happy to submit a paragraph for that.

hillairet avatar Aug 26 '23 16:08 hillairet

Hi @hillairet.

I noticed that Sentry has incorporated support for Loguru, although I hadn't delved into the details yet. The implementation appears very clean. Thanks a lot to @PerchunPak for the hard work!

Following your suggestion, I'm closing this ticket since an official solution is now available.

In my opinion, the Sentry documentation effectively outlines the integration process between Loguru and Sentry. It doesn't seem necessary to duplication this information in the Loguru documentation. After all, it's a Sentry feature built upon on top of Loguru, rather than the other way around. I assume individuals searching for "Sentry integration with Loguru" on their preferred search engine will easily figure out the relevant documentation.

Delgan avatar Aug 27 '23 16:08 Delgan