structlog icon indicating copy to clipboard operation
structlog copied to clipboard

Decorator for basic enter and exit logging for functions.

Open anudeepsamaiya opened this issue 5 years ago • 2 comments

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.

anudeepsamaiya avatar Jan 23 '20 12:01 anudeepsamaiya

@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'

JCapriotti avatar Oct 04 '20 16:10 JCapriotti

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

anudeepsamaiya avatar Oct 05 '20 05:10 anudeepsamaiya