python logger

2021-01-09 20:31

阅读:526

标签:basic   from   count   name   port   erro   ack   exist   mail   

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()

python logger

标签:basic   from   count   name   port   erro   ack   exist   mail   

原文地址:https://www.cnblogs.com/minding/p/12957939.html


评论


亲,登录后才可以留言!