Thursday, September 15, 2016

Reading log file path from environment Variable in logback

In this short blog i will be showing how to read the log folder location from environment variable.

In general log path for an application is one time configuration. So why to keep multiple property files for each environments. Better approach could be using environment variable on server, which can be configured once.

Here i am using Tomcat 7.x as a server. For Logback using following jars.

  • logback-classic-1.1.3.jar
  • logback-core-1.1.3.jar

First lets start by creating environment variable in tomcat server. For this you need to open context.xml file located at TOMCAT_HOME/conf folder. Open with text editor and add following line in the file.

  <Environment name="LOG_PATH" type="java.lang.String" value="/logs"/>

you are done with creation of environment variable which will be accessible via jndi lookup.

next will be open logback.xml file which contains application logging configurations.

Use JNDI lookup to retrieve the environment variable. Logback provides a tag "insertFromJNDI" which has attributes like "env-entry-name" and "as".

"env-entry-name" - in this attribute, jndi lookup path needs to be mentioned. e.g.

env-entry-name="java:comp/env/LOG_PATH"

"as" - in this attribute,variable will be created where the value returned from lookup will be stored.

<insertFromJNDI env-entry-name="java:comp/env/LOG_PATH" as="LOG_PATH" />

 Assign this variable to Context and then access it via "${CONTEXT_NAME}". shown below.

<contextName>${LOG_PATH}</contextName>

Complete configuration code is given below.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<configuration>
 <insertFromJNDI env-entry-name="java:comp/env/LOG_PATH" as="LOG_PATH" />
   <contextName>${LOG_PATH}</contextName>
 <appender name="SAMPLE-DEBUG"
  class="ch.qos.logback.core.rolling.RollingFileAppender">
  <file>${CONTEXT_NAME}/debug.log</file>
  <filter class="ch.qos.logback.classic.filter.LevelFilter">
   <level>debug</level>
   <onMatch>ACCEPT</onMatch>
   <onMismatch>DENY</onMismatch>
  </filter>
  <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
   <Pattern>
    %d{yyyy-dd-MM HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
   </Pattern>
  </encoder>
  <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
   <fileNamePattern>${CONTEXT_NAME}/archived/debug.%d{yyyy-dd-MM}.%i.log</fileNamePattern>
   <timeBasedFileNamingAndTriggeringPolicy
    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
    <maxFileSize>2MB</maxFileSize>
   </timeBasedFileNamingAndTriggeringPolicy>
  </rollingPolicy>
 </appender>
 <root level="DEBUG">
  <appender-ref ref="SAMPLE-DEBUG"  />
 </root>
</configuration>

share your feedback. 

No comments:

Post a Comment

Components of Big Data - Hadoop System

In this blog i will explain important components which are part of Hadoop System. I will give very brief overview of these components. Be...