码迷,mamicode.com
首页 > 编程语言 > 详细

python logger

时间:2020-05-25 17:50:36      阅读:69      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!