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.

Question on logger.catch()

See original GitHub issue

Hi! Is there a way to implement @logger.catch as a decorator for all tests, predeterming it in conftest.py in order to not to mark every my test? What i’m trying to do whit it now is:

# conftest.py

@pytest.fixture(autouse=True)
def write_logs(request):
    # put logs in tests/logs
    log_path = Path("Tests") / "logs"

    # tidy logs in subdirectories based on test module and class names
    module = request.module
    class_ = request.cls
    name = request.node.name + ".log"

    if module:
        log_path /= module.__name__.replace("tests.", "")
    if class_:
        log_path /= class_.__name__

    log_path.mkdir(parents=True, exist_ok=True)

    # append last part of the name
    log_path /= name

    # enable the logger
    logger.remove()
    logger.configure(handlers=[{"sink": log_path, "level": "TRACE", "mode": "w"}])
    logger.enable("my_package")

def pytest_configure(config):
    # register an additional marker
    config.addinivalue_line(
        "markers", "log_catcher: mark tests which we want to log"
    )


def pytest_collection_modifyitems(items):
    for item in items:
        item.add_marker('log_catcher')


def pytest_runtest_setup(item):
    if item.iter_markers(name="log_catcher"):
        logger.catch(reraise=True)
# test.py
class TestFirstSuite(unittest.TestCase):

    def test_01_First(self):
        assert 1+1 == 3

    def test_02_First(self):
        print('test_02_First executed')

    def test_03_First(self):
        print('test_03_First executed')

but i get no logs from this in my file.log

From debugging I see that pytest collector actually “marks” all tests, but I guess this cannot work because of the incorrect usage of “logger.catch” function or just custom decorators cant work like this if I use @logger.catch right before the def_test() then everything is working ok, but I want to mark all my tests with it and at the same time I wouldnt like to mark each test. I need “fixture” which will mark all tests automatically with this decorator during test collection. Could you help me please find the way out of this problem? What am i doing wrong and what i have to do?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:11 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
Delgancommented, Feb 21, 2021

Hi @PistonY.

There is inevitably a small performance penalty, at least with CPython interpreter. In the case of logger.catch() being used as a decorator, there is one more frame and function call due to the nested method. Also, the logger.catch() is implemented using context manager which has a cost. Apart from that, it’s a basic try / except block.

Overall, the cost on performances should negligible. If the part of your code is really critical, you can use instead try / except and then logger.exception().

0reactions
PistonYcommented, Feb 22, 2021

Thanks @Delgan .

Read more comments on GitHub >

github_iconTop Results From Across the Web

how to print an exception using logger? - java - Stack Overflow
My concern is if I do so many thing in try block and I keep only one catch block as catch(Exception e), Then...
Read more >
Top 25 Log4j Interview Questions and Answers (2022)
Here are Log4j interview questions and answers for freshers as well as experienced candidates to get their dream job.
Read more >
Logging Exceptions in Java - Loggly
A surprisingly common approach to exception handling is to catch the exception, then ignore it. Not only is the issue not handled, but...
Read more >
Log within try-catch or after? [closed]
First of all, you have to ensure that logging never throws any exceptions. It's better not to log one message than breaking program...
Read more >
The Ultimate Guide to Logging in Python - Rollbar
ERROR - A more serious problem due to which the program was unable to perform a function. CRITICAL - A serious error, indicating...
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