优选主流主机商
任何主机均需规范使用

Flask使用日志

目录结构
1334255-20200930152827286-1348911335

编辑 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

未经允许不得转载:搬瓦工中文网 » Flask使用日志