structlog icon indicating copy to clipboard operation
structlog copied to clipboard

JSONRenderer and not serializable dict keys

Open askurihin opened this issue 5 years ago • 3 comments

This code


import uuid
import structlog             

structlog.configure(processors=[structlog.processors.JSONRenderer()]) 
structlog.get_logger().info({uuid.uuid4(): 1})

fails with TypeError

TypeError: keys must be str, int, float, bool or None, not UUID

In my setup, I can fix this issue by using a custom json encoder, passed to json.dums using cls argument. What do you suggest, fix the issue in structlog code or mention this case in the docs?

askurihin avatar Jun 22 '20 16:06 askurihin

This seems a very fringe use-case. Ultimately, if you want to pass non-standard datatypes into your log entries, you have to customize dumps anyway. If you want to have non-standard keys, that's even more true. I would recommend to do it via default argument if possible though.

hynek avatar Jun 25 '20 16:06 hynek

I didn't manage to make it work via default argument, as far as I understood, default is applied to values, not keys.

I think that is quite a fringe use-case, sure, but it can be useful for someony If it is mentioned in the docs. Will you accept a PR with such change?

askurihin avatar Jun 26 '20 18:06 askurihin

Yes, because it’s rather unexpected that someone uses anything else than strings as keys. 😅

This use-case by itself is nothing I would want to add to the docs, since they are quite extensive already.

What I could imagine is an isolated chapter specifically on JSON logs that explains some beste practices and logging of custom types.

hynek avatar Jun 28 '20 10:06 hynek