flask 框架日誌

三只松鼠發表於2024-07-31

  除了自定義配置的log日誌外,flask框架的有自己的日誌處理機制,使用它的好處就是出現異常,即使沒有捕獲也能列印到日誌裡,方便定位問題。

import sys
from logging.handlers import TimedRotatingFileHandler
from logging import StreamHandler
from logging import Formatter

app = Flask(__name__)
def LoggerLoad(app):
    LogPath = './log/test/'
    app.logger = logging.getLogger("root")
    #設定收集的日誌等級
    app.logger.setLevel(logging.INFO)
    # 配置日誌格式
    formatter = Formatter(" %(asctime)s threadId-%(thread)d %(levelname)s %(module)s %(funcName)s %(message)s")
    # 定義控制檯輸出
    handler = StreamHandler(sys.stderr)
    handler.setFormatter(formatter)
    os.makedirs(LogPath, exist_ok=True)
    # 配置TimedRotatingFileHandler保留策略
    time_handler = TimedRotatingFileHandler(f'{LogPath}/main.log',
                                               when="midnight",
                                               interval=1,
                                               backupCount=20,
                                               encoding='utf-8')
    time_handler.setFormatter(formatter)
    # 可以單獨給每個handler設定日誌等級,上面已統一設定過
    # time_handler.setLevel(logging.INFO)
    # add輸出控制檯handler
    app.logger.addHandler(handler)
    # add自定義檔案輸出handler
    app.logger.addHandler(time_handler)

LoggerLoad(app)
app.logger.info('This is info')
app.logger.warning('This is warning')
app.logger.error('This is error')

@app.route('/')
def index():
    app.logger('')
    # 製造一個錯誤
    return None

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

輸出:

2024-02-02 15:49:55,411 threadId-5332 INFO app <module> This is info
 2024-02-02 15:49:55,412 threadId-5332 WARNING app <module> This is warning
 2024-02-02 15:49:55,412 threadId-5332 ERROR app <module> This is error
 2024-02-02 15:49:55,427 threadId-5332 INFO _internal _log [31m[1mWARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.[0m
 * Running on http://127.0.0.1:5000
 2024-02-02 15:49:55,427 threadId-5332 INFO _internal _log [33mPress CTRL+C to quit[0m
 2024-02-02 15:50:11,428 threadId-9920 ERROR app log_exception Exception on / [GET]
Traceback (most recent call last):
  File "C:\Users\shenhao\AppData\Local\pypoetry\Cache\virtualenvs\flaskproject1-_AJUdV2B-py3.10\lib\site-packages\flask\app.py", line 1455, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\shenhao\AppData\Local\pypoetry\Cache\virtualenvs\flaskproject1-_AJUdV2B-py3.10\lib\site-packages\flask\app.py", line 869, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\shenhao\AppData\Local\pypoetry\Cache\virtualenvs\flaskproject1-_AJUdV2B-py3.10\lib\site-packages\flask\app.py", line 867, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\shenhao\AppData\Local\pypoetry\Cache\virtualenvs\flaskproject1-_AJUdV2B-py3.10\lib\site-packages\flask\app.py", line 852, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "C:\Users\shenhao\PycharmProjects\flaskProject1\app.py", line 75, in index
    app.logger('')
TypeError: 'RootLogger' object is not callable
 2024-02-02 15:50:11,432 threadId-9920 INFO _internal _log 127.0.0.1 - - [02/Feb/2024 15:50:11] "[35m[1mGET / HTTP/1.1[0m" 500 -

如果是在檢視函式,可直接透過 current_app.logger.info() 方法呼叫。非檢視函式沒有上下文關係,需要先 with app.app_context() ,再呼叫 current_app.logger.info() 。

相關文章