Tuesday, July 9, 2013

How to use log4j without log4j.properties file

Usually when using log4j for logging log4j.properties file is used to configure log4j properties. But sometimes you may need to change these properties by your code. This tutorial simply show you how to set log4j properties through java code.
Download log4j-1.2.17.jar from Apache website and add it to your project.
Create a new java class and name it as LoggerTest. Create another java class and name it as LoggerUtil. Add following method to your LoggerUtil class so you don't need to have a log4j.properties file.

public static void initLogger() {
    try {
      String filePath = "D:/mylog.log";
      PatternLayout layout = new PatternLayout("%-5p %d %m%n");
      RollingFileAppender appender = new RollingFileAppender(layout, filePath);
      appender.setName("myFirstLog");
      appender.setMaxFileSize("1MB");
      appender.activateOptions();
      Logger.getRootLogger().addAppender(appender);
    } catch (IOException e) {
      e.printStackTrace();
    }
}

Explaining the method:
✪  First we define the log file path.
✪  Then we create a PatternLayout object by passing the pattern of the log entry.
✪  Note that here are using a RollingFileAppender. RollingFileAppender automatically rename the log files
    when they reach a certain size and create a new log file. By default it create a new log file when
    the current log file come to the size of 10MB. You can change this size by using one of
    appender.setMaximumFileSize() or appender.setMaxFileSize() methods.
✪  activateOptions() is an internal method and which throws an exception or give you warnings if it
    couldn't execute this methods correctly, for an example if file name is not set.
✪  Finally we append the appender to Root Logger.

Note that within the application running time you need to call this method only once.

We have almost finished our work. Now add a main method to your LoggerTest class as below and run it.
  public static void main(String[] args) {
    //calling initLogger() method to initialize properties. 
    //You need to call this method only once.
    LoggerUtil.initLogger(); 
    
    //Getting the already registered logger 'myFirstLog'
    Logger accessLog = Logger.getLogger("myFirstLog");
 
    accessLog.info("This is my first info message.");
    accessLog.warn("This is my first warn message.");
    accessLog.error("This is my first error message.");
    accessLog.fatal("This is my first fatal message.");
  }

Now open the log file(D:/mylog.log) and you will see the output.

10 comments:

  1. how can you add date to the end of the log file if the date falls to the next date.

    ReplyDelete
  2. so much for thanks in advance its been almost a year and still no reply

    ReplyDelete
  3. Pleasant Tips..Thanks for Sharing….We keep up hands on approach at work and in the workplace, keeping our business pragmatic, which recommends we can help you with your tree clearing and pruning in an invaluable and fit way.
    python training institute in marathahalli
    python training institute in btm
    Python training course in Chennai

    ReplyDelete
  4. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    Data Science training in rajaji nagar
    Data Science with Python training in chennai
    Data Science training in electronic city
    Data Science training in USA
    Data science training in pune

    ReplyDelete
  5. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. Best Devops Training in pune
    Devops Training in Bangalore
    Microsoft azure training in Bangalore
    Power bi training in Chennai

    ReplyDelete
  6. Thank For Sharing Your Information The Information Shared Is Very Valuable Please Keep Updating Us Time Went On Just Reading The Article Python Online Course

    ReplyDelete