sighalt / logdecorator Goto Github PK
View Code? Open in Web Editor NEWMove logging code out of your business logic with python decorators.
License: MIT License
Move logging code out of your business logic with python decorators.
License: MIT License
Hi,
we want to add some log messages if a method returns a specific result (like False
or None
). I couldn't find a suitable decorator to archive this behaviour.
Are there any plans to add a decorator like described above to your project?
Or maybe you can explain how to extend your code to write my own decorator, based on your code?
From https://github.com/sighalt/logdecorator#documentation
An alternative logger object. If no logger is given logdecorator creates a logger object with the name of the module the decorated function is in (
decorated_function.__module__
) Default: Creates a new logger with the namedecorated_function.__module__
I find that the auto-created logger with the name of the decorated function is very useful. It might help to be able to specify a handler for this auto-created logger, e.g.
# app.py
import logging
logging.basicConfig(level=logging.INFO)
# Set up pyzmq log handler
from zmq.log.handlers import PUBHandler
ctx = zmq.Context.instance()
publisher = ctx.socket(zmq.PUB)
publisher.bind('ipc://log')
zmq_log_handler = PUBHandler(publisher)
# Set up logdecorator
from logdecorator import log_on_start
@log_on_start(logging.INFO, "Starting greeter", handler=zmq_log_handler)
def greeter():
print("Hello world")
greeter()
Then, on a separate process, I would first run the following to listen for a log event:
$ python -m zmq.log ipc://log
Again, on a separate process, I run the main script:
$ python app.py
Starting to use mypy --strict which disallows usage of this decorator package since it is untyped. If I had more time I'd fork it and type it for you. So, it is just a wishlist item for those of us whose projects need or want to pass mypy --strict type checking. Great package, thanks!
This would be a useful resource if you decide to undertake this: Typing decorators
A new decorator log_exception
should be implemented using logger.exception
.
I've my own configuration of logger, that writes to FileHandler & StreamHandler, has custom formatting and etc..
I would like to use it.
How this is achievable with this library?
Hi,
there seems to be a mistake in your documentation, if i try to log errors like this:
@log_on_error(logging.ERROR, "Error on downloading",
on_exceptions=[MyException1, MyException2],
reraise=True)
i receive the following error:
TypeError: catching classes that do not inherit from BaseException is not allowed
this is because you try to catch the exceptions like defined in on_exceptions
but the Python Docs (*) state the following:
An except clause may name multiple exceptions as a parenthesized tuple, for example:
so we must use the decorator like this:
@log_on_error(logging.ERROR, "Error on downloading",
on_exceptions=(MyException1, MyException2),
reraise=True)
As pointed out by z33kz33k in #11 a KeyError occurs when an optional parameter is used in the format string, but is omitted when calling the decorated functions.
Example:
import logging
from logdecorator import log_on_start
@log_on_start(logging.INFO, "Param: {param}")
def fn(param=None):
pass
fn()
Is it possible to log the decorated function name just like in args or return value?
ie. from this to
@log_on_start(logging.DEBUG, "Starting process_text_files with {file_name:s}")
def process_text_files(file_name=None):
pass
something like this,
@log_on_start(logging.DEBUG, "Starting {_function:s} with {file_name:s}")
def process_text_files(file_name=None):
pass
Hello,
the log_exception
decorator tries to force me to log on level ERROR
instead of CRITICAL/FATAL
or any self defined level, if i use one of those levels i get the following warning:
UserWarning: `log_exception` can only log into ERROR log level
What's the intention behind this warning? Why is this decorator bound to this specific log level?
It would be nice to be able to have access in messages to data sitting on self
, if the decorated function is a method.
For instance, I use logdecorator
with my SshClient
class (a simple wrapper for some features of paramiko
and scp
). So I use log_on_start
on my connect()
method and the message is a simple:
"Establishing connection"
.
But if I had access to host
and port
that are sitting unused on self
, the message would be a more descriptive:
"Establishing connection to {host}:{port}"
.
Nice decorator lib. Thanks for open sourcing it.
I can log messages involving self if I return self in the instance method:
def batz(self) -> FooBar:
...
return self
and then do, say:
@log_on_end(log_level=logging.DEBUG, "self.foo: {self.foo}", logger=logger, result_format_variable="self")
but it would be nice if I could access self without returning self as some instance methods should not have a return value, or more specifically should return None. I.e., It would be cool to use logdecorator to log instance var state without having to add a return of self to accomplish it.
I looked at the code and perhaps it could be done, but I'd have to look into it further. I guess it could be a feature request if it isn't already possible in some better way that I have not yet discovered.
Hi! First of all, thanks for the great project. I've been using it since recently and find it a great convenience.
Unfortunately I noticed that the decorators hide the type hints of the decorated functions, making mypy complain about mismatching types. For example:
@log_on_end(...)
def foo() -> bool:
return True
Results in mypy reporting the returned type as Any
, while the actual type is bool. This can be solved by using PEP-612.
Is there any chance you could update your type hints to use PEP-612 for the next release in order to preserve the original types?
Logdecorator isn't asyncio compatible, the logs get fired before the coroutine is awaited.
See this example:
In [9]: @log_on_start(logging.CRITICAL, "START")
...: @log_on_end(logging.CRITICAL, "END")
...: async def test():
...: print("test")
...:
In [10]:
In [10]: await test()
START
END
test
Expected Output was:
START
test
END
Its not even necessary to await the coroutine, see:
In [14]: test()
START
END
Out[14]: <coroutine object test at 0x7f14c7cefc48>
Is it possiable to access local variable inside a function with log decorator ?
Hi and thanks for this awesome project,
i think you should consider making log_on_error
and log_exception
decorators reraise exceptions by default.
Otherwise adding those decorators would change my existing program flow (of course i can explicit set reraise
to true
, but in my opinion the logging part should not per default affect the flow of my program).
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.