简体   繁体   English

How to log UUID of api request payload on every log messages with python?

[英]How to log UUID of api request payload on every log messages with python?

I'm working on a micro services where i need to log the uuid recieved on a payload to the cloud based logger. But i've one module calling another module, so for every submodule functions to log the messages with uuid, i need to pass uuid to every function i call, but that's a bad idea, is there a better way of doing this ??

Illustration of what i'm trying to achieve:

def call_bar(uuid):
    app.logger.info("Something coming with uuid: {uuid}")   

def call_foo(uuid):
    # 
    app.logger.info("Something coming with uuid: {uuid}")    
    call_bar(uuid)

def flask_view():
    # i get a uuid here
    app.logger.info("Something coming with uuid: {uuid}")
    call_foo(uuid)

The issue in the above code is i need to explicitly pass the value to every function i call.

The logger component of Lambda Power tools does this for us on AWS. Lambda Power tools的记录器组件在 AWS 上为我们完成了这项工作。 the code setup is pretty minimal:代码设置非常少:

 from aws_lambda_powertools import Logger logger = Logger() def flask_view(): request_uuid = i_get_a_uuid_here() logger.append_keys(uuid=request_uuid) call_foo() def call_foo() logger.info("foo happened")

This would get you a json log line than line that as well as bunch of other fields has the following keys.这将为您提供 json 日志行,而不是该行以及其他字段具有以下键的行。

 { "message": "foo happened", "uuid": "<request_uuid>" }

if your not on aws lambda, I'd take a look at structlog its log.bind(uuid=uuid) works similarly allowing you to add keys that get used for subsequent log entries.如果您不在 aws lambda 上,我会看一下structlog ,它的log.bind(uuid=uuid)工作方式类似,允许您添加用于后续日志条目的密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM