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