falsk本身有一个logging的模块,并且有一个create_logger函数,并且有一个default_handler的默认handler。

    1. from flask import has_request_context, request
    2. from flask.logging import default_handler
    3. class RequestFormatter(logging.Formatter):
    4. def format(self, record):
    5. if has_request_context():
    6. record.url = request.url
    7. record.remote_addr = request.remote_addr
    8. else:
    9. record.url = None
    10. record.remote_addr = None
    11. return super().format(record)
    12. formatter = RequestFormatter(
    13. '[%(asctime)s] %(remote_addr)s requested %(url)s\n'
    14. '%(levelname)s in %(module)s: %(message)s'
    15. )
    16. default_handler.setFormatter(formatter)
    1. import logging
    2. import os
    3. import datetime
    4. from flask import Flask
    5. from flask.logging import default_handler
    6. from flask_sqlalchemy import SQLAlchemy
    7. from flask_cors import CORS
    8. from dev_setting import Config
    9. class LogConfig:
    10. from logging.handlers import TimedRotatingFileHandler
    11. log_path = os.path.join(os.path.dirname(__file__), 'log')
    12. my_handler = logging.handlers.TimedRotatingFileHandler(
    13. os.path.join(log_path, f'{str(datetime.date.today())}_all.log'), when='midnight'
    14. , interval=1, backupCount=7,
    15. atTime=datetime.time(0, 0, 0, 0))
    16. my_handler.setFormatter(logging.Formatter('%(asctime)s\t%(levelname)s\t%(funcName)s\t%(message)s'))
    17. # 配置一个记录错误信息的handler,精确到了文件的行
    18. f_handler = logging.FileHandler(os.path.join(log_path, 'error.log'))
    19. f_handler.setLevel(logging.ERROR)
    20. f_handler.setFormatter \
    21. (logging.Formatter('%(asctime)s\t%(levelname)s\t%(filename)s\t[: %(lineno)d]\t%(funcName)s\t%(message)s'))
    22. def create_flask_app(config):
    23. app = Flask(__name__)
    24. app.config.from_object(config)
    25. return app
    26. app = create_flask_app(Config)
    27. app.logger.setLevel(logging.DEBUG)
    28. # 默认的Handler是flask.logging.StreamHandler(wsgi_errors_stream),没有落到文件中,给他干掉
    29. app.logger.removeHandler(default_handler)
    30. my_handler = LogConfig.my_handler
    31. f_handler = LogConfig.f_handler
    32. # 把上面的自己的两个handler装到logger上
    33. app.logger.addHandler(my_handler)
    34. app.logger.addHandler(f_handler)
    35. CORS(app)
    36. db = SQLAlchemy(app)

    后面的自己的程序的日志,都用这个来搞
    https://blog.csdn.net/weixin_30553837/article/details/102140509