Using @logged, TracedMethods, and @traced together — Autologging 0.4.0 documentation

# Using `@logged`, `TracedMethods`, and `@traced` together

Release: | 0.4.0

- Add logging and tracing to a class
- Add logging and tracing to a function

## Add logging and tracing to a class

    # my_module.py

    from autologging import logged, TracedMethods

    @logged
    class MyClass(metaclass=TracedMethods())

       def __init__(self, value):
          self.__logger.info("I like %s.", value)
          self._value = value

       def my_method(self, arg, keyword=None):
          return "%s, %s, and %s" % (arg, self._value, keyword)

    >>> import logging, sys
    >>> from autologging import TRACE
    >>> logging.basicConfig(level=TRACE, stream=sys.stdout,
    ...     format="%(levelname)s:%(name)s:%(funcName)s:%(message)s")
    >>> from my_module import MyClass
    >>> my_obj = MyClass("ham")
    TRACE:my_module.MyClass:__init__:CALL *('ham',) **{}
    INFO:my_module.MyClass:__init__:I like ham.
    TRACE:my_module.MyClass:__init__:RETURN None
    >>> my_obj.my_method("spam", keyword="eggs")
    TRACE:my_module.MyClass:my_method:CALL *('spam',) **{'keyword': 'eggs'}
    TRACE:my_module.MyClass:my_method:RETURN 'spam, ham, and eggs'
    'spam, ham, and eggs'

## Add logging and tracing to a function

Warning

Although the `@logged` and `@traced` decorators will “do the right thing” regardless of the order in which they are applied to the same function, it is recommended that `@logged` always be used as the innermost decorator.

This is because `@logged` simply sets the `_logger` attribute and then returns the original function, making it “safe” to use in combination with any other decorator.

    # my_module.py

    from autologging import logged, traced

    @traced
    @logged
    def my_function(arg, keyword=None):
       my_function._logger.info("my message")
       return "%s and %s" % (arg, keyword)

    >>> import logging, sys
    >>> from autologging import TRACE
    >>> logging.basicConfig(level=TRACE, stream=sys.stdout,
    ...     format="%(levelname)s:%(name)s:%(funcName)s:%(message)s")
    >>> from my_module import my_function
    >>> my_function("spam", keyword="eggs")
    TRACE:my_module:my_function:CALL *('spam',) **{'keyword': 'eggs'}
    INFO:my_module:my_function:my message
    TRACE:my_module:my_function:RETURN 'spam and eggs'
    'spam and eggs'