Home > Uncategorized > How to implement log4j in java code itself without using log4j.properties

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

  1. Creating a logger and appender. Add appender to logger.
  2. Set the LEVEL if you want
  3. Define log message layout.
  4. 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.”);
Amit Gupta

Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

Categories: Uncategorized Tags: , , , , , ,
  1. March 12th, 2011 at 05:32 | #1

    Download log4j.jar first.
    Then write the below line in your code

    import org.apache.log4j.*;

  2. Aniket
    March 11th, 2011 at 06:47 | #2

    Hi Which JAR do we have to import for using Logger?