Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature(engine): use context vars to pass context to logger #31

Open
leosmerling opened this issue Mar 18, 2021 · 0 comments
Open

feature(engine): use context vars to pass context to logger #31

leosmerling opened this issue Mar 18, 2021 · 0 comments
Labels
good first issue Good for newcomers in-spec This issue needs to be specified proposed

Comments

@leosmerling
Copy link
Collaborator

leosmerling commented Mar 18, 2021

Remove the need to call logger with context as first parameter, by introducing a context manager to set and get EventContext object on each event step call.

See https://docs.python.org/3/library/contextvars.html

asyncio support
Context variables are natively supported in asyncio and are ready to be used without any extra configuration. For example, here is a simple echo server, that uses a context variable to make the address of a remote client available in the Task that handles that client:

import asyncio
import contextvars

client_addr_var = contextvars.ContextVar('client_addr')

def render_goodbye():
    # The address of the currently handled client can be accessed
    # without passing it explicitly to this function.

    client_addr = client_addr_var.get()
    return f'Good bye, client @ {client_addr}\n'.encode()

async def handle_request(reader, writer):
    addr = writer.transport.get_extra_info('socket').getpeername()
    client_addr_var.set(addr)

    # In any code that we call is now possible to get
    # client's address by calling 'client_addr_var.get()'.

    while True:
        line = await reader.readline()
        print(line)
        if not line.strip():
            break
        writer.write(line)

    writer.write(render_goodbye())
    writer.close()

async def main():
    srv = await asyncio.start_server(
        handle_request, '127.0.0.1', 8081)

    async with srv:
        await srv.serve_forever()

asyncio.run(main())

# To test it you can use telnet:
#     telnet 127.0.0.1 8081
@leosmerling-hopeit leosmerling-hopeit added in-spec This issue needs to be specified proposed labels Mar 22, 2021
@leosmerling leosmerling changed the title feature(engine): use context manager to pass context to logger feature(engine): use context vars to pass context to logger May 18, 2021
@leosmerling-hopeit leosmerling-hopeit added the good first issue Good for newcomers label Oct 25, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
good first issue Good for newcomers in-spec This issue needs to be specified proposed
Projects
None yet
Development

No branches or pull requests

2 participants