python – 为Flask的app.logger提供额外信息
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 为Flask的app.logger提供额外信息,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含4012字,纯文字阅读大概需要6分钟。
内容图文
![python – 为Flask的app.logger提供额外信息](/upload/InfoBanner/zyjiaocheng/705/5eeda88a986949cba2bfa271edcae2a6.jpg)
Flask 0.10的default debug log format是
debug_log_format =
'-------------------------------------------------------------------------\n%
%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s
\n-------------------------------------------------------------------------'
如何将其更改为:
'-------------------------------------------------------------------------\n%
work_id %(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s
\n-------------------------------------------------------------------------'
其中work_id是每个请求的随机生成的UUID.
如果记录器是由我自己创建的,我可以使用logging.LoggerAdapter并提供额外的信息作为dict {‘work_id’:some_uuid},然后我可以使用record.work_id在日志记录中访问它.
但是app.logger是由create_logger() in Flask’slogging.py创建的,我是否必须修改Flask源来实现我想要的?
我还想过用我自己的记录器覆盖app.logger,比如app.logger = my_logger,它似乎不对.
解决方法:
通过Flask.debug_log_format
这样做:
app.debug = True
app.debug_log_format = """-------------------------------------------------------------------------
%(worker_id)s (levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s
-------------------------------------------------------------------------"""
app.logger.log("test", extra={"worker_id": request.your_uuid_property)
例:
import logging
from flask import Flask, request
app = Flask(__name__)
# please replace "request.uuid" with your actual property
log = lambda msg: app.logger.info(msg, extra={'worker_id': "request.uuid" })
@app.route("/")
def hello():
log("hello world")
return "Hello World!"
if __name__ == "__main__":
app.debug_log_format = """-------------------------------------------------------------------------
%(worker_id)s in %(module)s [%(pathname)s:%(lineno)d]:
%(message)s
-------------------------------------------------------------------------"""
app.debug = True
log("hello world")
app.run()
通过标准记录模块的Handler和Formatter
Flask以任何方式使用日志记录,因此您可以使用logging.Handler和logging.Formatter来实现Flask外部.可以在here找到一个通用示例.日志配置的高级主题可以在the doc和cookbook中找到
针对您的问题的定制示例是:
import logging
from flask import Flask
app = Flask(__name__)
class CustomFormatter(logging.Formatter):
def format(self, record):
record.worker_id = "request.uuid" # replace this with your variable
return super(CustomFormatter,self).format(record)
@app.route("/")
def hello():
app.logger.info("hello world")
return "Hello World!"
if __name__ == "__main__":
custom_format = """-------------------------------------------------------------------------
%(worker_id)s in %(module)s [%(pathname)s:%(lineno)d]:
%(message)s
-------------------------------------------------------------------------"""
app.debug = True
ch = logging.StreamHandler()
ch.setFormatter(CustomFormatter(fmt=custom_format))
app.logger.addHandler(ch)
app.logger.debug("hello world")
app.run()
通过覆盖logging.Logger类
通过覆盖默认记录器类可以实现相同的目标.结合flask request context stack,您将能够在日志中获得自己的字段:
import logging
from flask import Flask
app = Flask(__name__)
from flask import _request_ctx_stack
CUSTOM_FORMAT = """-------------------------------------------------------------------------
%(worker_id)s in %(module)s [%(pathname)s:%(lineno)d]:
%(message)s
-------------------------------------------------------------------------"""
class MyLogger(logging.Logger):
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
ctx = _request_ctx_stack.top
custom_extra = dict(
worker_id="request.uuid"
)
if ctx is not None:
url = ctx.request.url # please replace this with your own field
custom_extra["worker_id"] = url
if extra is not None:
extra.update(custom_extra)
else:
extra = custom_extra
return super(MyLogger,self).makeRecord(name, level, fn, lno, msg, args, exc_info, func=func, extra=extra)
logging.setLoggerClass(MyLogger)
@app.route("/")
def hello():
app.logger.info("hello world")
return "Hello World!"
if __name__ == "__main__":
app.debug_log_format = CUSTOM_FORMAT
app.debug = True
app.logger.debug("hello world")
app.run()
内容总结
以上是互联网集市为您收集整理的python – 为Flask的app.logger提供额外信息全部内容,希望文章能够帮你解决python – 为Flask的app.logger提供额外信息所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。