python-3.x 如何使用fastapi日志记录捕获X-Forwarded-For?

0dxa2lsx  于 2023-01-27  发布在  Python
关注(0)|答案(2)|浏览(285)

我在下面的函数中运行带有guvicorn的FastApi:

if __name__ == "__main__":

    uvicorn.run(
        app="app.main:app",
        host="HOSTIP",
        port=8000,
        reload=True,
        # log_config=None,
        log_config=log_config,
        log_level="info"
    )

下面是我的log_config:

log_config = {
    "version": 1,
    "disable_existing_loggers": True,
    "formatters": {
        "default": {
            "()": "uvicorn.logging.DefaultFormatter",
            "fmt": "%(asctime)s::%(levelname)s::%(name)s::%(filename)s::%(funcName)s - %(message)s",
            "use_colors": None,
        },
        "access": {
            "()": "uvicorn.logging.AccessFormatter",
            "fmt": '%(asctime)s::%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s',
        },
    },
    "handlers":
    {
        "default":
        {
            "formatter": "default",
            # "class": 'logging.NullHandler',
            "class": 'logging.FileHandler',
            "filename": CONFIG[SECTION]["default"]
        },
        "error":
        {
            "formatter": "default",
            # "class": 'logging.NullHandler',
            "class": 'logging.FileHandler',
            "filename": CONFIG[SECTION]["error"]
        },
        "access":
        {
            "formatter": "access",
            # "class": 'logging.NullHandler',
            "class": 'logging.FileHandler',
            "filename": CONFIG[SECTION]["access"]
        },
    },
    "loggers":
    {
        "uvicorn": {"handlers": ["default"], "level": "INFO", "propagate": False},
        "uvicorn.error": {"handlers": ["error"], "level": "ERROR", "propagate": False},
        "uvicorn.access": {"handlers": ["access"], "level": "INFO", "propagate": False},
    }
}

我在2台服务器上有2个fastapi示例,运行在haproxy后面。我可以在haproxy中放入此选项,将客户端IP转发到我的API:

option forwardfor

我能够在其中一个API服务器上使用TCPDUMP确认我实际上正在接收一些x-fwd头文件:

[user@server ~]# tcpdump -i INTERFACE host SERVERIP -AAA | grep -i IP OF MY LAPTOP
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on INTERFACE, link-type EN10MB (Ethernet), capture size 262144 bytes
*X-Forwarded-For: IP OF MY LAPTOP*

但是在我的日志中,我只能看到请求命中的vip的IP,即使HAproxy正在转发客户端的IP,我也无法记录它。
是否有可用于log_config访问部分的自定义变量?
谢谢。

nhn9ugyo

nhn9ugyo1#

您可以使用proxy_headers=True填充远程地址信息:
来自文档:

--proxy-headers / --no-proxy-headers
                                  Enable/Disable X-Forwarded-Proto,
                                  X-Forwarded-For, X-Forwarded-Port to
                                  populate remote address info.

https://www.uvicorn.org/deployment/#running-from-the-command-line

bkhjykvo

bkhjykvo2#

好吧,我知道了。
我不得不在www.example.com中添加两项内容start.py:

if __name__ == "__main__":

    uvicorn.run(
        app="app.main:app",
        host="HOSTIP",
        port=8000,
        reload=True,
        proxy_headers=True, # THIS LINE
        forwarded_allow_ips='*', # THIS LINE
        log_config=log_config,
        log_level="info"
    )

相关问题