Skip to main content

Decorator for logging function arguments by human-readable way

Project description

logwrap

https://travis-ci.org/penguinolog/logwrap.svg?branch=master https://coveralls.io/repos/github/penguinolog/logwrap/badge.svg?branch=master Documentation Status https://img.shields.io/pypi/v/logwrap.svg https://img.shields.io/pypi/pyversions/logwrap.svg https://img.shields.io/pypi/status/logwrap.svg https://img.shields.io/github/license/penguinolog/logwrap.svg

logwrap is a helper for logging in human-readable format function arguments and call result on function call.

Pros:

Python 2.7
Python 3.4
Python 3.5
Python 3.6
PyPy
Jyton 2.7

This package also includes helpers:

  • pretty_repr

  • pretty_str

  • PrettyFormat

  • async_logwrap on python 3.5+ only

Usage

logwrap

The main decorator. Could be used as not argumented (@logwrap.logwrap) and argumented (@logwrap.logwrap()). Not argumented usage simple calls with default values for all positions. Argumented usage with arguments from signature:

@logwrap.logwrap(
    log=logging.getLogger(__name__),  # __name__ = 'logwrap'
    log_level=logging.DEBUG,
    exc_level=logging.ERROR,
    max_indent=20,  # forwarded to the pretty_repr
    spec=None,  # use target callable function for spec
    blacklisted_names=None,  # list argument names, which should be dropped from log
)

Usage examples:

@logwrap.logwrap()
def foo():
    pass

is equal to:

@logwrap.logwrap
def foo():
    pass

Get decorator for use without parameters:

get_logs = logwap.logwrap()  # set required parameters via arguments

@get_logs
def foo():
    pass

Call example:

import logwrap

@logwrap.logwrap
def example_function1(
        arg1: str,
        arg2: str='arg2',
        *args,
        kwarg1: str,
        kwarg2: str='kwarg2',
        **kwargs
) -> tuple():
    return (arg1, arg2, args, kwarg1, kwarg2, kwargs)

example_function1('arg1', kwarg1='kwarg1', kwarg3='kwarg3')

This code during execution will produce log records:

Calling:
'example_function1'(
    # POSITIONAL_OR_KEYWORD:
    'arg1'=u'''arg1''',
    'arg2'=u'''arg2''',
    # VAR_POSITIONAL:
    'args'=(),
    # KEYWORD_ONLY:
    'kwarg1'=u'''kwarg1''',
    'kwarg2'=u'''kwarg2''',
    # VAR_KEYWORD:
    'kwargs'=
         dict({
            'kwarg3': u'''kwarg3''',
         }),
)
Done: 'example_function1' with result:

 tuple((
    u'''arg1''',
    u'''arg2''',
    (),
    u'''kwarg1''',
    u'''kwarg2''',
     dict({
        'kwarg3': u'''kwarg3''',
     }),
 ))

Limitations: * return value from awaitable objects (async def(…) is not accessible - on call asyncio object is returned. Please use async_logwrap instead.

  • nested wrapping (@logwrap @deco2 …) is not parsed under python 2.7: funcsigs limitation. Please set logwrap as the first level decorator.

async_logwrap

Async version of logwrap decorator. Usage is the same as logwrap, but result object type is coroutine. This method is available only on python 3.5+ installations.

Example:

import asyncio

import logwrap

@logwrap.async_logwrap
async def foo():
    pass

asyncio.get_event_loop().run_until_complete(foo())

Remember: async_logwrap can be applied over classic functions, but anyway it will return coroutine:

import asyncio

import logwrap

@logwrap.async_logwrap
def foo():
    pass

asyncio.get_event_loop().run_until_complete(foo())

pretty_repr

This is specified helper for making human-readable repr on complex objects. Signature is self-documenting:

def pretty_repr(
    src,  # object for repr
    indent=0,  # start indent
    no_indent_start=False,  # do not indent the first level
    max_indent=20,  # maximum allowed indent level
    indent_step=4,  # step between indents
    py2_str=False,  # use bytes for python 2 __repr__ and __str__
)

Limitation: Dict like objects is always marked inside {} for readability, even if it is collections.OrderedDict (standard repr as list of tuples).

pretty_str

This is specified helper for making human-readable str on complex objects. Signature is self-documenting:

def pretty_str(
    src,  # object for __str__
    indent=0,  # start indent
    no_indent_start=False,  # do not indent the first level
    max_indent=20,  # maximum allowed indent level
    indent_step=4,  # step between indents
    py2_str=False,  # use bytes for python 2 __repr__ and __str__
)
Limitations:

Dict like objects is always marked inside {} for readability, even if it is collections.OrderedDict (standard repr as list of tuples).

Iterable types is not declared, only brackets is used.

String and bytes looks the same (its __str__, not __repr__).

PrettyFormat

PrettyFormat is the main formatting implementation class. on pretty_repr instance of this class is created and executed. This class is mostly exposed for typing reasons. Object signature:

def __init__(
    self,
    simple_formatters,  # Will be used to repr not complex. Keys is data types and 'default'.
    complex_formatters,  # Currently only legacy pretty_repr formatters is supported, will be extended in the future
    keyword='repr',  # Currently 'repr' is supported, will be extended in the future
    max_indent=20,  # maximum allowed indent level
    indent_step=4,  # step between indents
    py2_str=False,  # use bytes for python 2 __repr__ and __str__
)

Callable object (PrettyFormat instance) signature:

def __call__(
    self,
    src,  # object for repr
    indent=0,  # start indent
    no_indent_start=False  # do not indent the first level
)

Adopting your code

pretty_repr behavior could be overridden for your classes by implementing specific magic method:

def __pretty_repr__(
    self,
    parser  # PrettyFormat class instance,
    indent  # start indent,
    no_indent_start  # do not indent the first level
):
    return ...

This method will be executed instead of __repr__ on your object.

Testing

The main test mechanism for the package logwrap is using tox. Test environments available:

pep8
py27
py34
py35
py36
pypy
jyton
pylint
docs

CI systems

For code checking several CI systems is used in parallel:

  1. Travis CI: is used for checking: PEP8, pylint, bandit, installation possibility and unit tests. Also it’s publishes coverage on coveralls.

  2. coveralls: is used for coverage display.

CD system

Travis CI: is used for package delivery on PyPI.

Project details


Release history Release notifications | RSS feed

This version

2.1.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

logwrap-2.1.0.tar.gz (21.6 kB view hashes)

Uploaded Source

Built Distribution

logwrap-2.1.0-py2.py3-none-any.whl (17.8 kB view hashes)

Uploaded Python 2 Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page