Kludex / asgi-logger

Access logger for ASGI servers! :tada:
MIT License
48 stars 8 forks source link

Automatic escape of header fields #40

Open elukey opened 1 year ago

elukey commented 1 year ago

Hi!

I am trying this library with KServe (see https://github.com/kserve/kserve/pull/2782) and I noticed that headers like User-Agent are not automatically escaped. Could it be a feature to add? For example, if I set something like:

'{"remote_address": "%(h)s", "user_name": "%(u)s", "date": "%(t)s", "status": "%(s)s", "method": "%(m)s", "url_path": "%(U)s", "query_string": "%(q)s", "protocol": "%(H)s", "response_length": "%(B)s", "referer": "%(f)s", "user_agent": "%(a)s", "request_time_seconds": "%(L)s"}'

The above leads to valid JSON only if the HTTP headers don't carry extra quotes. I am not sure where the escape would fit best, but added to this library (maybe with a flag?) could be a nice addition. I can work on a PR if the idea is acceptable :)

Kludex commented 1 year ago

Sure

elukey commented 1 year ago

@Kludex If you have time I'd need an advice about the best road to take. Ideally having a JSON representation of the Uvicorn access logs would be nice, so I tried multiple roads:

1) As described above, hacked the format string to print a JSON-like output, but it is not very resilient when we have special chars. 2) Run uvicorn with a python json logger in its access log logging config (like python-json-logger) but when I override it with asgi-logger I loose also the JSON formatting.

Not sure if you have suggestions about 1), otherwise another solution could be to add a "json" flag to asgi-logger to use a json formatter in AccessLoggerMiddleware. No idea what road is best, I am all ears for suggestions :)

Thanks in advance!