0

I have a function

import logging

def print_logs():
    logging.info('info log 1.')
    logging.warning('warning log 1.')
    logging.error('error log 1.')
    logging.error('error log 2.')

I would like to call this function, and then get all logs of a specified logging level. So I want to be able to do something like:

print_logs()
error_logs = get_logs_by_level('error')

or

error_logs = get_logs_by_level(print_logs, 'error')

and the function print_logs runs, and error_logs would be ['error log 1.', 'error log 2']

Is this possible?

Preethi Vaidyanathan
  • 1,203
  • 1
  • 12
  • 32

1 Answers1

0

The following is a example that installs a handler to capture the logs.

This works in Python 2.7. For Python 3 replace cStringIO.StringIO with io.StringIO or io.BytesIO. Or use the ListHander that does not need either.

If you would rather keep the log records before they are formatted or the separation between the lines for each message. This can be adapted but requires writing a Handler.

import logging
import cStringIO

class Handler(object):
    def __init__(self, handler):
        self.handler = handler
    def __enter__(self):
        logging.root.handlers.append(self.handler)
        return self.handler
    def __exit__(self, type, value, tb):
        logging.root.handlers.remove(self.handler)

def print_logs():
    logging.info('info log 1.')
    logging.warning('warning log 1.')
    logging.error('error log 1.')
    logging.error('error log 2.')

h = logging.StreamHandler(stream=cStringIO.StringIO())
h.setLevel('ERROR')

with Handler(h):
    print_logs()

error_logs = h.stream.getvalue().splitlines()
error_logs

class RecordListHandler(logging.Handler):
    def __init__(self):
        logging.Handler.__init__(self)
        self.log = []

    def emit(self, record):
        self.log.append(record)

class ListHandler(logging.Handler):

    def __init__(self):
        logging.Handler.__init__(self)
        self.log = []

    def emit(self, record):
        msg = self.format(record)
        self.log.append(msg)

h = RecordListHandler()
h.setLevel('ERROR')

with Handler(h):
    print_logs()

error_logs = h.log
error_logs

h = ListHandler()
h.setLevel('ERROR')

with Handler(h):
    print_logs()

error_logs = h.log
error_logs
Dan D.
  • 73,243
  • 15
  • 104
  • 123