snok / asgi-correlation-id

Request ID propagation for ASGI apps
MIT License
370 stars 29 forks source link

Accept a string template to generate the ID value. #31

Closed williamjamir closed 2 years ago

williamjamir commented 2 years ago

First of all, thanks for the library!

Would you be willing to accept a PR that adds a new parameter on CorrelationIdMiddleware to generate a new ID value based on a template?

My idea is to have something like:

app.add_middleware(
    CorrelationIdMiddleware,
    id_value_template='MyService-{uuid}'
)

And in my understanding this change will only affect these lines: https://github.com/snok/asgi-correlation-id/blob/main/asgi_correlation_id/middleware.py#L43-L49

sondrelg commented 2 years ago

Hi @williamjamir!

What is the use-case for this, just for my own understanding?

If it's a matter of altering the way the ID appears in your logs, I think a better solution would be to create your own log filter.

You could copy this filter and alter the record value to something like this:

class CorrelationId(Filter):
    def filter(self, record: 'LogRecord') -> bool:
        cid = correlation_id.get()
        record.correlation_id = f'MyService-{cid[:uuid_length]}'
        return True
sondrelg commented 2 years ago

Closing for now, as I think this is resolved. Feel free to reopen if you have more questions.