I just implemented logging in my app, and I'd like to know if there's a method to check if a logger is empty or not.
What I have in mind is to set two handlers in my script:
WARNING
DEBUG
At the end of the script, I need to check if CONSOLE
logger is not empty. This means that during the run, some messages with level >= WARNING
were logged, and in this case I'd like to send the log file with debug level thru smtp
to my mailbox.
Is this check possible inside the python
script itself, without shell redirection to file?
There's a general purpose way to count the number of times a function was called using decorators you can check out here
If you wrap this decorator around class calls you are interested in you could find out how many times each member function was called, something like this:
def counted(fn):
def wrapper(*args, **kwargs):
wrapper.called += 1
return fn(*args, **kwargs)
wrapper.called = 0
wrapper.__name__ = fn.__name__
return wrapper
class MyLogger(logging.Logger, object):
@counted
def info(self, *args, **kwargs):
super(MyLogger, self).info(*args, **kwargs)
@counted
def warning(self, *args, **kwargs):
super(MyLogger, self).warning(*args, **kwargs)
Next just set up your logger like any other and use it as you normally would:
log = my_logger.MyLogger('test_logger')
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
log.addHandler(ch)
log.setLevel(logging.DEBUG)
>>> log.info('no big deal')
no big deal
>>> log.info('harmless message')
harmless message
>>> log.warning('oh no')
oh no
>>> log.info.called
2
>>> log.warning.called
1
You would need to decorate all of the classes you wanted counted, so exception, debug etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With