2017-07-31 949 views
0

是否有辦法使用scala日誌記錄將控制檯輸出導向日誌文件。在下面的代碼中,println向控制檯寫入數據可以通過定義的logback.xml將其定向到日誌文件。Scala日誌記錄,將控制檯輸出直接輸出到日誌文件

import com.typesafe.scalalogging.LazyLogging 

object FileProcessing extends LazyLogging { 

    def main(args: Array[String]): Unit = { 
    val fp = new FileProcessing 
    logger.info(fp.fileMoves.toString()) 
    println("My desired directory is - "+fp.dir) 
    } 
} 

使用下面的Scala登錄我的build.gradle

compile "ch.qos.logback:logback-classic:1.1.7" 
compile "com.typesafe.scala-logging:scala-logging_2.12:3.5.0" 
+0

您需要修改您的記錄器配置文件以包含文件輸出 – puhlen

回答

1

println寫入Console.out。你可以給它任何你想要的流。例如:

Console.withOut(new PrintStream(new FileOutputStream("/dev/null"))) { 
    println("this will not be printed anywhere") 
} 
Console.withOut(new PrintStream(new FileOutputStream("console.txt"))) { 
    println("this is printed to console.txt") 
} 
println("This still goes to stdout") 

你也可以用全局(不推薦)Console.setOut改變輸出流,但這不是一個真正的好主意(就像任何其他的想法,包括不斷變化的全球JVM狀態在運行時)。在這種情況下,在命令行上使用> console.txt運行程序會更好。

請注意,如果其他人(除了println/Console也寫入同一個文件),由於緩衝和賽車,你得到的結果可能不會是你喜歡的。