logging 日志完整应用实例

日志文件函数:日志相关设置
logfile.py

import logging
def logg():
    # LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(filename)s, line:%(lineno)d - %(message)s" # 带有文件名、行号
    DATE_FORMAT = "%Y-%m-%d %H:%M:%S"
    
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)  #这里设置日志的级别
    
    # 输出到文件
    file_handler = logging.FileHandler("all.log", mode='a', encoding='utf-8')
    
    # 输出到控制台
    stream_handler = logging.StreamHandler()
    
    # 错误日志单独输出到一个文件
    error_handler = logging.FileHandler('error.log', mode='a', encoding='utf-8')
    error_handler.setLevel(logging.ERROR)  #注意这里,错误日志只记录ERROR级别的日志
    
    # 将所有的处理器加入到logger中
    logger.addHandler(file_handler)
    logger.addHandler(stream_handler)
    logger.addHandler(error_handler)
    
    formatter = logging.Formatter(fmt=LOG_FORMAT, datefmt=DATE_FORMAT)
    
    # 设置格式化
    file_handler.setFormatter(formatter)
    stream_handler.setFormatter(formatter)
    error_handler.setFormatter(formatter)
    
    logger.info('info级别的')
    logger.error('error级别')
    logger.debug('debug级别')
    logger.warning('warning级别')
logg()

应用用文件uploadAPI.py调用日志文件方法
uploadAPI.py


from flask import Flask, jsonify , request,render_template,redirect,url_for
import os
from flask import send_from_directory
from werkzeug.utils import secure_filename 
import logging
import traceback  
from logfile import logg
'''
logging.basicConfig(filename='log_record.txt',
                    filemode='w', format='[%(asctime)s] [%(levelname)s] >>>  %(message)s',
                    level=logging.DEBUG,
                    datefmt='%Y-%m-%d %I:%M:%S'
                    
                    )'''

try:
    app = Flask(__name__)

    #UPLOAD_FOLDER = r'..\pythonproject01\flask\caiquan2\media'
    UPLOAD_FOLDER = r'..\media' 
    #UPLOAD_FOLDER = r'D:\pythonXangmu\pythonproject01\flask\caiquan2\media'
    ff = os.path.abspath(UPLOAD_FOLDER)
    print('路径',ff)
    ALLOWED_EXTENSIONS = set(['txt','pdf','png','jpg','jpeg','doc'])
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER#设置上传文件存储路径
    def allowed_file(filename):
        houzui_name = "."in filename and filename.rsplit('.',1)[1].lower()
        #return houzui_name in ALLOWED_EXTENSIONS
        #print('#####',houzui_name in ALLOWED_EXTENSIONS)#True

        if  houzui_name in ALLOWED_EXTENSIONS :
            return '上传成功'
        elif  houzui_name not in ALLOWED_EXTENSIONS :
            return '上传文件格式不支持'
    @app.route('/')
    def index():
        return render_template('upload.html')   

    @app.route('/center/upload',methods=['POST'])#对应表单里面的action="/upload"
    def center():
        if "file" not in request.files: #"file" 对应前端upload.html 中的name
            return redirect(request.url)#redirect 重定向新的地址

        file = request.files.get('file')  # 获取文件
        if not file :#如果文件为空
            return "请选择文件"
            
            
        if not allowed_file(file.filename): #如果不是传入的指定格式文件。重定向到当前url
            #return redirect(request.url)
            return redirect('www.baidu.com')

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  # 用这个函数确定文件名称是否是安全
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))  # 保存文件  os.path.join把目录和文件名合成一个路径
            return redirect(url_for('show', filename=filename))


    # 展示
    @app.route('/show/')
    def show(filename):
        # send_from_directory可以从目录加载文件
        return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000, debug=True)

except Exception as ee:
   # logging.error('main programe error')
   # logging.error(ee)
    #logging.error(ee)
    #logging.error(traceback.format_exc)
    # logger.info('info级别的')
    # logger.error('error级别')
    # logger.debug('debug级别')
    # logger.warning('warning级别')
    logg()#调用日志文件中的函数方法
    


关联html文件
upload.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传title>
head>
<body>
    <form action="/center/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" >
        <input type="submit"  value="提交">
    form>
    
body>
html>

https://blog.csdn.net/nikeylee/article/details/109768064

你可能感兴趣的:(Python,Python自动化,logging)