我想使用 Scala 监视日志文件。日志的具体问题是您还需要能够考虑日志轮换(这是 Linux tail 的基本功能之一)。
我知道对于纯Java有Tailer ,但我想知道是否有类似的 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 的东西非常强大,所以使用它可能是个好主意!
关于Scala 拖尾文件的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24179203/