0

I am new to Scala and I am struggling to find out how I can redirect my logs to a file in Scala. This is a simple task in Python but I can't find the relevant documentation for Scala. I am trying to use log4j but I don't mind to use other packages either. All references that I find discuss how to do so through a configuration file but I would like to do this programmatically.

This is what I have found so far and works but I do not know how to add a file. I think FileAppender should solve my problem but I can't find an example how to add it to my logger:

import org.apache.log4j.Logger    
val logger = Logger.getLogger("My Logger")
logger.info("I am a log message")

What I wish to achieve (with some extra details) can be written in Python as follows:

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
handler = logging.FileHandler('output.log')
handler.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("I am a log message")
F Gh
  • 65
  • 8
  • 1
    https://stackoverflow.com/questions/8965946/configuring-log4j-loggers-programmatically – pasha701 Nov 11 '19 at 13:25
  • This is for Java. I am looking for an Scala example. For instance `import org.apache.log4j.{Level, Logger, FileAppender}` does not work. – F Gh Nov 11 '19 at 21:49

1 Answers1

1

Link from comment translated to Scala:

import org.apache.log4j.PatternLayout
import org.apache.log4j.{Level, Logger, FileAppender}
val fa = new FileAppender
fa.setName("FileLogger")
fa.setFile("mylog.log")
fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"))
fa.setThreshold(Level.DEBUG)
fa.setAppend(true)
fa.activateOptions

//add appender to any Logger (here is root)
Logger.getRootLogger.addAppender(fa)

// usage
val logger = Logger.getLogger("My Logger")
logger.info("I am a log message")

If " import org.apache.log4j.{Level, Logger, FileAppender}" is not worked, means, log4j libraries absent in classpath.

pasha701
  • 6,831
  • 1
  • 15
  • 22
  • I get this error: `object FileAppender is not a member of package org.apache.log4j import org.apache.log4j.{Level, Logger, FileAppender}` – F Gh Nov 12 '19 at 19:20
  • Looks like log4j jar file is not present in classpath. – pasha701 Nov 12 '19 at 22:47
  • Actually I can `import org.apache.log4j.{Level, Logger}`. I can't only import `FileAppender`. Not sure why? – F Gh Nov 13 '19 at 23:24
  • maybe, some 'log4j' versions don't contains this class; I can see FileAppender in 'log4j-1.2.17.jar' – pasha701 Nov 14 '19 at 10:34