2

I have a file /files/somelog.log that is continuously written to by some other process. What I want to do is to read that file as a (never-ending) stream and respond to it whenever there is a new log line available.

val logStream: Stream[String] = readAsStream("/files/somelog.log")
logStream.foreach { line: String => println(line) }

So, immediately when the other process writes anther line to the logfile, I expect the println above to go off (and keep going off).

However, that doesn't seem to be how the default Stream-type works. Scala's Stream isn't async, it's just lazy. What I'm probably looking for is something similar to what akka streams offers (I think). But Akka is so huge (150MB!) - I don't want to pull in so many new things that I don't need just to do something this simple/basic. Is there really no other (tiny!) library or technique I can use?

1

2 Answers 2

2

If you simply want to tail the file you could use Tailer from Apache Commons IO:

val l = new TailerListenerAdapter() {
    override def handle(line: String): Unit = println(line)
}

val tail = Tailer.create(new File("file.txt"), l)
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not actually recommending this, but you could roll your own.

def nextLine( itr: Iterator[String] ): String = {
  while (!itr.hasNext) Thread.sleep(2000)
  itr.next
}
. . .
val log = io.Source.fromFile("/files/somelog.log").getLines
val logTxt = nextLine( log )  // will block until next line is available
. . .

10 Comments

doesn't look very async to me
Not being async isn't the biggest problem with it. It actually doesn't work at all: once EOF is reached, the file is closed, and hasNext will never return true again.
It's an interesting suggestion. Too bad it won't work ^. You could always async'ify it manually by putting it in its own thread.
@Dima, whadyameanitdosntwork?? All my test results are exactly as desired. It throws an error if the log file doesn't exist, but a more complete implementation would cover that. Try it. hasNext returns true after the next line is written to the log. [Wow, harsh audience.]
@kornfridge, exactly! You can async'ify as desired.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.