Scala方式的Tailing文件

时间:2014-06-12 07:56:25

标签: scala

我想使用Scala监控日志文件。日志的具体问题是你需要能够考虑logrotation(这是Linux尾部的基本功能之一)。

我知道纯Java有Tailer,但我想知道是否有类似的Scala实现。

1 个答案:

答案 0 :(得分:4)

从Scala的外观中很容易包装Scala。

object ScalaTailer {
   private val DefaultBufSize = 4096

   def apply(file: File, onFileNotFound: => Unit = (), onFileRotated: => Unit = (),
              handleException: Exception => Unit = (), handleLine: String => Unit = (),
              delayMillis: Long = 1000, end: Boolean = false, reOpen: Boolean = false,
              bufSize: Int = DefaultBufSize) = {
     val listener = new TailerListener {
        override def fileNotFound() = onFileNotFound
        override def fileRotated() = onFileRotated
        override def handle(ex: Exception) = handleException(ex)
        override def handle(line: String) = handeLine(line)
     }
     new Tailer(file, listener, delayMillis, end, reOpen, bufSize)
  }
}

val tailer = ScalaTailer(myFile, handleLine = println)

这可能是没有Scala实现的原因。此外,Apache Commons的东西非常强大,所以使用它可能是一个好主意!