
# Captured logs

`captureLogs` records what is logged through `SpringLog` during each test, so a test can check that code warns or logs an error instead of throwing. In a test class, a `@CapturedOutput()` field does the same.

## Why

Some behaviour is only visible in the log: a warning about a slow payment, an error that is handled and logged instead of thrown. Checking it keeps such code from silently changing.

## Example

```dart
void main() {
  final logs = captureLogs(level: SpringLogLevel.debug); // once, outside the tests
  final app = springBootTest(springApplication);

  test('warns about slow payments', () {
    app.getBean<Checkout>().pay(slowOrder);
    expect(logs.messages, contains('slow payment'));
    expect(logs.atLevel(SpringLogLevel.warning), hasLength(1));
    expect(logs.ofLogger('neon.checkout'), isNotEmpty); // and its child loggers
  });
}
```

```dart
@SpringBootTest()
class CheckoutLogTest {
  @CapturedOutput()
  late CapturedLogs logs;                      // emptied before every test

  @Autowired()
  late Checkout checkout;

  @Test()
  void payingIsLogged() {
    checkout.pay(3);
    expect(logs.messages, contains('paid 3.0'));
  }
}
```

## CapturedLogs

| Member | Gives |
|---|---|
| `records` | The `SpringLogRecord`s, with level, logger, message, fields and error |
| `messages` | The messages |
| `text` | One `LEVEL [logger] message` line per record |
| `atLevel(level)` | The records of exactly that level (warnings do not include errors) |
| `ofLogger(name)` | The records of that logger and the loggers below it |

- Every test starts with an empty capture.
- Records are captured after the loggers' own levels filtered them.
- `level` sets `SpringLog.level` during each test and puts the old level back afterwards.
- Call `captureLogs` once in `main` or a `group`, outside the tests.

## app.output

`app.output` is something else: the lines the application printed, such as the failure report of a context that did not start, or the banner when it is on. Each line is also shown when a test fails. The startup information is logged, not printed, so it is in the captured logs, not in `output`.

## In Spring (Java)

Spring Boot's `OutputCaptureExtension` captures everything the process prints. `captureLogs` captures `SpringLog` records only, with their levels and loggers, so assertions do not parse text.

## See also

- [springBootTest](spring-boot-test.md)
- [spring_boot_starter_logging](../spring-boot-starter-logging/index.md)
- [SpringLog](../spring-core-dart/logging/spring-log.md)
