Java Log file tailer (tail -f) in Spring Boot
In this article, we will focus on streaming file changes on a Spring Boot endpoint. You probably used the tail -f command to follow the changes in a file. We will see the same output from our new endpoint.
The most simple approach is to return the content we read from a file in our endpoint. This feature is already available here in Spring Boot Actuator based on this class.

If we try to compare this situation to some real-life activity: you don’t go to the grocery store to buy one item, go home, leave again, get something else, and so on. You are losing a lot of time on your way to the store.

Streaming the content is a better idea in this situation. We can use Server Sent Events to provide file updates in the first http connection.

There are some key tasks for this flow to work:
- Expose a Text Event Stream endpoint (GET /logs)
- Send updates to the connected clients (StreamService)
- Detect file changes (MonitoringService)
- Read new lines (MonitoringService)

Text Event Stream endpoint
You can find different articles on how to achieve this here or here. Long story short, depending on the spring boot flavor you use, in the spring-mvc context, you have to use a SseEmitter to be able to send updates to the calling client.

We can see the browser is waiting for our request to finish due to the Content-Type: text/event-stream header.

The next challenge is to store all the connections in our application. We do this because we want to broadcast all the file changes to all the connected clients.
You can find below a sample class allowing us to register new connections, send messages to a specific topic while removing invalid connections.






