Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Logging - How To Check If Logger Is Empty

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:

  • One for console with level WARNING
  • One for file with level 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 smtpto my mailbox.

Is this check possible inside the python script itself, without shell redirection to file?

like image 770
Enrico Gherardo Avatar asked Sep 28 '22 01:09

Enrico Gherardo


1 Answers

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.

like image 105
Mike Avatar answered Oct 06 '22 02:10

Mike