Search code examples
pythondjangosentry

Sentry.io ignore logger dynamically


I am hoping to dynamically add loggers to a file whenever I decide to ignore a certain logger from sending to sentry, I've read the docs and this answer How to ignore a logger in the Sentry Python SDK and I believe I got it working when I has put the literal string into the ignore_logger function.

When I try the below code, it doesn't ignore the logger, is there a better way to achieve this?

with suppress(FileNotFoundError):
    with open(os.path.join(SITE_ROOT, '..', 'sentry_ignore_logger.txt')) as f:
        for log_line in f:
            ignore_logger(log_line)

I had a print statement inside the loop to check it was reading the file and it printed as desired, so the issue isn't an incorrect file. The contents of the file are:

django.security.DisallowedHost

I'm using Djano and I've put this in my settings.py after the sentry_sdk.init (I had it before it, however that also didn't work)

Thanks


Solution

  • Ok I've changed my tack on this and instead of reading a flat file which didn't work for me, I've changed the file to a json structure and loaded the string as a json object and ignored the contents from the dictionary loaded into memory.

    with suppress(FileNotFoundError):
        with open(os.path.join(SITE_ROOT, '..', 'sentry_ignore_logger.json')) as f:
            ignore_logger_dict = json.loads(f.read())
            for logger_name in ignore_logger_dict.get('loggers'):
                ignore_logger(logger_name)
    

    The file contents are:

    {
        'loggers':
            [
                'django.security.DisallowedHost',
                'proj.module.submodule'
            ]
    }
    

    This seems to work for me and feels a bit more complete

    Now I just need to add a new entry to that array and restart apache or the app server and the new loggers are ignored

    Hope that helps