Reputation: 309
public class MyUtil {
public static boolean showLogging;
public static boolean saveLogging;
public static void log(Object s) {
if (showLogging) {
// show logging on console
}
if (saveLogging) {
// save logging to file and append logging old file when it is created
}
}
}
This is my current idea. I heard of log4j but it's too complicate for me.
So I just want something that's simple to print logging on console and also write it to a file based on user configuration.
Upvotes: 0
Views: 1972
Reputation: 1741
Use log4j
First define the log4j.xml which defines both console and file appender as follows:
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="CA" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
</layout>
</appender>
<appender name="Daily" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="logs/sample.log" />
<param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] - %m%n%n%n" />
</layout>
</appender>
<root>
<appender-ref ref="CA" />
<appender-ref ref="Daily" />
</root>
</log4j:configuration>
Put this xml file in the classpath ... also keep log4j in the classpath
A sample code is:
package com.vanilla.helloworld;
import org.apache.log4j.*;
public class HelloWorld
{
static final Logger logger = Logger.getLogger(HelloWorld.class);
public static void main(String[] args) throws InterruptedException
{
logger.info("I am going to log to file as well as console");
}
}
Upvotes: 0
Reputation: 1793
Use a logging framework, such as the one that comes in the JDK, and configure it to log to both places. They solve these problems for you.
Due to the prevalence of frameworks like log4j, most people standardize on that and use the same logging framework so all things go to the same place. (i.e., they use a third party library which is already using log4j).
Here is something you might want to read to get a handle on how these frameworks work (most are similar): http://logging.apache.org/log4j/1.2/manual.html
Scroll down a bit in this document to see some real-world examples
Upvotes: 1