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.
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");
You can create a log4j.xml in the resource folder.
.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%p [%t] %c{1}.%M(%L) | %m%n" />
</layout>
</appender>
<appender name="FILE" class="org.apache.log4j.rolling.RollingFileAppender">
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="fileNamePattern" value="/yourfolder/debug_%d{dd-MM-yy}.log" />
</rollingPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%p [%t] %c{1}.%M(%L) | %m%n" />
</layout>
</appender>
<root>
<level value="WARN" />
<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</root>
</log4j:configuration>
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