DEV Community

Rodrigo Suárez
Rodrigo Suárez

Posted on • Updated on

Use assertLogs to test Python logs

Is well-known that logs can save us the day if we use them correctly.
In most cases, create correct logs and add them into the corrects places are crucial to analyze our system flow. On the other hand, we know too, that to get a good night nap with a clear conscience we MUST test our code.

Getting together the best of these worlds, we have a good practice that can help us to make sure that a log will be written if we follow a particular path of the flow.
Imagine that you want to log if a result is false, and you want to ensure that it will be in the log file tomorrow. For ensuring that nobody will change this behavior without your consent, or maybe, be deleted by yourself in the future. You will have a test that accuses this action.

If you are a Python developer, good news! It has an excellent assert function to do that!
I didn't know about the existence of this. I think it's a good idea considering it in your upcoming tests.

Here a dummy example:

import logging

logger = logging.getLogger('backend')

# ...

def foo(self, num):
    if num == 1:
        logger.warning('One is not acepted')
        return False
    # Do somenthing ...
    return True

# ...

def test_foo(self):
    with self.assertLogs('backend', level='INFO') as cm:
        result =
    self.assertIn('WARNING:backend:One is not acepted', cm.output)

You can read more here:

Top comments (3)

mrseanpaul81 profile image

Awesome, I was looking for exactly this for a personal project just now and found your post.

yashvardhandg profile image

Is there a similar function like this for pytest?

kthy profile image
Kristian Thy

Not as far as I can tell, but you can use unittest tests in pytest. This means you can just add a unittest class alongside your normal pytest tests and it will magically all work.