2017-07-31 946 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也写入同一个文件),由于缓冲和赛车,你得到的结果可能不会是你喜欢的。