Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sentry integration #509

Closed
fratambot opened this issue Sep 16, 2021 · 3 comments
Closed

Sentry integration #509

fratambot opened this issue Sep 16, 2021 · 3 comments
Labels
documentation Improvements or additions to documentation

Comments

@fratambot
Copy link

fratambot commented Sep 16, 2021

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 !

@Delgan
Copy link
Owner

Delgan commented Sep 24, 2021

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: getsentry/sentry-python#653 (comment)

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

@hillairet
Copy link
Contributor

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.

@Delgan
Copy link
Owner

Delgan commented Aug 27, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

No branches or pull requests

3 participants