V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
zxCoder
V2EX  ›  问与答

flask log 输出到文件的问题

  •  
  •   zxCoder · 2021-06-12 13:54:07 +08:00 · 651 次点击
    这是一个创建于 1042 天前的主题,其中的信息可能已经有所发展或是发生改变。
    from flask import Flask
    import logging
    
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        app.logger.error("hello")
        return 'Hello World!'
    
    if __name__ == '__main__':
        handler = logging.FileHandler('flask.log', encoding='UTF-8')
        handler.setLevel(logging.DEBUG)
        logging_format = logging.Formatter(
            '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
        handler.setFormatter(logging_format)
        app.logger.addHandler(handler)
        app.run()
        app.logger.error("????")
    

    启动后访问 127.0.0.1:5000/

    app.logger.error("hello")这个日志打印了,但是没有按设定的格式,而且也找不到 flask.log 文件

    2 条回复    2021-06-12 17:55:36 +08:00
    zeyexe
        1
    zeyexe  
       2021-06-12 15:01:37 +08:00
    When you want to configure logging for your project, you should do it as soon as possible when the program starts.

    https://flask.palletsprojects.com/en/2.0.x/logging/#basic-configuration

    请尝试在 app = Flask(__name__) 之前配置日志。
    johnsona
        2
    johnsona  
       2021-06-12 17:55:36 +08:00 via iPhone
    flask 有个 logger 属性 实际上是被 property 装饰的方法 创建对象的时候执行了 文档的建议是 你晚了就 remove 好像是的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1192 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:51 · PVG 07:51 · LAX 16:51 · JFK 19:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.