zoukankan      html  css  js  c++  java
  • 日志记录类

    日志记录类

    import logging
    import os
    
    
    class LogRecorder:
        """日志记录类 单例"""
        _instance = None
    
        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = object.__new__(cls)
            return cls._instance
    
        def __init__(self, module_name, log_path):
            self.logger = logging.getLogger(module_name)
            self.logger.setLevel(logging.DEBUG)
            format_str = '%(asctime)s - %(levelname)s - %(filename)s:%(lineno)s - %(funcName)s - %(message)s'
            self.formatter = logging.Formatter(format_str)
            self.add_file_handler(log_path)
            self.add_console_handler()
    
        def add_file_handler(self, log_path):
            if os.path.exists(log_path):
                os.remove(log_path)
            # 文件记录
            file_handler = logging.FileHandler(log_path)
            file_handler.setLevel(logging.DEBUG)
            file_handler.setFormatter(self.formatter)
            self.logger.addHandler(file_handler)
    
        def add_console_handler(self):
            # 控制台记录
            console_handler = logging.StreamHandler()
            console_handler.setLevel(logging.DEBUG)
            console_handler.setFormatter(self.formatter)
            self.logger.addHandler(console_handler)
    
        def get_logger(self):
            return self.logger
    
    
    log_recorder = LogRecorder("cnblogs", "/root/cnblogs.log")
    logger = log_recorder.get_logger()
    
    抟扶摇而上者九万里
  • 相关阅读:
    python字典推导式
    什么是Python 自省
    类变量和实例变量
    Python 使用正则表达式匹配URL网址
    python is 和 “==”的区别
    阮一峰老师的bash教程,建议阅读
    python里的闭包
    什么是生成器
    python访问限制
    pytorch使用Tips
  • 原文地址:https://www.cnblogs.com/fengting0913/p/14547805.html
Copyright © 2011-2022 走看看