falsk本身有一个logging的模块,并且有一个create_logger
函数,并且有一个default_handler
的默认handler。
from flask import has_request_context, request
from flask.logging import default_handler
class RequestFormatter(logging.Formatter):
def format(self, record):
if has_request_context():
record.url = request.url
record.remote_addr = request.remote_addr
else:
record.url = None
record.remote_addr = None
return super().format(record)
formatter = RequestFormatter(
'[%(asctime)s] %(remote_addr)s requested %(url)s\n'
'%(levelname)s in %(module)s: %(message)s'
)
default_handler.setFormatter(formatter)
import logging
import os
import datetime
from flask import Flask
from flask.logging import default_handler
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from dev_setting import Config
class LogConfig:
from logging.handlers import TimedRotatingFileHandler
log_path = os.path.join(os.path.dirname(__file__), 'log')
my_handler = logging.handlers.TimedRotatingFileHandler(
os.path.join(log_path, f'{str(datetime.date.today())}_all.log'), when='midnight'
, interval=1, backupCount=7,
atTime=datetime.time(0, 0, 0, 0))
my_handler.setFormatter(logging.Formatter('%(asctime)s\t%(levelname)s\t%(funcName)s\t%(message)s'))
# 配置一个记录错误信息的handler,精确到了文件的行
f_handler = logging.FileHandler(os.path.join(log_path, 'error.log'))
f_handler.setLevel(logging.ERROR)
f_handler.setFormatter \
(logging.Formatter('%(asctime)s\t%(levelname)s\t%(filename)s\t[: %(lineno)d]\t%(funcName)s\t%(message)s'))
def create_flask_app(config):
app = Flask(__name__)
app.config.from_object(config)
return app
app = create_flask_app(Config)
app.logger.setLevel(logging.DEBUG)
# 默认的Handler是flask.logging.StreamHandler(wsgi_errors_stream),没有落到文件中,给他干掉
app.logger.removeHandler(default_handler)
my_handler = LogConfig.my_handler
f_handler = LogConfig.f_handler
# 把上面的自己的两个handler装到logger上
app.logger.addHandler(my_handler)
app.logger.addHandler(f_handler)
CORS(app)
db = SQLAlchemy(app)
后面的自己的程序的日志,都用这个来搞
https://blog.csdn.net/weixin_30553837/article/details/102140509