org.slf4j.Logger logs to console, how do I log to file?
java, log4j, logging, slf4j
Solution
The simplest way, I think, is to define a `FileAppender` in a log4j.properties file:
# Define the file appender
log4j.appender.FileAppender=org.apache.log4j.RollingFileAppender
log4j.appender.FileAppender.File=[log filename].log
log4j.appender.FileAppender.layout = org.apache.log4j.PatternLayout
log4j.appender.FileAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# Direct all messages there
log4j.rootLogger = INFO, FileAppender
Just replace `[log filename]` with some relevant filename. I think Log4j is able to automatically locate the file when you run the project from Eclipse if the file is in your project directory, but I'm not 100% sure. You can use `PropertyConfigurator` at the start of your application to tell Log4j where to find the properties file, e.g.:
PropertyConfigurator.configure("log4j.properties");
Problem
I am using the org.slf4j.Logger to log output. Output is going to console. How do I get logging logged to a log file? ``` private static final Logger LOG = LoggerFactory.getLogger(ClassName.class ); LOG.info("Logging output to console"); ``` I am not using a log4j.properties file. I am assuming I will need one. I added the following log4j.properties file and placed it in different parts of my eclipse project. ``` # Define the file appender log4j.appender.FileAppender=org.apache.log4j.RollingFileAppender log4j.appender.FileAppender.File=logger.log log4j.appender.FileAppender.layout = org.apache.log4j.PatternLayout log4j.appender.FileAppender.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n # Direct all messages there log4j.rootLogger = INFO, FileAppender ``` I even used ``` PropertyConfigurator.configure("log4j.properties"); ``` But no logging file appears. log4j.properties doesn't seem to have an effect.