美文网首页
为项目添加log记录

为项目添加log记录

作者: LittleJessy | 来源:发表于2018-12-17 21:58 被阅读0次
    1. 工作目录中新建log文件夹,用来存放log日志
      settings.py文件添加日志路径配置
    # 日志配置
    BASE_LOG_DIR = os.path.join(BASE_DIR, "log")
    
    1. public文件夹下新增log.py文件
    # _*_ coding:utf-8 _*_
    import time
    import logging
    from QAPlatform.settings import BASE_LOG_DIR
    
    # 定义日志名称,每天生成一个日志文件
    timer = time.strftime("%y-%m-%d", time.localtime(time.time()))
    global logname
    logname = BASE_LOG_DIR + r"\log" + timer + ".txt"
    
    class Log:
        def __init__(self,level="INFO"):
            print ("start")
            self.filename=logname
            self.level=level
            self.logger=logging.getLogger() #得到logger实体
            self.logger.setLevel(logging.DEBUG)#设置日志最低输出级别默认为WARN
            self.formatter=logging.Formatter("[%(asctime)s - %(filename)s] - %(levelname)s : %(message)s")#设置日志格式
    
        def __createHandler(self):
            #创建FileHandler,日志输入到文件
            fh=logging.FileHandler(self.filename,'a',encoding='utf-8')
            fh.setLevel(logging.DEBUG)
            fh.setFormatter(self.formatter)
            self.logger.addHandler(fh)
    
            # 创建FileHandler,日志输入到控制台
            ch = logging.StreamHandler()
            ch.setLevel(logging.DEBUG)
            ch.setFormatter(self.formatter)
            self.logger.addHandler(ch)
            return fh,ch
    
        def __console(self,message):
            if self.level == "INFO":
                self.logger.info(message)
            if self.level == "DEBUG":
                self.logger.debug(message)
            if self.level == "WARN":
                self.logger.warn(message)
            if self.level == "ERROR":
                self.logger.error(message)
    
        def __call__(self,fuc):
            def wrapper(*args,**kwargs):
                fh, ch=self.__createHandler()
                for i in range(len(args)):
                    self.__console(args[i])
                self.logger.removeHandler(fh)
                self.logger.removeHandler(ch)
                fuc(*args, **kwargs)
            return wrapper
    
    
    @Log(level="INFO")
    def writeLog_info(message):
        print(message)
    
    @Log(level="DEBUG")
    def writeLog_debug(message):
        print(message)
    
    @Log(level="WARN")
    def writeLog_warn(message):
        print(message)
    
    @Log(level="ERROR")
    def writeLog_error(message):
        print(message)
    
    1. view.py文件中的使用,已登录为例:
    from public.utils import login_Check
    from public.log import *
    from rbac.service.init_permission import init_permission
    
    def login(request):
        if request.method == "GET":
            return render(request, "login.html")
        if request.method == "POST":
            username = request.POST.get('form-username')
            password = request.POST.get('form-password')
    
            user_obj = UserInfo.objects.filter(username=username, password=password).first()
            try:
                if user_obj:
                    try:
                        init_permission(request, user_obj)  # 调用init_permission,初始化权限
                        writeLog_info(u"用户%s:权限初始化成功!" % username)
                    except Exception as e:
                        writeLog_error(u"用户%s:权限初始化失败:%s" % (username,str(e)))
                    try:
                        request.session["user_id"] = user_obj.pk
                        request.session["Username"] = username
                        print("==========session保存:", request.session['Username'])
                        writeLog_info(u"用户%s保存session:%s" % (username,request.session))
                    except Exception as e:
                        writeLog_error(u"用户%s保持session失败:%s" % (username, str(e)))
                    try:
                        t = 300
                        request.session.set_expiry(t)  # 设置session有效期为60s*5=5分钟
                        writeLog_info(u"设置session有效期:%s分钟" % (int(t/60)))
                    except Exception as e:
                        writeLog_error(u"设置session有效期失败:%s" % (str(e)))
    
                    writeLog_info(u"用户%s:登录成功" % username)
                    return HttpResponseRedirect("/index/")
            except Exception as e:
                writeLog_error(u"登录失败:%s"%(str(e)))
                return render(request, "login.html", {"error": "Username and Password is error"})
    

    相关文章

      网友评论

          本文标题:为项目添加log记录

          本文链接:https://www.haomeiwen.com/subject/prkhkqtx.html