1

Is there way to direct console-output to log file using scala logging. In below code println writes to console is there way to direct that to log-file as defined logback.xml.

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)   
  }
}

Using below scala logging my build.gradle

compile "ch.qos.logback:logback-classic:1.1.7"
compile "com.typesafe.scala-logging:scala-logging_2.12:3.5.0"
Naga
  • 444
  • 2
  • 7
  • 18

1 Answers1

3

println writes to Console.out. You can give it any stream you want. For example:

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")

You can also change the output stream globally with (deprecated) Console.setOut, but this isn't really a good idea (like any other idea, involving changing global JVM state at run time). You are much better off just running your program with > console.txt on command line in that case.

Note, that, if someone else (besides println/Console is also writing to the same file), the results you get aren't probably going to be what you like, because of buffering and racing).

Dima
  • 39,570
  • 6
  • 44
  • 70