How to implement log4j in java code itself without using log4j.properties
January 12th, 2011
613 views
Leave a comment
Go to comments
If you are not willing to use log4j configuration file ie log4j.properties then you will have to define a java class to set all properties in your code itself.
STEPS
- Creating a logger and appender. Add appender to logger.
- Set the LEVEL if you want
- Define log message layout.
- Don’t forget to attach log file path where you have to write your messages.
Sample code: Copy and paste below sample class somewhere in your java project.
public class Log
{
public static Logger as_looger;
public Log(){}
static
{
as_looger = Logger.getLogger("articles logging");
// as_looger = Logger.getLogger(Log.class.getName());
FileAppender as_appender = null;
as_appender = new DailyRollingFileAppender(new PatternLayout("%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p: %m%n"), “path of file where to write logs”, "'.'dd-MM-yyyy");
as_looger.setLevel(Level.DEBUG);
as_looger.addAppender(as_appender);
}
}
Since as_looger is declared as static in above example class. So you can use it throughout your java project using class name as follow;
Syntax
< Log class name >.< logger name >.< method denoting a level >(“message”);
Example
Log.as_logger.debug(“article-stack.com has been started.”);

Download log4j.jar first.
Then write the below line in your code
import org.apache.log4j.*;
Hi Which JAR do we have to import for using Logger?