madtyn
madtyn

Reputation: 1549

Python logging SMTPHandler not working

I have done and tried this code in Python 3 for sending me an email when exceptions happen, but the STMPHandler is not working. It works perfectly with the same args and values for SMTPHandler and the same code copy-pasted from this answer

Working code:

import logging.handlers

smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.gmail.com", 587),
                                            fromaddr="[email protected]",
                                            toaddrs="[email protected]",
                                            subject=u"Alfred error!",
                                            credentials=("[email protected]", "asdasdasdasdasd"),
                                            secure=())


logger = logging.getLogger()
logger.addHandler(smtp_handler)

try:
    raise Exception()
except Exception as e:
    logger.exception('Unhandled Exception')

All handlers are doing fine and the code from the answer works just with the exception() call.

I can't understand why this is not working.

log_config.py (not working code):

import os

import logging
import logging.handlers

version = "2.0.0"
LOGFILE_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'log', 'my_app.log')
logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.DEBUG)
logging.getLogger('telegram').setLevel(logging.WARNING)
logging.getLogger('chardet.charsetprober').setLevel(logging.WARNING)


class TimedOutFilter(logging.Filter):
    def filter(self, record):
        if "Error while getting Updates: Timed out" in record.getMessage():
            return False


def getLogger(name):
    """
    Return a logger for the file
    :param name: the file name
    :return: a logger
    """
    global version
    logger = logging.getLogger(name)

    fh = logging.handlers.TimedRotatingFileHandler(LOGFILE_PATH, when='midnight')
    formatter = logging.Formatter('%(asctime)s - ({0}) %(name)s - %(levelname)s - %(message)s'.format(version))
    fh.setFormatter(formatter)
    fh.addFilter(TimedOutFilter())
    fh.setLevel(logging.DEBUG)
    logger.addHandler(fh)

    if os.environ.get('SERVER', True):
        mh = logging.handlers.SMTPHandler(mailhost=("smtp.gmail.com", 587),
                                          fromaddr="[email protected]",
                                          toaddrs="[email protected]",
                                          subject=u"Alfred error!",
                                          credentials=("[email protected]", "asdasdasdasdasd"),
                                          secure=())
        mh.setFormatter(formatter)
        mh.addFilter(TimedOutFilter())
        mh.setLevel(logging.ERROR)
        logger.addHandler(mh)

    ch = logging.StreamHandler()
    formatter = logging.Formatter('{0} %(levelname)s - %(message)s'.format(version))
    ch.setFormatter(formatter)
    ch.addFilter(TimedOutFilter())
    ch.setLevel(logging.ERROR)
    logger.addHandler(ch)

    return logger


if __name__ == '__main__':
    logger = getLogger(__name__)
    try:
        raise Exception()
    except Exception as e:
        logger.exception('Unhandled Exception')
        logger.error('an error line')
        logger.debug('a debug line')

Upvotes: 1

Views: 2314

Answers (1)

madtyn
madtyn

Reputation: 1549

The timedOutFilter was ruining everything because it only returned False but never True.

So just doing:

class TimedOutFilter(logging.Filter):
    def filter(self, record):
        if "Error while getting Updates: Timed out" in record.getMessage():
            return False
        return True  # <==== Added this line only

fixed the whole thing.

Upvotes: 2

Related Questions