sighalt / logdecorator

Move logging code out of your business logic with python decorators.
MIT License
73 stars 12 forks source link

Access self in logging of instance methods #15

Closed analyticd closed 3 years ago

analyticd commented 3 years ago

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.

sighalt commented 3 years ago

Hi @analyticd, this already works, since all arguments are passed to the format string:

from logdecorator import log_on_end
import logging

class A:
    @log_on_end(logging.INFO, "self.var = {self.var}")
    def __init__(self, var):
        self.var = var

logging.basicConfig(level=logging.INFO)

A(12)
# output: INFO:__main__:self.var = 12
analyticd commented 3 years ago

Thanks for your reply. A new day and it works for me too. No changes to the code. I don't know what to say as I don't know why it didn't yesterday. Lol. Appreciate your responsiveness and for the awesome lib too.