Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(958) Add exception logging in debug mode #976

Merged
merged 19 commits into from
Feb 4, 2023
Merged

(958) Add exception logging in debug mode #976

merged 19 commits into from
Feb 4, 2023

Conversation

JacobCoffee
Copy link
Member

@JacobCoffee JacobCoffee commented Dec 22, 2022

Re: Issue #958

PR Checklist

  • Have you followed the guidelines in CONTRIBUTING.md?
  • Have you got 100% test coverage on new code?
  • Have you updated the prose documentation?
  • Have you updated the reference documentation?

@JacobCoffee JacobCoffee changed the title Add exception logging in debug mode (958) Add exception logging in debug mode Dec 22, 2022
@Goldziher
Copy link
Contributor

so, wassup here? Why does this take so long?

@JacobCoffee
Copy link
Member Author

not 100% sure on the testing here, can someone verify it is checking correctly?

@JacobCoffee JacobCoffee marked this pull request as ready for review January 23, 2023 22:57
Co-authored-by: Na'aman Hirschfeld <nhirschfeld@gmail.com>
@provinzkraut provinzkraut linked an issue Jan 27, 2023 that may be closed by this pull request
@provinzkraut
Copy link
Member

@JacobCoffee What's the status of this?

@provinzkraut
Copy link
Member

The remaining problem here is that app.logger.debug is called (which is correct), but the starlite logger is at the INFO level. I propose the following changes to the default logging configuration when debug=True is passed to Starlite:

  1. If no logger is configured and logging_config is not explicitly set to None, configure a logger
  2. Set the starlite logger to DEBUG

@JacobCoffee
Copy link
Member Author

I am working on a fix for the pytest issue via this
pytest-dev/pytest#3697 (comment)

@provinzkraut provinzkraut added this to the 2.0 milestone Feb 2, 2023
@peterschutt
Copy link
Contributor

@JacobCoffee have you seen this fixture in the logging middleware tests?

https://github.com/starlite-api/starlite/blob/901596e566cd1b0ab902e67867300b7d8cf4e348/tests/middleware/test_logging_middleware.py#L29-L38

I'd say that's there to solve the same problem that you are hitting here, although there might be other reasons for it also. However, if you are looking for a low friction way to get this through, then you could move that fixture out of tests/middleware/test_logging_middleware.py and move it into tests/middleware/conftest.py, change the log level that is set in the fixture to debug, and set the logger returned from that callable on to your application logger for the test.

I've done this and have tested that the full suite passes, so I'll PR it into your fork and you can take a look.

If you do still want to go the route of implementing that capturing context manager pattern from the linked issue, you should perhaps look at whether we can apply that to the logging middleware tests where the current fixture-based workaround is being applied as well.

- moves get_logger fixture to conftest.py for middleware tests
- patches app logger in tests with one that propagates so caplog works.
@provinzkraut
Copy link
Member

@peterschutt

I've done this and have tested that the full suite passes

This fixture was my first attempt as well, but it didn't seem to work as intended.

@pytest.fixture
def get_logger():
    return LoggingConfig(
        handlers=default_handlers,
        loggers={
            "starlite": {"level": "DEBUG", "handlers": ["queue_listener"], "propagate": True},
        },
    ).configure()


@pytest.mark.parametrize(
    "debug,logging_config",
    [
        (True, LoggingConfig()),
        (False, LoggingConfig()),
        (False, None),
    ],
)
def test_exception_handler_middleware_debug_logging(
    get_logger, caplog: "LogCaptureFixture", debug: bool, logging_config: Optional[LoggingConfig]
) -> None:
    @get("/test")
    def handler() -> None:
        raise ValueError("Test debug exception")

    app = Starlite([handler], logging_config=logging_config, debug=debug)
    app.get_logger = get_logger

    with TestClient(app=app) as client, caplog.at_level("DEBUG"):

        response = client.get("/test")
        assert response.status_code == HTTP_500_INTERNAL_SERVER_ERROR
        assert "Test debug exception" in response.text

        if debug and logging_config:
            assert len(caplog.records) == 1
            # other assertions for the content of this record here
        else:
            assert not caplog.records

Still fails for me. How did you get it working?

Anyway, I tested the workaround @JacobCoffee linked, and it seems to me that it's a more stable solution. I think it's worth generally adopting that for our tests. Wdyt?

@peterschutt
Copy link
Contributor

I hit that too, but the code accesses app.logger, it doesn't call app.get_logger(). So, instead of app.get_logger = ... I used app.logger = get_logger("starlite").

@peterschutt
Copy link
Contributor

I think it's worth generally adopting that for our tests. Wdyt?

I agree, but whether that is something that @JacobCoffee wants to do as part of this task, or we split it out to another issue, I'm not fussed.

JacobCoffee and others added 3 commits February 3, 2023 10:41
…ents_ps

Use `get_logger` fixture to test exception logged in debug.

Co-authored-by: Peter Schutt <peter.github@proton.me>
@@ -47,6 +47,8 @@ async def __call__(self, scope: "Scope", receive: "Receive", send: "Send") -> No
await self.app(scope, receive, send)
except Exception as e: # pylint: disable=broad-except
starlite_app = scope["app"]
if self.debug and (logger := starlite_app.logger):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if self.debug and (logger := starlite_app.logger):
if self.debug and (logger := starlite_app.get_logge()):

no?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps, but it broke my test 🙃 looking into why tonight hopefully

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe because the function isn’t called get_logge but get_logger? 😉

Copy link
Member Author

@JacobCoffee JacobCoffee Feb 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i fixed that as soon as i committed the suggestion and realized 😛
commit dffccbf

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this change breaks the test, it most likely is because we are patching app.logger with response of calling the get_logger fixture in the test, whereas for this to work, we'd have to patch the app.get_logger attribute with the get_logger fixture itself.

In the starlite constructor, we both assign the get_logger callable and a logger instance to the application instance:

        if self.logging_config:
            self.get_logger = self.logging_config.configure()
            self.logger = self.get_logger("starlite")

...and it wasn't obvious to me which one we should be using in this case either.

@Goldziher
Copy link
Contributor

@all-contributors add @JacobCoffee code

@allcontributors
Copy link
Contributor

@Goldziher

@JacobCoffee already contributed before to code

@Goldziher Goldziher merged commit 21f4a2f into litestar-org:main Feb 4, 2023
@provinzkraut
Copy link
Member

@Goldziher Why was this merged? Tests are not passing.

provinzkraut added a commit that referenced this pull request Feb 4, 2023
@JacobCoffee JacobCoffee deleted the 985_debug_console_log_enhancements branch February 6, 2023 17:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Enhancement: Log tracebacks to console in debug mode
5 participants