Flask 使用日志


目錄結構

編輯 app.py

from flask import Flask
import logging
from ops import test

# 在創建 app 之前將 log 級別重置為debug,讓其線上 info 日志級別
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)

@app.route('/')
def hello_world():
    app.logger.info('info log')          # 測試 info 日志
    app.logger.warning('warning log')    # 測試 sarning 日志
    test.test()                          # 調用其他頁面函數,輸出日志

    a = [1, 2, 3]
    try:
        print(a[3])
    except Exception as e:
        app.logger.exception(e)         # 測試 error 日志

    return 'Hello World!'


if __name__ == '__main__':
    handler = logging.FileHandler('flask.log', encoding='UTF-8')   # 設置日志字符集和存儲路徑名字
    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()

新建 Python Package ops, 新建 test.py 文件,內容如下

from flask import current_app
import logging


def test():
    current_app.logger.warning('A warning occurred (%d apples)', 42)

測試查看 flask.log 文件

2020-09-30 15:15:04,932 - INFO - app.py - hello_world - 11 - info log
2020-09-30 15:15:04,933 - WARNING - app.py - hello_world - 12 - warning log
2020-09-30 15:15:04,933 - WARNING - test.py - test - 9 - A warning occurred (42 apples)
2020-09-30 15:15:04,933 - ERROR - app.py - hello_world - 19 - list index out of range
Traceback (most recent call last):
  File "app.py", line 17, in hello_world
    print(a[3])
IndexError: list index out of range


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM