jrobichaud / django-structlog

Structured Logging for Django
https://django-structlog.readthedocs.io/en/latest/
MIT License
434 stars 34 forks source link

Add support to override `user_id` key instead of `pk` #545

Closed sshishov closed 4 months ago

sshishov commented 4 months ago

Currently the user_id context variable is set from pk (primary_key), but some organizations are using different field, like UUID or similar to track their "public" identifiers.

I would like to request to add the support to override pk field to anything else, set inside settings. In this case we do not need to override all signals in order to record proper user id.

And for backward compatibility we can set the default value of the setting to pk.

Proposal:

@staticmethod
def extract_user_id(request):
    if hasattr(request, "user") and request.user is not None:
        user_id = None
        if hasattr(request.user, app_settings.USER_ID_KEY):
            user_id = getattr(request.user, app_settings.USER_ID_KEY)
            if isinstance(user_id, uuid.UUID):
                user_id = str(user_id)
        structlog.contextvars.bind_contextvars(user_id=user_id)

This is the follow up after https://github.com/jrobichaud/django-structlog/issues/80

jrobichaud commented 4 months ago

I agree with the idea.

I was thinking of naming the setting app_settings.USER_ID_FIELD instead.

Also, I'd like to support assigning None to app_settings.USER_ID_FIELD in order to completely disable the logging of the user_id.

jrobichaud commented 4 months ago

@sshishov please see #546

jrobichaud commented 4 months ago

8.1.0 is out