一:项目架构

二:自定义日志类

1. 建立log.conf的配置文件

log.conf

[log]
LOG_PATH = /log/
LOG_NAME = info.log

2. 定义日志类

LogClass.py

import logging
from logging import handlers class Mylogger(object):
def __init__(self,log_path,log_name):
# 1.指明日志记录到哪个文件 "F:/xxx/xx" + "info.log"
logfile = log_path + log_name
# 2.配置日志操作器
handler = handlers.RotatingFileHandler(logfile, maxBytes=1024 * 1024, backupCount=5, encoding='utf-8')
# 3.设置日志格式
fmt = "%(levelname)s-%(asctime)s-%(module)s-%(lineno)d-%(message)s"
# 4. 配置格式实例
formatter = logging.Formatter(fmt)
# 5.操作器加载格式实例
handler.setFormatter(formatter)
# 6.创建logger实例
self.logger = logging.getLogger()
# 7.给实例增加日志操作器
self.logger.addHandler(handler)
# 8.给实例增加日志输出登记
self.logger.setLevel(logging.DEBUG)
  # 设置方法返回looger实例
def get_logger(self):
return self.logger

三:视图中使用logger日志

user_api.py

from flask import Flask,request,jsonify
from flask_cors import CORS
from log.LogClass import Mylogger
import os
import configparser
app = Flask(__name__)
CORS(app,supports_credentials=True)
# 1.获取根目录
root_path = os.path.split(os.path.realpath(__file__))[0]
# 2. 设置日志解析实例
cf = configparser.ConfigParser()
# 3.读取日志文件
cf.read(root_path+"/config/log.conf")
# 4. 创建自定义日志类的实例对象
logger = Mylogger(root_path + cf.get("log","LOG_PATH"),cf.get("log","LOG_NAME")).get_logger() @app.route("/index",methods=["POST","GET"])
def demo():
try:
print(1/0)
except Exception as e:
logger.error(e) if __name__ == '__main__':
app.run(debug=True)

运行程序后 访问 127.0.0.1:5000/index,在log文件夹里面增加了info.log文件

查看info.log

INFO-2019-12-10 14:36:22,124-_internal-122- * Restarting with stat
WARNING-2019-12-10 14:36:22,590-_internal-122- * Debugger is active!
INFO-2019-12-10 14:36:22,594-_internal-122- * Debugger PIN: 259-203-506
INFO-2019-12-10 14:36:22,602-_internal-122- * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
ERROR-2019-12-10 14:36:25,475-user_api-23-division by zero
INFO-2019-12-10 14:36:25,480-_internal-122-127.0.0.1 - - [10/Dec/2019 14:36:25] "GET /index HTTP/1.1" 500 -
INFO-2019-12-10 14:36:25,497-_internal-122-127.0.0.1 - - [10/Dec/2019 14:36:25] "GET /index?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
INFO-2019-12-10 14:36:25,498-_internal-122-127.0.0.1 - - [10/Dec/2019 14:36:25] "GET /index?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
INFO-2019-12-10 14:36:25,498-_internal-122-127.0.0.1 - - [10/Dec/2019 14:36:25] "GET /index?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
INFO-2019-12-10 14:36:25,537-_internal-122-127.0.0.1 - - [10/Dec/2019 14:36:25] "GET /index?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
INFO-2019-12-10 14:36:25,581-_internal-122-127.0.0.1 - - [10/Dec/2019 14:36:25] "GET /index?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
INFO-2019-12-10 14:36:25,626-_internal-122-127.0.0.1 - - [10/Dec/2019 14:36:25] "GET /index?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

将LogClass.py中 self.logger.setLevel(logging.DEBUG) 改为 self.logger.setLevel(logging.ERROR),然后运行程序,查看info.log

INFO-2019-12-10 14:40:12,643-_internal-122- * Detected change in 'F:\\info\\log\\LogClass.py', reloading
INFO-2019-12-10 14:40:12,673-_internal-122- * Restarting with stat
WARNING-2019-12-10 14:40:13,135-_internal-122- * Debugger is active!
INFO-2019-12-10 14:40:13,139-_internal-122- * Debugger PIN: 259-203-506
INFO-2019-12-10 14:40:13,147-_internal-122- * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
ERROR-2019-12-10 14:40:17,367-user_api-23-division by zero
INFO-2019-12-10 14:40:17,372-_internal-122-127.0.0.1 - - [10/Dec/2019 14:40:17] "GET /index HTTP/1.1" 500 -
INFO-2019-12-10 14:40:17,388-_internal-122-127.0.0.1 - - [10/Dec/2019 14:40:17] "GET /index?__debugger__=yes&cmd=resource&f=style.css HTTP/1.1" 200 -
INFO-2019-12-10 14:40:17,389-_internal-122-127.0.0.1 - - [10/Dec/2019 14:40:17] "GET /index?__debugger__=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -
INFO-2019-12-10 14:40:17,389-_internal-122-127.0.0.1 - - [10/Dec/2019 14:40:17] "GET /index?__debugger__=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -
INFO-2019-12-10 14:40:17,427-_internal-122-127.0.0.1 - - [10/Dec/2019 14:40:17] "GET /index?__debugger__=yes&cmd=resource&f=ubuntu.ttf HTTP/1.1" 200 -
INFO-2019-12-10 14:40:17,466-_internal-122-127.0.0.1 - - [10/Dec/2019 14:40:17] "GET /index?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -
INFO-2019-12-10 14:40:17,511-_internal-122-127.0.0.1 - - [10/Dec/2019 14:40:17] "GET /index?__debugger__=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

