question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to configure asgi-correlation with loguru ?

See original GitHub issue

Hello there !

Loguru seems to get more popularity as time goes by, I’ve tried to setup a very minimal example to get your library working with it, but it seems it can’t find the correlation id.

I’ve tried several things, and right now i’m doing this :

import logging
import sys

import uvicorn
from asgi_correlation_id import CorrelationIdMiddleware
from fastapi import FastAPI
from loguru import logger

app = FastAPI()

app.add_middleware(CorrelationIdMiddleware)

# remove default handler
logger.remove()

fmt = "[{time}] [application_name] [{extra[correlation_id]}] [{level}] - {name}:{function}:{line} - {message}"
logger.add(sys.stderr, format=fmt, level=logging.DEBUG)

@app.get('/')
def index():
    logger.info(f"Request with id ")
    return 'OK'



if __name__ == '__main__':
    uvicorn.run(app)


And I get a :

Record was: {'elapsed': datetime.timedelta(seconds=1, microseconds=1880), 'exception': None, 'extra': {}, 'file': (name='another_main.py', path='C:\\Users\\User\\PycharmProjects\\x\\y\\another_main.py'), 'function': 'index', 'level': (name='INFO', no=20, icon='ℹ️'), 'line': 21, 'message': 'Request with id ', 'module': 'another_main', 'name': '__main__', 'process': (id=3412, name='MainProcess'), 'thread': (id=9164, name='asyncio_0'), 'time': datetime(2021, 11, 17, 15, 7, 54, 443182, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Paris, Madrid'))}
Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\x\venv\lib\site-packages\loguru\_handler.py", line 155, in emit
    formatted = precomputed_format.format_map(formatter_record)
KeyError: 'correlation_id'
--- End of logging error ---

Got any idea ? Thanks !

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
sorasfulcommented, Nov 17, 2021

Wow, this works great! I wouldn’t have thought about this.

I just post this full example so people will know.

import logging
import sys

import uvicorn
from asgi_correlation_id import CorrelationIdMiddleware
from asgi_correlation_id.context import correlation_id
from fastapi import FastAPI
from loguru import logger

app = FastAPI()
app.add_middleware(CorrelationIdMiddleware)

# remove default handler
logger.remove()


def correlation_id_filter(record):
    record['correlation_id'] = correlation_id.get()
    return record['correlation_id']


fmt = "[{time}] [application_name] [{correlation_id}] [{level}] - {name}:{function}:{line} - {message}"
logger.add(sys.stderr, format=fmt, level=logging.DEBUG, filter=correlation_id_filter)


@app.get('/')
def index():
    logger.info(f"Request with correlation id ")
    return 'OK'


if __name__ == '__main__':
    uvicorn.run(app)

Thank you for your precious help and your time, I’ll close this now 😃

1reaction
ponpononcommented, Jan 17, 2022

Here’s my example

import logging
import sys

import uvicorn
from asgi_correlation_id import CorrelationIdMiddleware
# from asgi_correlation_id import correlation_id_filter
from asgi_correlation_id.context import correlation_id
from fastapi import FastAPI
from loguru import logger

app = FastAPI()

app.add_middleware(CorrelationIdMiddleware)

logger.remove()


def correlation_id_filter(record):
    record['correlation_id'] = correlation_id.get()
    return record['correlation_id']


fmt = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <red> {correlation_id} </red> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"


logger.add(sys.stderr, format=fmt, level=logging.DEBUG,
           filter=correlation_id_filter)


@app.get('/')
def index():
    logger.info(f"Request with id ")
    return 'OK'

输出如下:

2022-01-17 16:14:09.973 | INFO     |  4a4395d4ff4648e6bdcaa09de74a7139  | main:index:32 - Request with id 
INFO:     127.0.0.1:55324 - "GET / HTTP/1.1" 200 OK
2022-01-17 16:14:10.823 | INFO     |  23acbd0ed8724888a516c3cfb6b5fef7  | main:index:32 - Request with id 
INFO:     127.0.0.1:55326 - "GET / HTTP/1.1" 200 OK
2022-01-17 16:14:11.420 | INFO     |  9456154f756a4894bc470148e430acb2  | main:index:32 - Request with id 
INFO:     127.0.0.1:55328 - "GET / HTTP/1.1" 200 OK
2022-01-17 16:14:11.995 | INFO     |  8e89a4b6cd3747c4a2a479f26f9e6051  | main:index:32 - Request with id 
INFO:     127.0.0.1:55330 - "GET / HTTP/1.1" 200 OK
2022-01-17 16:14:12.657 | INFO     |  e4050d68717d4709983fa733683bef99  | main:index:32 - Request with id 
INFO:     127.0.0.1:55332 - "GET / HTTP/1.1" 200 OK
2022-01-17 16:14:13.202 | INFO     |  5b34d75b2fa54a0ebf95b84af949ceda  | main:index:32 - Request with id 
INFO:     127.0.0.1:55334 - "GET / HTTP/1.1" 200 OK

图片

Read more comments on GitHub >

github_iconTop Results From Across the Web

snok/asgi-correlation-id: Request ID propagation for ASGI apps
To set up the package, you need to add the middleware and configure logging. Adding the middleware. The middleware can be added like...
Read more >
A Complete Guide to Logging in Python with Loguru
Analyze, correlate and filter logs with SQL. Create actionable dashboards. Share and comment with built ...
Read more >
How To Override Uvicorn Logger in FastAPI using Loguru
Uvicorn is a lightning-fast ASGI server implementation, using uvloop and httptools. Until recently Python has ... Easy to use and customize with loguru....
Read more >
asgi-correlation-id 0.1.1 - PyPI
Middleware that propagates HTTP header correlation IDs to project logs. ... pip install asgi-correlation-id==0.1.1. Copy PIP instructions.
Read more >
Switching from standard logging to loguru
The main difference is that standard logging requires the user to explicitly instantiate named Logger and configure them with Handler , Formatter and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found