python实现的logging写入日志的功能。logging模块还是挺好用的
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 # @Time : 2018/4/25 17:05 5 # @Author : zms 6 # @Site : 7 # @File : Log.py 8 # @Software: PyCharm Community Edition 9 10 import time 11 import logging 12 import os 13 from logging.handlers import RotatingFileHandler 14 15 project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 16 log_path = project_dir + r"\log\\" 17 18 19 class Log(logging.Logger): 20 def __init__(self, logname): 21 # super(MyLogger, self).__init__(filename) 22 filename = log_path + logname + ‘.log‘ 23 logging.Logger.__init__(self, filename) 24 25 # 设置日志格式 26 fmtHandler = logging.Formatter(‘%(asctime)s [%(filename)s:%(lineno)s][%(levelname)s] %(message)s‘) 27 28 # 终端log输出流设置 29 try: 30 consoleHd = logging.StreamHandler() 31 consoleHd.setLevel(logging.ERROR) 32 consoleHd.setFormatter(fmtHandler) 33 self.addHandler(consoleHd) 34 except Exception as reason: 35 self.error("%s" % reason) 36 37 # 设置log文件 38 try: 39 os.makedirs(os.path.dirname(filename)) 40 except Exception as reason: 41 pass 42 try: 43 # 设置回滚日志,每个日志最大10M,最多备份5个日志 44 fileHd = logging.handlers.RotatingFileHandler( 45 filename, maxBytes=10 * 1024 * 1024, backupCount=5) 46 # fileHd = logging.FileHandler(filename) 47 fileHd.setLevel(logging.INFO) 48 fileHd.setFormatter(fmtHandler) 49 self.addHandler(fileHd) 50 except Exception as reason: 51 self.error("%s" % reason) 52 53 return 54 55 56 57 if __name__ == ‘__main__‘: 58 test1 = Log(‘test1‘) 59 test2 = Log(‘test2‘) 60 while True: 61 test1.error("test1") 62 test2.error("test2")
原文地址:https://www.cnblogs.com/bluezms/p/8955427.html
时间: 2024-11-01 11:46:32