# 具体原因 TODO

flask中自定义日志类的更多相关文章

  1. Python3自定义日志类教程

    一.说明 Python3的logging功能是比较丰富的支持不同层次的日志输出,但或是我们想在日志前输出时间.或是我们想要将日志输入到文件,我们还是想要自定义日志类. 之前自己也尝试写过但感觉文档太乱 ...

  2. Flask之自定义模型类

    4.3自定义模型类 定义模型 模型表示程序使用的数据实体,在Flask-SQLAlchemy中,模型一般是Python类,继承自db.Model,db是SQLAlchemy类的实例,代表程序使用的数据 ...

  3. 关于MapReduce中自定义分区类(四)

    MapTask类 在MapTask类中找到run函数 if(useNewApi){       runNewMapper(job, splitMetaInfo, umbilical, reporter ...

  4. 关于MapReduce中自定义分组类(三)

    Job类  /**    * Define the comparator that controls which keys are grouped together    * for a single ...

  5. python3.4中自定义数组类(即重写数组类)

    '''自定义数组类,实现数组中数字之间的四则运算,内积运算,大小比较,数组元素访问修改及成员测试等功能''' class MyArray: '''保证输入值为数字元素(整型,浮点型,复数)''' de ...

  6. shell脚本中自定义日志记录到文件

    自定义日志函数和前期变量 # adirname - return absolute dirname of given file adirname() { odir=`pwd`; cd `dirname ...

  7. 如何自定义Flask中的响应类

    http://codingpy.com/article/customizing-the-flask-response-class/

  8. Python3自定义日志类 mylog

    #encoding=utf-8 import os, sysimport datetimeimport time class Mylog(object): # 根文件夹    root_dir = s ...

  9. 关于MapReduce中自定义Combine类(一)

    MRJobConfig      public static fina COMBINE_CLASS_ATTR      属性COMBINE_CLASS_ATTR = "mapreduce.j ...

随机推荐

  1. Putty - 免用户名密码登录

    打开 Putty 时携带 -pw your_password your_username@your_host 参数即可.

  2. 【linux】的文件按时间排序

    > ls -alt # 按修改时间排序 > ls --sort=time -la # 等价于> ls -alt > ls -alc # 按创建时间排序 > ls -alu ...

  3. Spring mvc注解说明

    编号 注解 说明 位置 备注 1 @Controller 将类变成Spring Bean 类 现阶段 @Controller . @Service 以及 @Repository 和 @Componen ...

  4. 在word中的表格指定位置插入一行

    //创建一个Document类对象,并加载Word文档 Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administ ...

  5. 2018.03.27 pandas duplicated 和 replace 使用

    #.duplicated / .replace import numpy as np import pandas as pd s = pd.Series([1,1,1,1,1,2,3,3,3,4,4, ...

  6. golang 标准库 sync.Map 中 nil 和 expunge 区别

    本文不是 sync.Map 源码详细解读,而是聚焦 entry 的不同状态,特别是 nil 状态和 expunge 状态的区分. entry 是 sync.Map 存放值的结构体,其值有三种,分别为 ...

  7. Linux中MySQL5.7设置utf8编码格式步骤

    关于编码问题,真的是弄得我很郁闷,网上找的帖子这方面也很多但都无济于事,晚上终于找到一篇有效的,特此贴上. 转自Ubuntu中MySQL5.7设置utf8编码格式步骤 1.首先打开终端 2.输入mys ...

  8. 解决Pip install Pillow 失败问题

    当我在使用Django一个上传图片功能的时候, Django 提示我安装 Pillow这个图片处理的库, 当我尝试安装的时候. 总是提示安装失败 报如下错误. v = self._sslobj.rea ...

  9. Cocos2d-X网络编程(1) 网络基本概念

    网络模型 OSI层模型.TCP/IP的层模型如下所示. TCP/IP各层对应的协议如下所示. 通过初步的了解,我知道: IP协议:对应于网络层,是网络层的协议, TCP协议:对应于传输层,是传输层的协 ...

  10. Redis的 SLAVEOF 命令

    SLAVEOF host port SLAVEOF 命令用于在 Redis 运行时动态地修改复制(replication)功能的行为. 通过执行 SLAVEOF host port 命令,可以将当前服 ...