美文网首页
Python + logging 日志和日志文件(一天一个日志文

Python + logging 日志和日志文件(一天一个日志文

作者: 小玉1991 | 来源:发表于2021-06-09 15:53 被阅读0次

    项目中用日志,但是老的代码没有日志文件,查找错误很麻烦,我经过两个小时的摸索,写了个日志工具类。可以方便的集成日志。
    日志工具类自动生成Logs文件夹如下


    image.png
    log_helper.py
    import logging
    import os.path
    import time
    
    logging.basicConfig(format='%(asctime)s - %(levelname)s--->: %(message)s',
                        level=logging.DEBUG,
                        filemode='a')
    
    
    def createLogFile(name, level):
        # 创建一个logger
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)  # Log等级总开关
    
        # 创建一个handler,用于写入日志文件
        rq = time.strftime('%Y-%m-%d', time.localtime(time.time()))
        # log_date = rq[:10]
        log_path = os.getcwd() + '/Logs/'
        isExists = os.path.exists(log_path)
        # # 判断结果
        if not isExists:
            os.makedirs(log_path)
        log_name = os.getcwd() + '/Logs/{}-'.format(rq) + name + '.log'
        fh = logging.FileHandler(log_name, mode='a')
        fh.setLevel(level)  # 输出到file的log等级的开关
    
        # 定义handler的输出格式
        formatter = logging.Formatter("%(asctime)s - %(levelname)s--->: %(message)s")
        fh.setFormatter(formatter)
        logger.addHandler(fh)
    
    
    def print_info(info, *args):
        createLogFile("info", logging.INFO)
        if len(args) > 0:
            log = ""
            for arg in args:
                log += "{}"
            logging.info((info + log).format(*args))
        else:
            logging.info(info)
    
    
    def print_error(error, *args):
        createLogFile("error",logging.ERROR)
        if len(args) > 0:
            log = ""
            for arg in args:
                log += "{}"
            logging.error((error + log).format(*args))
        else:
            logging.error(error)
    
    def deleteBigFile(path):
        for file in os.listdir(path):
            fsize = os.path.getsize(f'{path}{file}')
            if (fsize > 1 * 1024 * 1024 * 1024):
                os.remove(f'{path}{file}')
    
    if __name__ == '__main__':
        createLogFile("info", logging.INFO)
    

    简单使用:

    app.py
    import json
    import time
    import log_helper
    
    from flask import Flask, request
    from waitress import serve
    
    from host_helper import HostManager
    from request_helper import api
    
    app = Flask(__name__)
    
    
    def access_log(fn):
        def wrapper():
            t_begin = time.time()
            res = fn()
            t_end = time.time()
            data = request.data.decode()
            print('url_params:{} \ncost:{} s \nres:{}\n'.format(data, t_end - t_begin, res[0:50]))
            return res
    
        return wrapper
    
    
    @app.route('/dispatch', methods=['POST'])
    @access_log
    def dispatch():
        data = request.data.decode()
        body = json.loads(data)
        headers = body.get('headers')
        params = body.get('params')
        url = body.get('url')
        method = body.get('method')
        proxy = body.get('proxy')
        timeout = body.get('timeout')
        res = api.exec(url=url, method=method, headers=headers, data=params, proxy=proxy, timeout=timeout)
        log_helper.print_info('url_params:{} \n res:{}\n'.format(data,  res[0:100]))
        return res
    
    

    另外可以用启动脚本,nohup 记录日志(nohup: 把输出追加到"nohup.out"),这个没有细细研究。有兴趣的同学可以研究一下。

    reboot.sh
    PID=`ps -ef |grep app.py | grep -v grep | awk '{print $2}'`
    echo ${PID}
    kill -9 ${PID}
    echo "shutdown this process"
    nohup python3 app.py &
    echo "reboot success"
    
    自动删除5天前的日志文件 auto-del-5-days-ago-log.sh
    #!/bin/sh
    
    #1、添加文件可运行权限
    #chmod +x /data/shell/bin/auto-del-5-days-ago-log.sh
    #2、打开系统 定时任务的配置
    # crontab -e
    #3、添加配置 每天0:00执行任务
    # 0 0 * * * /root/nezha-proxy/auto-del-5-days-ago-log.sh
    
    DIR=$(cd `dirname $0` ; pwd)
    echo "删除5天前的log日志" $DIR/Logs/
    find $DIR/Logs/ -mtime +5 -name "*.log" -exec rm -rf {} \;
    
    

    相关文章

      网友评论

          本文标题:Python + logging 日志和日志文件(一天一个日志文

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