• Python 日志管理封装


    封装python中的logging方便日常使用

    class Logger(object):
        level_mapping = {
            'debug': logging.DEBUG,
            'info': logging.INFO,
            'warning': logging.WARNING,
            'error': logging.ERROR,
            'critical': logging.CRITICAL
        }  # 日志映射
    
        def __init__(self, filename, level='info', when='D', backCount=3,
                     fmt='%(asctime)s - [line:%(lineno)d] - %(levelname)s: %(message)s'):
            self.logger = logging.getLogger(filename)
            format_str = logging.Formatter(fmt)  # 设置格式
            self.logger.setLevel(self.level_mapping.get(level))  # 设置级别
            self.logger.propagate = False  # 关闭logger向上级传输
            stream = logging.StreamHandler()  # 流形式向屏幕输出
            stream.setFormatter(format_str)  # 流的显示的格式
            file = handlers.TimedRotatingFileHandler(filename=filename, when=when, backupCount=backCount,
                                                     encoding='utf-8')  # 往文件里写入
            # Calculate the real rollover interval, which is just the number of
            # seconds between rollovers.  Also set the filename suffix used when
            # a rollover occurs.  Current 'when' events supported:
            # S 秒
            # M 分
            # H 小时
            # D 天
            # W 每星期(interval==0时代表星期一)
            # midnight 凌晨
            file.setFormatter(format_str)  # 设置文件里写入的格式
            self.logger.addHandler(stream)  # 把对象加到logger里
            self.logger.addHandler(file)  # 把对象加到logger里

    封装logging的类以后,通过修改init中的参数来设置日志输出级别,样式,日志生成时间间隔,最大备份数等

    例如做一个小的网络监控小脚本运作日志输出:

    if __name__ == '__main__':
        ip = "www.google.com"  # 修改自己需要ping的路径
        path = os.path.join(os.path.dirname(__file__), 'pingLogs.log')
        # 日志存放位置
        log = Logger(filename=path)
        while True:
            time.sleep(1)
            ping = os.system("ping %s -n 1" % ip)  # ping 命令根据不同操作系统写不同ping格式  windows
            # ping = os.system('ping -c 1 -W 1 %s' % ip)  # ping 命令根据不同操作系统写不同ping格式  linux
            if ping == 0:
                log.logger.info('connection is ok and continue ping to %s' % ip)
                continue
            else:
                log.logger.error('server is disconnected for %s check your network' % ip)
                continue
  • 相关阅读:
    3dsmax不同版本 pyside qt UI 设置max窗口为父窗口的方法
    oracle中的数据库和实例
    oracle中的表空间(tablespace)、方案(schema)、段(segment)、区(extent)、块(block)
    什么是WSE
    Server.Transfer,Response.Redirect的区别
    Oracle 中的几个数据类型介绍
    oracle中的连接字符串
    Oracle中的 单引号 和 双引号
    接口是否可以继承接口?抽象类是否可以实现接口?抽象类是否可以继承实体类?
    聚簇索引
  • 原文地址:https://www.cnblogs.com/grandlulu/p/9804162.html
Copyright © 2020-2023  润新知