bobbui/json-logging-python

Cant access correlation id , help

fmieres opened this issue · 2 comments

I'm not getting the correlation_id outside of the request handled by the library. I dont know if i'm understanding something wrong:

main.py

app = get_application()

# json_logging.CREATE_CORRELATION_ID_IF_NOT_EXISTS = True
json_logging.init_fastapi(enable_json=True)
json_logging.init_request_instrument(app)

# init the logger as usual
logger = logging.getLogger("platform")
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler(sys.stdout))

some route.py

logger = logging.getLogger("platform")

@router.get('/{user_id}')
def get(user_id):
    # correlation_id = json_logging.get_correlation_id()
    logger.info('getting one user', extra={'props': {'user_id': user_id}})
    # logger.info('getting one user', extra={'props': {'user_id': user_id, 'correlation_id': correlation_id}})
    return service.get(user_id)
  ...

and these are my logs :

{"written_at": "2021-08-11T21:45:54.656Z", "written_ts": 1628718354656737000, "msg": "getting one user", "type": "log", "logger": "platform", "thread": "asyncio_0", "level": "INFO", "module": "users", "line_no": 25, "user_id": "0x3801ec574", "correlation_id": "-"}
{"written_at": "2021-08-11T21:45:55.382Z", "written_ts": 1628718355382893000, "type": "request", "correlation_id": "819f68c8-faed-11eb-9d1d-0242ac110003", "remote_user": "-", "request": "/v1/users/0x3801ec574", "referer": "-", "x_forwarded_for": "-", "protocol": "HTTP/1.1", "method": "GET", "remote_ip": "172.17.0.1", "request_size_b": -1, "remote_host": "172.17.0.1", "remote_port": 57790, "request_received_at": "2021-08-11T21:45:54.655Z", "response_time_ms": 727, "response_status": 200, "response_size_b": "120", "response_content_type": "application/json", "response_sent_at": "2021-08-11T21:45:55.382Z"}

And another question, if I wanted to go further and use the correlation ID inside service.get(user_id), Woudl i be able to get it from there?
I appretiate your help, thank you.

I have re run the exact same lines i put above and now it works, even without the get_correlation_id call . Thank you very much for your time :)