zoukankan      html  css  js  c++  java
  • 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()
    
  • 相关阅读:
    比较全的笔记
    ios路线
    字符串颜色
    ios 开发学习步骤
    百度地图反地理
    p12证书
    ios官方demo
    ios视频网盘
    图片穿透
    OC温习一:基本数据类型
  • 原文地址:https://www.cnblogs.com/minding/p/12957939.html
Copyright © 2011-2022 走看看