python web(bottle框架)知行合一之-简单知识付费平台-”全栈“实践(19)---应用多日志文件记录

python web(bottle框架)知行合一之-简单知识付费平台-”全栈“实践(19)---应用多日志文件记录

PS:笔记只是为了更好表达我怎么语言表述,有些时候可能难免废话一推!
因知识有限, 如有错误, 欢迎指正!

背景

应用的日志的必要性是必不可缺的,当应用出现什么错误信息,或找对应的请求日志的时候,我们都是需要核对的,所以相关运维角度来说,日志还是很有必要的。

定义日志的错误维度需求

  • 区分开错误的日志 和请求的日志 或 警告日志

logger_helper.py

#!/usr/bin/evn python
# coding=utf-8
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +
#        ┏┓   ┏┓+ +
#    ┏┛┻━━━┛┻┓ + +
#    ┃       ┃  
#    ┃   ━   ┃ ++ + + +
#    ████━████ ┃+
#    ┃       ┃ +
#    ┃   ┻   ┃
#    ┃       ┃ + +
#    ┗━┓   ┏━┛
#      ┃   ┃           
#      ┃   ┃ + + + +
#      ┃   ┃    Codes are far away from bugs with the animal protecting   
#      ┃   ┃ +     神兽保佑,代码无bug  
#      ┃   ┃
#      ┃   ┃  +         
#      ┃    ┗━━━┓ + +
#      ┃        ┣┓
#      ┃        ┏┛
#      ┗┓┓┏━┳┓┏┛ + + + +
#       ┃┫┫ ┃┫┫
#       ┗┻┛ ┗┻┛+ + + +
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +"""
"""
Author = zyx
@Create_Time: 2018/4/29 15:49
@version: v1.0.0
@Contact: 308711822@qq.com
@File: logger_helper.py
@文件功能描述:
"""''

import logging, logging.handlers
import sys
import os


class Logger:

    def __init__(self, logName, log_dir, _levels_tag='INFO', backupCount=10):
        self.logName = logName
        self.log_dir = log_dir
        self._levels_tag = _levels_tag

        # 如果不存在log文件夹, 则再当前脚本目录下创建log文件夹存放日志文件-
        if not os.path.exists('log'): os.mkdir('log')
        # 定义日志目录
        self.log_dir = os.path.join(log_dir, 'log')

        self._logfmt = '%Y-%m-%d %H:%M:%S'
        self._logger = logging.getLogger(self.logName)
        self.logFile = os.path.join(self.log_dir, '{0}.log'.format(self.logName))
        handler = logging.handlers.TimedRotatingFileHandler(filename=self.logFile,
                                                            backupCount=backupCount,
                                                            when="midnight")
        handler.suffix = "%Y%m%d"
        formatter = logging.Formatter(
            '[ %(levelname)s ] %(asctime)s %(filename)s:%(threadName)s:%(lineno)d %(message)s', datefmt=self._logfmt)
        handler.setFormatter(formatter)
        self._logger.addHandler(handler)
        # 日志等级
        self._levels = {
            "DEBUG": logging.DEBUG,
            "INFO": logging.INFO,
            "WARNING": logging.WARNING,
            "ERROR": logging.ERROR,
            "CRITICAL": logging.CRITICAL
        }
        self._logger.setLevel(self._levels.get(self._levels_tag))

    @property
    def getLogger(self):
        return self._logger

logging_helper.py

#!/usr/bin/evn python
# coding=utf-8
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +
#        ┏┓   ┏┓+ +
#    ┏┛┻━━━┛┻┓ + +
#    ┃       ┃  
#    ┃   ━   ┃ ++ + + +
#    ████━████ ┃+
#    ┃       ┃ +
#    ┃   ┻   ┃
#    ┃       ┃ + +
#    ┗━┓   ┏━┛
#      ┃   ┃           
#      ┃   ┃ + + + +
#      ┃   ┃    Codes are far away from bugs with the animal protecting   
#      ┃   ┃ +     神兽保佑,代码无bug  
#      ┃   ┃
#      ┃   ┃  +         
#      ┃    ┗━━━┓ + +
#      ┃        ┣┓
#      ┃        ┏┛
#      ┗┓┓┏━┳┓┏┛ + + + +
#       ┃┫┫ ┃┫┫
#       ┗┻┛ ┗┻┛+ + + +
# + + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + ++ + + +"""
"""
Author = zyx
@Create_Time: 2018/4/28 16:57
@version: v1.0.0
@Contact: 308711822@qq.com
@File: logging_helper.py
@文件功能描述:
有时候会报错,是因为有些日志文件生成的所属的权限有问题,删除了对应的文件之后就可以了!!!比较奇怪
PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问
"""
import logging
import os
import traceback
from basic.utils import except_helper


def init(pro_path=''):
    # 如果不存在log文件夹, 则再当前脚本目录下创建log文件夹存放日志文件-
    if not os.path.exists('log'):
        os.mkdir('log')
    # 定义日志目录
    log_path = os.path.join(pro_path, 'log')
    # print('当前日志路径------', log_path)

    # 定义日志输出格式-输出是信息等级的
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        filename="%s/info.log" % log_path,
                        filemode='a')


from basic.utils.logger_helper import Logger

# 系统的日志对象
syslog = None


def sys_log_init(logName, log_dir):
    global syslog
    if not syslog:
        syslog = Logger(logName, log_dir).getLogger
    # reqlog = logger2.Logger("req",pro_path).getLogger


def sys_info_write(message):
    syslog.info(message)


def sys_write_error(content='', is_send_mail=True):
    """记录错误日志信息"""
    if traceback:
        content = content + '\n' + traceback.format_exc() + '\n'
    # 获取程序当前运行的堆栈信息
    detailtrace = except_helper.detailtrace()
    content = content + '程序调用堆栈的日志:' + detailtrace + '\n'
    syslog.error(content)


# =============================================
# 请求的日志对象
reqlog = None


def req_log_init(logName, log_dir):
    global reqlog
    if not reqlog:
        reqlog = Logger(logName, log_dir).getLogger
    # reqlog = logger2.Logger("req",pro_path).getLogger


def req_info_write(message):
    reqlog.info(message)


# 请求的日志对象
error_log = None


def error_log_init(logName, log_dir):
    global error_log
    if not error_log:
        error_log = Logger(logName, log_dir).getLogger
    # reqlog = logger2.Logger("req",pro_path).getLogger


def error_log_write(content='', is_send_mail=True):
    """记录错误日志信息"""
    if traceback:
        content = content + '\n' + traceback.format_exc() + '\n'
    # 获取程序当前运行的堆栈信息
    detailtrace = except_helper.detailtrace()
    content = content + '程序调用堆栈的日志:' + detailtrace + '\n'
    error_log.error(content)

# syslog.info("sys hello info")
# syslog.debug("sys hello debug")
# syslog.error("sys hello error")
# syslog.warning("sys hello warning")
#
# reqlog.info("req hello info")
# reqlog.debug("req hello debug")
# reqlog.error("req hello error")
# reqlog.warning("req hello warning")

初始化及调用

image.png

image.png
image.png
image.png

可能遇到问题:
1.PermissionError: [WinError 32] 另一个程序正在使用此文件,进程无法访问
解决:
删除文件重新生成新的文件!

结束

以上笔记纯属个人学习实践总结,有兴趣的同学可以加群一起学习讨论QQ:30871182

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。