Setting logging level in unit tests for Gradle plugin

Hi. In my plugin in addition to functional tests I have unit tests of the plugin logic. I would like to be able to change logging level to see also INFO messages (by default only LIFECYCLE+ are visible).

In my code I use standard Slf4j’s Logger. First I tried with logback.xml, but Gradle seems to use its own slf4j implementation (OutputEventListenerBackedLogger) which wins in unit tests in runtime (although the code is Gradle agnostic) and I need (in a very ugly way) to get context from the logger and set in it (and in addition in OutputEventRenderer) a desired level.

What is a recommended way to configure logging level in unit tests (where Gradle engine isn’t itself involved in the execution)?

Guys, is it at all possible to do in a civilized way?

1 Like

Reported as a feature request.

I don’t think it’s possible. From my perspective it would also not be a unit test as your are reaching out of your class to an external system. In this case the external system would be the logging system. Here’s how I’d solve it as unit test.

  1. Mock the Logger instance and inject it via a package-level method (or better constructor) into the class under test.
  2. Assert that certain logger methods are called based on the expected logic.

Thanks for your answer Benjamin. I agree I should not use it for real unit tests (and those tests I don’t care about logging). I accidentally misled you.

The tests I have problem with are the integration tests which do not use Gradle infrastructure (they just call to external systems and I verify/debug so integration issues). In those tests logging is very important (when something doesn’t work correctly) as I may need to see for example requests and responses which isn’t logged at the LIFECYCLE+ level (to do not spam console output in the Gradle execution).

The main issue here seems to be the fact that my SLF4J loggers are “intercepted” by Gradle logging mechanism even if Gradle itself isn’t executed (it is just on a classpath and probably is loaded first). Maybe in slf4j 1.8.0 it will be possible to set a different implementation precedence in unit tests, but currently it would be nice to have an ability to control somehow Gradle logging configuration (in the better way than changing private properties in OutputEventListenerBackedLogger).

OK, thanks for the explanation. Sorry, I can’t give you any other advice. I am not super familiar with the SLF4J logging integration with Gradle or what could be done about your problem in your context.