如何通过 JUnit 测试拦截 SLF4J(带 logback)日志记录?
How to intercept SLF4J (with logback) logging via a JUnit test?
是否有可能以某种方式拦截日志记录(SLF4J + logback)并通过 JUnit 测试用例获得 InputStream
(或其他可读的东西)...?
您可以创建自定义附加程序
public class TestAppender extends AppenderBase<LoggingEvent> {
static List<LoggingEvent> events = new ArrayList<>();
@Override
protected void append(LoggingEvent e) {
events.add(e);
}
}
并配置 logback-test.xml 以使用它。现在我们可以检查测试中的日志记录事件:
@Test
public void test() {
...
Assert.assertEquals(1, TestAppender.events.size());
...
}
注意:如果您没有得到任何输出,请使用 ILoggingEvent
- 请参阅评论部分了解原因。
您可以使用 http://projects.lidalia.org.uk/slf4j-test/ 中的 slf4j-test。
它用自己的 slf4j api 测试实现替换了整个 logback slf4j 实现,并提供了一个 api 来断言日志事件。
示例:
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<classpathDependencyExcludes>
<classpathDependencyExcludes>ch.qos.logback:logback-classic</classpathDependencyExcludes>
</classpathDependencyExcludes>
</configuration>
</plugin>
</plugins>
</build>
public class Slf4jUser {
private static final Logger logger = LoggerFactory.getLogger(Slf4jUser.class);
public void aMethodThatLogs() {
logger.info("Hello World!");
}
}
public class Slf4jUserTest {
Slf4jUser slf4jUser = new Slf4jUser();
TestLogger logger = TestLoggerFactory.getTestLogger(Slf4jUser.class);
@Test
public void aMethodThatLogsLogsAsExpected() {
slf4jUser.aMethodThatLogs();
assertThat(logger.getLoggingEvents(), is(asList(info("Hello World!"))));
}
@After
public void clearLoggers() {
TestLoggerFactory.clear();
}
}
我在测试日志行时遇到问题,例如:LOGGER.error(消息,异常)。
http://projects.lidalia.org.uk/slf4j-test/ 中描述的解决方案也尝试对异常进行断言,并且重新创建堆栈跟踪并不容易(而且在我看来毫无价值)。
我是这样解决的:
import org.junit.Test;
import org.slf4j.Logger;
import uk.org.lidalia.slf4jext.LoggerFactory;
import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static uk.org.lidalia.slf4jext.Level.ERROR;
import static uk.org.lidalia.slf4jext.Level.INFO;
public class Slf4jLoggerTest {
private static final Logger LOGGER = LoggerFactory.getLogger(Slf4jLoggerTest.class);
private void methodUnderTestInSomeClassInProductionCode() {
LOGGER.info("info message");
LOGGER.error("error message");
LOGGER.error("error message with exception", new RuntimeException("this part is not tested"));
}
private static final TestLogger TEST_LOGGER = TestLoggerFactory.getTestLogger(Slf4jLoggerTest.class);
@Test
public void testForMethod() throws Exception {
// when
methodUnderTestInSomeClassInProductionCode();
// then
assertThat(TEST_LOGGER.getLoggingEvents()).extracting("level", "message").contains(
tuple(INFO, "info message"),
tuple(ERROR, "error message"),
tuple(ERROR, "error message with exception")
);
}
}
这也有不依赖 Hamcrest 匹配器 库的优点。
Slf4j API 没有提供这样的方法,但是 Logback 提供了一个简单的解决方案。
您可以使用 ListAppender
:一个白盒 logback appender,其中日志条目被添加到我们可以用来进行断言的 public List
字段中。
这是一个简单的例子。
富 class :
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Foo {
static final Logger LOGGER = LoggerFactory.getLogger(Foo .class);
public void doThat() {
logger.info("start");
//...
logger.info("finish");
}
}
FooTest class :
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
public class FooTest {
@Test
void doThat() throws Exception {
// get Logback Logger
Logger fooLogger = (Logger) LoggerFactory.getLogger(Foo.class);
// create and start a ListAppender
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
// add the appender to the logger
fooLogger.addAppender(listAppender);
// call method under test
Foo foo = new Foo();
foo.doThat();
// JUnit assertions
List<ILoggingEvent> logsList = listAppender.list;
assertEquals("start", logsList.get(0)
.getMessage());
assertEquals(Level.INFO, logsList.get(0)
.getLevel());
assertEquals("finish", logsList.get(1)
.getMessage());
assertEquals(Level.INFO, logsList.get(1)
.getLevel());
}
}
您还可以使用 Matcher/assertion 库作为 AssertJ 或 Hamcrest。
对于 AssertJ 它将是:
import org.assertj.core.api.Assertions;
Assertions.assertThat(listAppender.list)
.extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getLevel)
.containsExactly(Tuple.tuple("start", Level.INFO), Tuple.tuple("finish", Level.INFO));
尽管创建自定义 logback appender 是一个很好的解决方案,但这只是第一步,您最终会使用 developing/reinventing slf4j-test, and if you go a bit further: spf4j-slf4j-test 或其他我还不知道的框架。
您最终需要担心在内存中保留了多少事件、在记录错误(但未断言)时单元测试失败、在测试失败时提供调试日志等...
免责声明:我是 spf4j-slf4j-test 的作者,我编写这个后端是为了能够更好地测试 spf4j,这是查看如何使用 spf4j- 示例的好地方slf4j-测试。我取得的主要优势之一是减少了我的构建输出(Travis 的限制),同时在发生故障时仍然拥有我需要的所有细节。
一个简单的解决方案可能是使用 Mockito 模拟 appender(例如)
MyClass.java
@Slf4j
class MyClass {
public void doSomething() {
log.info("I'm on it!");
}
}
MyClassTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock private Appender<ILoggingEvent> mockAppender;
private MyClass sut = new MyClass();
@Before
public void setUp() {
Logger logger = (Logger) LoggerFactory.getLogger(MyClass.class.getName());
logger.addAppender(mockAppender);
}
@Test
public void shouldLogInCaseOfError() {
sut.doSomething();
verify(mockAppender).doAppend(ArgumentMatchers.argThat(argument -> {
assertThat(argument.getMessage(), containsString("I'm on it!"));
assertThat(argument.getLevel(), is(Level.INFO));
return true;
}));
}
}
注意:我使用的是断言而不是 returning false
,因为它使代码和(可能的)错误更易于阅读,但如果您有多个验证,它将不起作用。在这种情况下,您需要 return boolean
指示值是否符合预期。
我会推荐一个简单、可重用的间谍实现,它可以作为 JUnit 规则包含在测试中:
public final class LogSpy extends ExternalResource {
private Logger logger;
private ListAppender<ILoggingEvent> appender;
@Override
protected void before() {
appender = new ListAppender<>();
logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); // cast from facade (SLF4J) to implementation class (logback)
logger.addAppender(appender);
appender.start();
}
@Override
protected void after() {
logger.detachAppender(appender);
}
public List<ILoggingEvent> getEvents() {
if (appender == null) {
throw new UnexpectedTestError("LogSpy needs to be annotated with @Rule");
}
return appender.list;
}
}
在您的测试中,您将通过以下方式激活间谍:
@Rule
public LogSpy log = new LogSpy();
调用 log.getEvents()
(或其他自定义方法)来检查记录的事件。
使用 JUnit5 + AssertJ
private ListAppender<ILoggingEvent> logWatcher;
@BeforeEach
void setup() {
this.logWatcher = new ListAppender<>();
this.logWatcher.start();
((Logger) LoggerFactory.getLogger(MyClass.class)).addAppender(this.logWatcher);
}
@Test
void myMethod_logs2Messages() {
...
int logSize = logWatcher.list.size();
assertThat(logWatcher.list.get(logSize - 2).getFormattedMessage()).contains("EXPECTED MSG 1");
assertThat(logWatcher.list.get(logSize - 1).getFormattedMessage()).contains("EXPECTED MSG 2");
}
归功于:@davidxxx 的回答。查看 import ch.qos.logback...
详细信息:
这是一种使用 lambda 的替代方法,它使日志捕获逻辑可在测试中重用(封装其实现)并且不需要 @BeforeEach
/@AfterEach
(在某些建议的解决方案中,appender未分离,这可能导致内存泄漏)。
被测代码:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyService {
private static final Logger LOG = LoggerFactory.getLogger(MyService.class);
public void doSomething(String someInput) {
...
LOG.info("processing request with input {}", someInput);
...
}
}
拦截器助手:
package mypackage.util
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.slf4j.LoggerFactory;
import java.util.List;
public class LogInterceptor {
public static List<ILoggingEvent> interceptLogs(Class<?> klass, Runnable runnable) {
final Logger logger = (Logger) LoggerFactory.getLogger(klass);
final ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
logger.addAppender(listAppender);
try {
runnable.run();
return listAppender.list;
} finally {
logger.detachAppender(listAppender);
}
}
}
测试套件:
import static mypackage.util.LogInterceptor.interceptLogs;
public class MyServiceTest {
private MyService myService;
...
@Test
void doSomethingLogsLineWithTheGivenInput() {
List<ILoggingEvent> logs = interceptLogs(
myService.getClass(),
() -> myService.doSomething("foo")
);
assertThat(logs).isNotEmpty();
ILoggingEvent logEntry = logs.get(0);
assertThat(logEntry.getFormattedMessage()).isEqualTo("Processing request with input foo");
assertThat(logEntry.getLevel()).isEqualTo(Level.INFO);
}
}
是否有可能以某种方式拦截日志记录(SLF4J + logback)并通过 JUnit 测试用例获得 InputStream
(或其他可读的东西)...?
您可以创建自定义附加程序
public class TestAppender extends AppenderBase<LoggingEvent> {
static List<LoggingEvent> events = new ArrayList<>();
@Override
protected void append(LoggingEvent e) {
events.add(e);
}
}
并配置 logback-test.xml 以使用它。现在我们可以检查测试中的日志记录事件:
@Test
public void test() {
...
Assert.assertEquals(1, TestAppender.events.size());
...
}
注意:如果您没有得到任何输出,请使用 ILoggingEvent
- 请参阅评论部分了解原因。
您可以使用 http://projects.lidalia.org.uk/slf4j-test/ 中的 slf4j-test。 它用自己的 slf4j api 测试实现替换了整个 logback slf4j 实现,并提供了一个 api 来断言日志事件。
示例:
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<classpathDependencyExcludes>
<classpathDependencyExcludes>ch.qos.logback:logback-classic</classpathDependencyExcludes>
</classpathDependencyExcludes>
</configuration>
</plugin>
</plugins>
</build>
public class Slf4jUser {
private static final Logger logger = LoggerFactory.getLogger(Slf4jUser.class);
public void aMethodThatLogs() {
logger.info("Hello World!");
}
}
public class Slf4jUserTest {
Slf4jUser slf4jUser = new Slf4jUser();
TestLogger logger = TestLoggerFactory.getTestLogger(Slf4jUser.class);
@Test
public void aMethodThatLogsLogsAsExpected() {
slf4jUser.aMethodThatLogs();
assertThat(logger.getLoggingEvents(), is(asList(info("Hello World!"))));
}
@After
public void clearLoggers() {
TestLoggerFactory.clear();
}
}
我在测试日志行时遇到问题,例如:LOGGER.error(消息,异常)。
http://projects.lidalia.org.uk/slf4j-test/ 中描述的解决方案也尝试对异常进行断言,并且重新创建堆栈跟踪并不容易(而且在我看来毫无价值)。
我是这样解决的:
import org.junit.Test;
import org.slf4j.Logger;
import uk.org.lidalia.slf4jext.LoggerFactory;
import uk.org.lidalia.slf4jtest.TestLogger;
import uk.org.lidalia.slf4jtest.TestLoggerFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static uk.org.lidalia.slf4jext.Level.ERROR;
import static uk.org.lidalia.slf4jext.Level.INFO;
public class Slf4jLoggerTest {
private static final Logger LOGGER = LoggerFactory.getLogger(Slf4jLoggerTest.class);
private void methodUnderTestInSomeClassInProductionCode() {
LOGGER.info("info message");
LOGGER.error("error message");
LOGGER.error("error message with exception", new RuntimeException("this part is not tested"));
}
private static final TestLogger TEST_LOGGER = TestLoggerFactory.getTestLogger(Slf4jLoggerTest.class);
@Test
public void testForMethod() throws Exception {
// when
methodUnderTestInSomeClassInProductionCode();
// then
assertThat(TEST_LOGGER.getLoggingEvents()).extracting("level", "message").contains(
tuple(INFO, "info message"),
tuple(ERROR, "error message"),
tuple(ERROR, "error message with exception")
);
}
}
这也有不依赖 Hamcrest 匹配器 库的优点。
Slf4j API 没有提供这样的方法,但是 Logback 提供了一个简单的解决方案。
您可以使用 ListAppender
:一个白盒 logback appender,其中日志条目被添加到我们可以用来进行断言的 public List
字段中。
这是一个简单的例子。
富 class :
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Foo {
static final Logger LOGGER = LoggerFactory.getLogger(Foo .class);
public void doThat() {
logger.info("start");
//...
logger.info("finish");
}
}
FooTest class :
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
public class FooTest {
@Test
void doThat() throws Exception {
// get Logback Logger
Logger fooLogger = (Logger) LoggerFactory.getLogger(Foo.class);
// create and start a ListAppender
ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
// add the appender to the logger
fooLogger.addAppender(listAppender);
// call method under test
Foo foo = new Foo();
foo.doThat();
// JUnit assertions
List<ILoggingEvent> logsList = listAppender.list;
assertEquals("start", logsList.get(0)
.getMessage());
assertEquals(Level.INFO, logsList.get(0)
.getLevel());
assertEquals("finish", logsList.get(1)
.getMessage());
assertEquals(Level.INFO, logsList.get(1)
.getLevel());
}
}
您还可以使用 Matcher/assertion 库作为 AssertJ 或 Hamcrest。
对于 AssertJ 它将是:
import org.assertj.core.api.Assertions;
Assertions.assertThat(listAppender.list)
.extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getLevel)
.containsExactly(Tuple.tuple("start", Level.INFO), Tuple.tuple("finish", Level.INFO));
尽管创建自定义 logback appender 是一个很好的解决方案,但这只是第一步,您最终会使用 developing/reinventing slf4j-test, and if you go a bit further: spf4j-slf4j-test 或其他我还不知道的框架。
您最终需要担心在内存中保留了多少事件、在记录错误(但未断言)时单元测试失败、在测试失败时提供调试日志等...
免责声明:我是 spf4j-slf4j-test 的作者,我编写这个后端是为了能够更好地测试 spf4j,这是查看如何使用 spf4j- 示例的好地方slf4j-测试。我取得的主要优势之一是减少了我的构建输出(Travis 的限制),同时在发生故障时仍然拥有我需要的所有细节。
一个简单的解决方案可能是使用 Mockito 模拟 appender(例如)
MyClass.java
@Slf4j
class MyClass {
public void doSomething() {
log.info("I'm on it!");
}
}
MyClassTest.java
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock private Appender<ILoggingEvent> mockAppender;
private MyClass sut = new MyClass();
@Before
public void setUp() {
Logger logger = (Logger) LoggerFactory.getLogger(MyClass.class.getName());
logger.addAppender(mockAppender);
}
@Test
public void shouldLogInCaseOfError() {
sut.doSomething();
verify(mockAppender).doAppend(ArgumentMatchers.argThat(argument -> {
assertThat(argument.getMessage(), containsString("I'm on it!"));
assertThat(argument.getLevel(), is(Level.INFO));
return true;
}));
}
}
注意:我使用的是断言而不是 returning false
,因为它使代码和(可能的)错误更易于阅读,但如果您有多个验证,它将不起作用。在这种情况下,您需要 return boolean
指示值是否符合预期。
我会推荐一个简单、可重用的间谍实现,它可以作为 JUnit 规则包含在测试中:
public final class LogSpy extends ExternalResource {
private Logger logger;
private ListAppender<ILoggingEvent> appender;
@Override
protected void before() {
appender = new ListAppender<>();
logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); // cast from facade (SLF4J) to implementation class (logback)
logger.addAppender(appender);
appender.start();
}
@Override
protected void after() {
logger.detachAppender(appender);
}
public List<ILoggingEvent> getEvents() {
if (appender == null) {
throw new UnexpectedTestError("LogSpy needs to be annotated with @Rule");
}
return appender.list;
}
}
在您的测试中,您将通过以下方式激活间谍:
@Rule
public LogSpy log = new LogSpy();
调用 log.getEvents()
(或其他自定义方法)来检查记录的事件。
使用 JUnit5 + AssertJ
private ListAppender<ILoggingEvent> logWatcher;
@BeforeEach
void setup() {
this.logWatcher = new ListAppender<>();
this.logWatcher.start();
((Logger) LoggerFactory.getLogger(MyClass.class)).addAppender(this.logWatcher);
}
@Test
void myMethod_logs2Messages() {
...
int logSize = logWatcher.list.size();
assertThat(logWatcher.list.get(logSize - 2).getFormattedMessage()).contains("EXPECTED MSG 1");
assertThat(logWatcher.list.get(logSize - 1).getFormattedMessage()).contains("EXPECTED MSG 2");
}
归功于:@davidxxx 的回答。查看 import ch.qos.logback...
详细信息:
这是一种使用 lambda 的替代方法,它使日志捕获逻辑可在测试中重用(封装其实现)并且不需要 @BeforeEach
/@AfterEach
(在某些建议的解决方案中,appender未分离,这可能导致内存泄漏)。
被测代码:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyService {
private static final Logger LOG = LoggerFactory.getLogger(MyService.class);
public void doSomething(String someInput) {
...
LOG.info("processing request with input {}", someInput);
...
}
}
拦截器助手:
package mypackage.util
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.slf4j.LoggerFactory;
import java.util.List;
public class LogInterceptor {
public static List<ILoggingEvent> interceptLogs(Class<?> klass, Runnable runnable) {
final Logger logger = (Logger) LoggerFactory.getLogger(klass);
final ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
logger.addAppender(listAppender);
try {
runnable.run();
return listAppender.list;
} finally {
logger.detachAppender(listAppender);
}
}
}
测试套件:
import static mypackage.util.LogInterceptor.interceptLogs;
public class MyServiceTest {
private MyService myService;
...
@Test
void doSomethingLogsLineWithTheGivenInput() {
List<ILoggingEvent> logs = interceptLogs(
myService.getClass(),
() -> myService.doSomething("foo")
);
assertThat(logs).isNotEmpty();
ILoggingEvent logEntry = logs.get(0);
assertThat(logEntry.getFormattedMessage()).isEqualTo("Processing request with input foo");
assertThat(logEntry.getLevel()).isEqualTo(Level.INFO);
}
}