Showing posts with label logging. Show all posts
Showing posts with label logging. Show all posts

Tuesday, 23 June 2015

Slf4j with log4j2 Example.

What is slf4j :- The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.Here we are using log4j2 logging framework at deployment time for this we need to add below jars.

Now create java class with slf4j logger object.
Test.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Test {
private static final Logger logger = LoggerFactory.getLogger(Test.class);
public static void main(String[] args) {
               logger.debug("this is debug msg");
               logger.info("this is info mesg");
      
}
}

Now where we have to store logs and which pattern we have to print logs these are all configure in log4j2.xml
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
  <Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
        <PatternLayout pattern="current date-%d LEVEL-%-5p  Thread-[%t]  Method-%M()   Class name-%C   Message-%m%n"/>
    </Console>
  </Appenders>
   <loggers>
  <Logger name="org.apache.log4j.xml" level="all"/>
    <root level="all">
      <appender-ref ref="STDOUT"/>
    </root>
  </loggers>
</Configuration>


Note: the configuration file log4j2.xml put in class path means under src folder.

How to Create a Custom Appender in log4j2?


In log4j2, you would create a plugin for create custom appender in log4j2.
When you annotate your custom Appender class with @Plugin(name=”MyCustomAppender”, category=”core” elementType=”appender” ,printObject=true) the plugin name becomes the configuration element name, so a configuration with your custom appender would then look like this:


Log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" packages="com.madhu.appender">
    <Appenders>
        <MyCustomAppender name="myapp" >
       <PatternLayout pattern="serial no: %sn |  Date: %d |  level:%level | class name:%logger | method name:%M() |  line number:%L |  Location: %l | message:%m%n" />
        </MyCustomAppender>
    </Appenders>
       <Loggers>
              <Root level="all" additivity="false">
                     <AppenderRef ref="myapp" />

              </Root>
       </Loggers>
</Configuration>

In log4j2.xml file don’t forgot packages attribute here configure your custom appender package.
Now we are create plugin for appender.

MyCustomImpl.java


@Plugin(name="MyCustomAppender", category="Core", elementType="appender", printObject=true)

public class MyCustomImpl extends AbstractAppender {

    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private final Lock readLock = rwLock.readLock();

    protected MyCustomImpl(String name, Filter filter,
            Layout<? extends Serializable> layout, final boolean ignoreExceptions) {
        super(name, filter, layout, ignoreExceptions);
    }
    @PluginFactory
    public static MyCustomImpl createAppender(
            @PluginAttribute("name") String name,
            @PluginElement("Layout") Layout<? extends Serializable> layout,
            @PluginElement("Filter") final Filter filter,
            @PluginAttribute("otherAttribute") String otherAttribute) {
        if (name == null) {
            LOGGER.error("No name provided for MyCustomAppenderImp");
            return null;
        }
        if (layout == null) {
            layout = PatternLayout.createDefaultLayout();
        }
        return new MyCustomImpl(name, filter, layout, true);

}
       @Override
       public void append(LogEvent event) {
                readLock.lock();
               try {    
                   final byte[] bytes = getLayout().toByteArray(event);
// here I am printing logs into console
                   System.out.println("LOG: " +new String(bytes, "UTF-8"));
               } catch (Exception ex) {
                   if (!ignoreExceptions()) {
                       throw new AppenderLoggingException(ex);
                   }
               } finally {
                   readLock.unlock();
               }
       }
}

Now we can test our custom appender. For this we can write one test class.

Note: Here custom appender plugin name and configuration appender name is same otherwise its won’t work.

Test.java


public class Test {
       public static final Logger LOGGER=LogManager.getLogger(Test.class);
public static void main(String[] args) throws IOException {
       LOGGER.info("this is info message");
       LOGGER.warn("this is warning message");
      
}
}

The output comes like below.

LOG: serial no: 1 |  Date: 2015-06-23 15:32:56,069 |  level:INFO | class name:com.madhu.appender.Test | method name:main() |  line number:15 |  Location: com.madhu.appender.Test.main(Test.java:15) | message:this is info message

LOG: serial no: 2 |  Date: 2015-06-23 15:32:56,072 |  level:WARN | class name:com.madhu.appender.Test | method name:main() |  line number:16 |  Location: com.madhu.appender.Test.main(Test.java:16) | message:this is warning message










Monday, 22 June 2015

Create Custom Pattern using log4j2 in java.

Log4j2 custom pattern example in java .

1. Create custom pattern, first we need to create plugin. For example I need to print TransactionLogId in logs.



TransactionLogIdConverter.java


@Plugin(name="TransactionIdConverter", category = "Converter")
@ConverterKeys({"trnLogid","trscId"})
public class TransactionLogIdConverter extends LogEventPatternConverter{
    protected TransactionLogIdConverter(String name, String style) {
        super(name, style);
    }

    public static TransactionLogIdConverter newInstance(String[] options) {
        return new TransactionLogIdConverter("trnLogid",Thread.currentThread().getName());
    }

    @Override
    public void format(LogEvent event, StringBuilder toAppendTo) {
        toAppendTo.append(getTransactionId());
       
    }

    protected String getTransactionId() {
      
       String transacationId = TransactionLogIdGenerator.myTransactionId();
      
        return transacationId;
    }

}


2. Next create TransactionIdGenerator.java class for generating TransactionLogId.

TransactionIdGenerator.java


public class TransactionLogIdGenerator {

       public static String  myTransactionId(){
              return "1234-5678-0123";
             
       }
   }

3. Now we need add custom pattern in log4j.xml file using  %trnLogid. And we have to add custom pattern plugin package name in log4j2.xml file in configuration element.

      log4j2.xml

      <?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns="http://logging.apache.org/log4j/2.0/config"
       status="OFF" packages="com.custom.pattern">
       <Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
     <PatternLayout pattern="  Date:-%d  TransactionLogID:- %trnLogid   line Number:-%L  Location:-%l   classNmae: %C  Message:-%m%n"/>
   
    </Console>
  </Appenders>
  <loggers>
              <Logger name="org.apache.log4j.xml" level="all" />
              <root level="all">
                     <appender-ref ref="STDOUT" level="TRACE" />
                     </root>
  </loggers>
</configuration>

  For testing log4j2 custom pattern we have to create one Test.java class.


Test.java

public class Test {
        private static final Logger logger = LogManager.getLogger(Test.class);   
       public static void myTest(){
              logger.info("this is my info message");
              logger.debug("This is debug message");
             
       }
       public static void main(String[] args) {
              myTest();
       }

}


The output comes like below.

Date:-2015-06-22 16:26:50,612  TransactionLogID:- 1234-5678-0123   line Number:-12  Location:-com.custom.test.Test.myTest(Test.java:12)   classNmae: com.custom.test.Test  Message:-this is my info message

Date:-2015-06-22 16:26:50,616  TransactionLogID:- 1234-5678-0123   line Number:-13  Location:-com.custom.test.Test.myTest(Test.java:13)   classNmae: com.custom.test.Test  Message:-This is debug message