Log File Tail Reader
Difficulty: Medium · Topics: File IO, Streaming, Real-time
Difficulty: Medium | Tags: File IO, Streaming, Real-time
Description
Implement a utility that continuously reads new lines appended to a log file in real-time, similar to tail -f in Unix. It should start reading from the end of the file and emit new lines as they are written.
Implement:
LogTailer
tail(filePath, callback) — start tailing, invoke callback per new line
tail(filePath, numLines) → String[] — return last N lines from file
stop() — stop tailing
Examples
Example 1 — Last N lines:
Input: file content = "line1\nline2\nline3\nline4\nline5"
numLines = 3
Output: ["line3", "line4", "line5"]
Example 2 — Live tailing:
tailer = new LogTailer()
tailer.tail("/var/log/app.log", (line) => {
print("[NEW] " + line)
})
// As another process writes to app.log:
// [NEW] 2026-02-19 14:20:00 INFO Request received
// [NEW] 2026-02-19 14:20:01 ERROR Connection timeout
Example 3 — File doesn't exist yet:
tailer.tail("/var/log/new.log", callback)
// Waits until the file is created, then starts tailing
Constraints
- Must handle log rotation (file truncated/replaced).
- Must handle files that don't exist yet (wait and watch).
- Memory-efficient: don't load entire file into memory.
- For
tail(filePath, numLines): read from the end of file, not from start. - Must clean up file handles on
stop().
Hints
Hint 1
For last-N-lines: use RandomAccessFile, seek to end, then read backwards until you find N newlines.
Hint 2
For live tailing: poll the file length periodically. When it grows, read the new bytes.
---
## API