• python 的日志相关应用


    python日志主要用logging模块;

    示例代码如下:

    #coding:utf-8
    import  logging
    
    
    class logger():
        '''
        %(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
        '''
        format_dict = {
           1 : logging.Formatter('%(asctime)s - %(filename)s-[line:%(lineno)d]-%(name)s - %(levelname)s - %(message)s'),
           2 : logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
           3 : logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
           4 : logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
           5 : logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        }
    
    
        def __init__(self, logname, loglevel, logger):
            '''
               指定保存日志的文件路径,日志级别,以及调用文件
               将日志存入到指定的文件中
            '''
    
            # 创建一个logger
            self.logger = logging.getLogger(logger)
            self.logger.setLevel(logging.DEBUG)
    
            # 创建一个handler,用于写入日志文件
            fh = logging.FileHandler(logname)
            fh.setLevel(logging.DEBUG)
    
            # 再创建一个handler,用于输出到控制台
            ch = logging.StreamHandler()
            ch.setLevel(logging.DEBUG)
    
            # 定义handler的输出格式
            #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            formatter =self.format_dict[int(loglevel)]
            fh.setFormatter(formatter)
            ch.setFormatter(formatter)
    
            # 给logger添加handler
            self.logger.addHandler(fh)
            self.logger.addHandler(ch)
    
        def __init__(self,loglevel, logger):
            '''
               指定保存日志的文件路径,日志级别,以及调用文件
               将日志存入到指定的文件中
            '''
    
            # 创建一个logger
            self.logger = logging.getLogger(logger)
            self.logger.setLevel(logging.DEBUG)
    
            # 再创建一个handler,用于输出到控制台
            ch = logging.StreamHandler()
            ch.setLevel(logging.DEBUG)
    
            # 定义handler的输出格式
            #formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            formatter =self.format_dict[int(loglevel)]
            ch.setFormatter(formatter)
    
            # 给logger添加handler
            self.logger.addHandler(ch)
    
    
        def getlog(self):
            return self.logger
    
    
    if __name__ == '__main__':
        logger = logger(loglevel=2, logger="log").getlog()
        logger.info("we are the world!!!!")
  • 相关阅读:
    idea用法
    pagehelper用法
    mybatis
    多线程2
    radio 标签状态改变时 触发事件
    多线程
    a标签点击后,给a标签添加样式
    servlet
    mybatis 查询
    springmvc 发送PUT 和 DELETE 请求
  • 原文地址:https://www.cnblogs.com/mlmy/p/6295132.html
Copyright © 2020-2023  润新知