python logger

import os
import logging
from logging.handlers import TimedRotatingFileHandler
from logging import handlers
import socket

def logger(path, loggername=None):
    os.makedirs(path, exist_ok=True)
    if loggername is None:
        loggername = ''

    logger = logging.getLogger(loggername)
    logger.setLevel(logging.INFO)

    handler = TimedRotatingFileHandler(path,
                                       when="midnight", # midnight
                                       interval=1,
                                       backupCount=30)

    logFormatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
    handler.setFormatter(logFormatter)
    logger.addHandler(handler)

    return logger


def critical_email_logger():
    HOST = 'Host.com'
    FROM = 'email0@Host.com'
    TO = 'email1@Host.com,email2@Host.com'
    CREDENTIALS = ('email0@Host.com','email0passwd')

    SUBJECT = 'Critical Event From [Project Name]'

    # Setup logging
    logging.basicConfig(level=logging.INFO)
    handler = handlers.SMTPHandler(HOST, FROM, TO, SUBJECT,CREDENTIALS)
    email_logger = logging.getLogger('Critical email log')
    email_logger.addHandler(handler)
    email_logger.setLevel = logging.CRITICAL

    return email_logger


def test():
    log_file = "project_name.log"
    my_logger = logger(log_file,  "project_name")
    my_logger.info('this is a test')

    try:
        open('/path/to/does/not/exist', 'rb')
    except Exception as e:
        my_logger.error('Failed to open file', exc_info=True)
        email_logger = critical_email_logger()

        try:
            email_logger.critical('Critical Event Notification~~~~~~')
        except socket.error as error:
            my_logger.critical('Could not send email via SMTPHandler: %r', error)

if __name__ == "__main__":
    test()
posted @ 2020-05-25 17:10  keep-minding  阅读(140)  评论(0编辑  收藏  举报