除了自定义配置的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() 。
标签:02,15,框架,flask,app,handler,threadId,日志,logger From: https://www.cnblogs.com/shenh/p/18003361