title: Serialize LogRecords in Python
body: <p>I want to test the logging output of a method.</p>
  
  <p>Everything works good, except I found no easy way to check if the logging which was done is the way I want it to be.</p>
  
  <p>Up to now I get this exception:</p>
  
  <pre><code>TypeError: &lt;logging.LogRecord object&gt; is not JSON serializable
  </code></pre>
  
  <p>Here is the code:</p>
  
  <pre><code>class TestCase(unittest.TestCase):
     def test_foo(self):
          logger=ToListLogger()
          foo=Foo.do_something(logger)
          self.assertEqual('[...]', json.dumps(logger.records))
  </code></pre>
  
  <p>ToListLogger:</p>
  
  <pre><code>class ToListLogger(logging.Logger):
      def __init__(self):
          super(ToListLogger, self).__init__('ToListLogger')
          self.records=[]
  
      def handle(self, record):
          self.records.append(record)
  </code></pre>
  
  <p>I search a way to serialize LogRecord instances to a human readable format. JSON is my favorite, but an other would be acceptable.</p>
  
  <p>My intention: The test should be short, nice and readable.</p>
  
  <p><strong>Solution</strong></p>
  
  <p>My Solution, based on the answer of maccinza:</p>
  
  <p>TestCase:</p>
  
  <pre><code>class TestCase(unittest.TestCase):
     def test_foo(self):
          logger=ToListLogger()
          foo=Foo.do_something(logger)
          self.assertEqual('[...]', logger.to_json())
  </code></pre>
  
  <p>ToListLogger:</p>
  
  <pre><code>class ToListLogger(logging.Logger):
      def __init__(self):
          super(ToListLogger, self).__init__('ToListLogger')
          self.records=[]
  
      def handle(self, record):
          self.records.append(record)
  
      def to_json(self):
          return LogRecordEncoder().encode(self.records)
  
  class LogRecordEncoder(json.JSONEncoder):
      def default(self, obj):
          if isinstance(obj, logging.LogRecord):
              return dict(msg=obj.msg)
          raise NotImplementedError()
  </code></pre>