Skip to content

Example in documentation doesn't work. #823

Description

@lavirlifiliol

The following example is present in https://www.structlog.org/en/latest/getting-started.html
In Python, log being assigned anywhere in view makes it a local variable, and so the first access to log is always going to create an unbound local error. It would be helpful to clarify the idiomatic pattern here.

def view(request):
    log = log.bind(
        user_agent=request.get("HTTP_USER_AGENT", "UNKNOWN"),
        peer_ip=request.client_addr,
    )

    if foo := request.get("foo"):
        log = log.bind(foo=foo)

    if something:
        log.info("something")
        return "something"
    elif something_else:
        log.info("something_else")
        return "something_else"
    else:
        log.info("else")
        return "else"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions