So I'm trying to set up log4j in my scala code. This is what I have so far:
LogHelper.scala
package myPackage
import org.apache.log4j.Logger
trait LogHelper {
val loggerName: String = this.getClass.getName
lazy val logger: Logger = Logger.getLogger(loggerName)
}
my class
package myPackage
class MyClass extends LogHelper {
...
logger.debug("my message")
...
}
But I don't really know where the logs go, or how to make it print to a file. My code is running a spark job which I run with spark-submit. How do I set this up to print to both the console and a log file?
Refer to this post. They have precise steps to get logging in Scala.
http://discuss.itversity.com/t/setting-up-log4j/5839:
Step 1: Update build.sbt with below log4j dependency
libraryDependencies += "log4j" % "log4j" % "1.2.14"
step 2: create Log4j.properties file under src/main/resources and update as follows:
# Define the root logger with appender file
log = /tmp/log4j
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
SBT run, can be seen in /tmp/log4j/log.out log
Step 3: Can be used in code as follows:
import org.apache.log4j.Logger
object HelloWorld {
val logger = Logger.getLogger(this.getClass.getName)
def main(args: Array[String]): Unit = {
logger.info("Logger : Welcome to log4j")
}
}
If you wanna know more about logging with log4j, I recommend this post on DZone:
https://dzone.com/articles/logging-with-log4j-in-java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With