推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
superbai
V2EX  ›  Python

Python 如何进行全局的请求日志记录?

  •  
  •   superbai · Jun 6, 2019 · 3155 views
    This topic created in 2557 days ago, the information mentioned may be changed or developed.

    现在有多个接口,怎么能够给这些接口添加统一的请求日志记录功能,并且自动在有新增的接口时,也无感增加日志记录?

    在网上搜索到的方法都是写一个装饰器,然后在接口函数上使用这个装饰器。这种方法没有满足无感的需求,如果写代码的时候忘记加装饰器的话,就没有日志记录了

    Supplement 1  ·  Jun 6, 2019
    补充下,基于框架或者继承的实现我都清楚,不过这两种方法都和特定的代码 /框架紧耦合在一起了,除了这些还有其它方法么?
    15 replies    2019-06-09 22:26:04 +08:00
    so1n
        1
    so1n  
       Jun 6, 2019
    中间件
    ifoolish
        2
    ifoolish  
       Jun 6, 2019
    全部接口继承一个基类
    lauix
        3
    lauix  
       Jun 6, 2019
    什么框架,flask 可以设置生命周期。其他框架也有的,自己查查文档。也可以自己写个 装饰器。
    superbai
        4
    superbai  
    OP
       Jun 6, 2019
    @ifoolish 嗯嗯,除了这种方式,还有其它的方法么?
    @lauix 不用框架有什么方法么?
    @so1n 是指 django 的中间件么?不用框架有什么方法么?
    binux
        5
    binux  
       Jun 6, 2019
    不用框架就只能 monkey patch 了
    ipwx
        6
    ipwx  
       Jun 6, 2019
    @superbai 做一个 metaclass,然后你就可以自动给所有成员函数自动加装饰器了。
    polebug
        7
    polebug  
       Jun 6, 2019
    赞同楼上 写一个 metaclass 给所有成员函数加上这个装饰器
    不过我不觉得直接给接口函数加装饰器有什么问题
    lihongjie0209
        8
    lihongjie0209  
       Jun 6, 2019
    没有拦截器?
    flyingghost
        9
    flyingghost  
       Jun 6, 2019
    实在想无感,直接在 nginx 反代层做好了。
    思维不要限制在 flask 之内嘛。
    superbai
        10
    superbai  
    OP
       Jun 6, 2019
    @binux
    @ipwx
    @polebug
    感谢,我瞅瞅;接口加装饰器当然没问题,不过我觉得有点烦...

    @lihongjie0209 Java 的那个拦截器么?我也想问哈哈哈,看起来是没有的

    @flyingghost 感谢,虽然一般没有这么做的,但也是个思路~
    xchange
        11
    xchange  
       Jun 6, 2019
    所有 logger 都输出到 stderr,然后用 supervisor 把输出重定向到一个文件里
    troywinter
        12
    troywinter  
       Jun 6, 2019
    如果是接口的请求最好直接在网关层做,微服务里应该很好做,我不喜欢在服务自己的框架里做很多事情,keep it simple
    chengxiao
        13
    chengxiao  
       Jun 6, 2019 via iPhone
    uwsgi 的日志不是记录的都有么?直接日子分析下不就好了?
    sazima
        14
    sazima  
       Jun 6, 2019
    @app.before_request
    linvaux
        15
    linvaux  
       Jun 9, 2019
    emm.....我之前就是写了个装饰器,没想到什么好办法
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   908 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 65ms · UTC 19:47 · PVG 03:47 · LAX 12:47 · JFK 15:47
    ♥ Do have faith in what you're doing.