question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to test loguru logger with unittest?

See original GitHub issue

I’ve got a project which is not using pytest. How can I successfully assert log statements made by loguru using unittests?

For example, I’ve got:

# test_loguru.py

import contextlib
import io
from unittest import TestCase

from loguru import logger


class LoggerTest(TestCase):
    def test_logger_stderr(self):
        f = io.StringIO()
        with contextlib.redirect_stderr(f):
            logger.info("loguru log right here")

        self.assertEqual("loguru log right here\n", f.getvalue())

Running the test reveals I’m unsuccessful in capturing the loguru output:

$ python -m unittest test_loguru.py
2022-03-14 15:01:40.597 | INFO     | test_loguru:test_logger_stderr:12 - loguru log right here
F
======================================================================
FAIL: test_logger_stderr (test_loguru.LoggerTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/fredrik/code/repos/logger/test_loguru.py", line 14, in test_logger_stderr
    self.assertEqual("loguru log right here\n", f.getvalue())
AssertionError: 'loguru log right here\n' != ''
- loguru log right here


----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
Delgancommented, Mar 15, 2022

Good point, I had forgotten that the format had to be adjusted as well!

I added the snippet to the documentation: Replacing assertLogs() method from unittest library.

Thanks for bringing this to my attention. 👍

0reactions
fredrikaverpilcommented, Mar 15, 2022

Very nice, this is a lot cleaner! 😃

I’m also thinking I’ll add in an arguments level and format (with some sane default), so I can tell individual tests what I’m actually probing for. Most of the time I don’t want to bother about the datetime string for example.

from contextlib import contextmanager

@contextmanager
def capture_logs(
    level="INFO", format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} - {message}"
):
    """Capture loguru-based logs."""
    output = []
    handler_id = logger.add(output.append, level=level, format=format)
    yield output
    logger.remove(handler_id)

Would be great to have this in the docs, yes! 😄

Read more comments on GitHub >

github_iconTop Results From Across the Web

PyDev unittesting: How to capture text logged to a logging ...
Does anybody know how to capture everything that is logged to a logging.Logger during the execution of this test? python · unit-testing ·...
Read more >
How To Unit Test Logging In Python (Asserting Logs) - YouTube
In this tutorial we will explore how to write unit test to check and assert you logs in python using unittest and pytest...
Read more >
Switching from standard logging to loguru
Using Loguru, there is no need to explicitly get and name a logger, ... The caplog fixture captures logging output so that it...
Read more >
How To Test Logging In Python?
1. Use The AssertLogs Context Manager From unitest ... If you are using unittest - the default Python testing library - you can...
Read more >
loguru Documentation - Read the Docs
The rotation check is made before logging each message. ... method defined in the unittest from standard library is used to capture and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found