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

Decorator for basic enter and exit logging for functions. #241

Open
anudeepsamaiya opened this issue Jan 23, 2020 · 2 comments
Open

Decorator for basic enter and exit logging for functions. #241

anudeepsamaiya opened this issue Jan 23, 2020 · 2 comments

Comments

@anudeepsamaiya
Copy link

anudeepsamaiya commented Jan 23, 2020

A decorator that creates a log statement with bound variables at entry and exit of the decorated functions. The bound variables can be set, reset or updated, so every log statement from inside the function can use these.

On entry, the decorator will print the passed passed parameters along with bound variables, and upon exit it will print the returned value if any in the exit log message.

This approach helps in removing the redundant log statements for entry and exit.
The binding of default values unrelated to the context of function in decorator also helps in achieving separation of concerns.

Thanks for the great library.

@JCapriotti
Copy link

@anudeepsamaiya I am working on a PR that has some of this. Can you give an example of your desired call and desired output?

Right now I have two decorators: one for adding context, the other for logging entry/exit.

Here's an example:

logger = structlog.get_logger()


@log_call(logger)
def my_method():
    logger.info('foo')


@log_context(fruit='apple')
@log_call(logger)
def my_method_with_context():
    logger.info('foo')


if __name__ == "__main__":
    structlog.configure(processors=[
        structlog.contextvars.merge_contextvars,
        structlog.processors.KeyValueRenderer(),
    ])
    my_method()
    my_method_with_context()

Which outputs:

event='Entered my_method'
event='foo'
event='Exited my_method'
fruit='apple' event='Entered my_method_with_context'
fruit='apple' event='foo'
fruit='apple' event='Exited my_method_with_context'

@anudeepsamaiya
Copy link
Author

Yes this is what I was trying to achieve, I have implemented the decorators in my project. Nicely done, having it as a processor is a cleaner approach.

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants