Log4j2 provides more control over logging.
Here i am going to provide a sample log4j2 xml that i used in my application.
----Sample log4j2.xml
<?xml version="1.0"
encoding="UTF-8"?>
<Configuration name="dss-config"
monitorInterval="60" packages="com.test">
<!-- Specifying the attribute
status="DEBUG" in configuration tag will print the all the statements
within the application log event. -->
<Properties>
<Property name="LOG_DIR">/logs/appName/applogs</Property>
<Property name="ARCHIVE">${LOG_DIR}/archive</Property>
<!-- %t - thread name; %d - date format
specifier;
M - output the method name where the
logging request is issued;
L - output the line number from where
the logging request is issued;
m - used to display the application
supplied message;
c - Used to output the category of the
logging event (class).
The
category conversion specifier can be optionally followed by precision
specifier, that is a decimal constant in brackets.
For
example, for the category name "a.b.c" the pattern %c{2} will output
"b.c".;
n - Outputs the platform dependent line
separator character or characters.This conversion character offers practically
the
same
performance as using non-portable line separator strings such as
"\n", or "\r\n".;
-5level - info / warn / error / etc...
-->
<!--Below pattern is not used as it is
more of default pattern
<Property
name="PATTERN1">%d{yyyy-mm-dd HH:mm:ss.SSS} %-5level [%t]
%c:%M(%L): %m%n</Property>
-->
<Property name="PATTERN">%d{yyyy-mm-dd
HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Property>
<property name="receipients">yourname@domainemail.com</property>
<property name="fromAddress">applicationHostName.com</property>
<property name="smtpHostName">localhost</property>
<property name="logfileName">appLogfileName.log</property>
<property name="errSubject">Application threw an exception- LOG4J error notification email. - ${sys:hostName}</property>
<!-- <property
name="smtpPortNum">25</property> -->
<property name="ErrorOnlyFileName">appErrorsOnly.log</property>
</Properties>
<Appenders>
<Console name="Console"
target="SYSTEM_OUT">
<PatternLayout pattern="${PATTERN}"/>
</Console>
<RollingFile name="fileWriter"
fileName="${LOG_DIR}/${logfileName}"
filePattern="${ARCHIVE}/${logfileName}.%d{yyyy-MM-dd-hh-mm-ss}-%i.gz">
<PatternLayout pattern="${PATTERN}"/>
<Policies>
<!-- interval an
integer : How often a rollover should occur based on the most specific time
unit in the date pattern. For example, with a date pattern with hours as the
most specific item and and increment of 4 rollovers would occur every 4 hours.
The default value is 1.
modulate a boolean :
indicates whether the interval should be adjusted to cause the next rollover to
occur on the interval boundary. For example, if the item is hours, the current
hour is 3 am and the interval is 4 then then the first rollover will occur at 4
am and then next ones will occur at 8 am, noon, 4pm, etc.-->
<!--<TimeBasedTriggeringPolicy
interval="24" modulate="true"/> -->
<SizeBasedTriggeringPolicy size="2MB"
/>
</Policies>
</RollingFile>
<File name="ErrorOnlyLogfile"
fileName="${LOG_DIR}/${ErrorOnlyFileName}">
<PatternLayout pattern="${PATTERN}"/>
</File>
<!-- attribute for smtp; bufferSize="512" is the default
value
smtpProtocol = "smtp" is the
default value -->
<smtp name="smtpMailer"
subject="${errSubject}" to="${receipients}" smtpDebug="true"
from="${fromAddress}" smtpHost="${smtpHostName}" bufferSize="5">
<!-- default is htmllayout
<PatternLayout>
<pattern>%d{dd-MM-yyyy
HH:mm:ss,SSS} %5p %m%n</pattern>
</PatternLayout> -->
</smtp>
</Appenders>
<Loggers>
<!-- This root default logger will have
a level which will send to the appenderref based on the priority
the appender ref level attribute will be as
a specific filter which prints only that necessary information in the file if
needed-->
<Root level="info">
<!-- <AppenderRef
ref="fileWriter"/> -->
<!-- <AppenderRef
ref="smtpMailer"/> -->
<!-- <appender-ref
ref="Console" level="debug"/> -->
<!--
<appender-ref ref="MyFile" level="error"/>
<appender-ref
ref="smtpMailer" level="error"/>
<appender-ref
ref="fileWriter" level="error"/> -->
<AppenderRef ref="ErrorOnlyLogfile"
level="error"/>
<AppenderRef ref="fileWriter"
level="info"/>
<!-- if the below code is commented, then the detail logging information will not be displayed in the console. -->
<AppenderRef ref="Console"/>
<!-- smtp port not enabled in local
host, so can be commented in windows. should be enabled in linux> -->
<!--<AppenderRef
ref="smtpMailer"
level="error"/>
-->
</Root>
<!-- Application uses Struts + spring + hibernate below logger will enable the hibernate query logs into the console in console if Appender ref is enabled. -->
<Logger name="org.hibernate"
level="debug"/>
<Logger name="org.hibernate.SQL"
level="debug"/>
<Logger name="org.hibernate.type.descriptor.sql"
level="trace"/>
<!-- <logger
name="com.test" level="error"
additivity="true">
<appender-ref
ref="smtpMailer" />
<appender-ref
ref="fileWriter" />
<appender-ref
ref="smtpMailer" level="error"/>
</logger> -->
<!-- <Logger
name="com.boeing.dss" level="TRACE"
additivity="false">
<appender-ref
ref="fileWriter" level="info"/>
<appender-ref
ref="Mail" level="ERROR"/>
</Logger>
-->
</Loggers>
</Configuration>
The above log4j2.xml, has enabled the email notification feature.
<Properties> tag is used to define the necessary properties used by the log4j2.
The errSubject property attribute has the email subject that will be used upon any error logged by the log4j2. if the application is coded with log.error("some string"), whenever the code executes the log.error it will trigger an email. The subject mail has ${sys:hostName} is a system property which can be used.
In order to configure the Log4j2.xml within the web application, we need to update the web.xml to use the log4j2.xml.
If the log4j2.xml configuration file exists within the application class path the by default the application will recognize it during deployment.
If the log4j2.xml needs to be outside the war or class path, we need to use the web.xml <context-para> tag to register it.
Note: i have placed the log4j2.xml file in tomcat conf directory. using the system variable catalina.base in the path.
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>${catalina.base}/conf/log4j2.xml</param-value>
</context-param>
*** NEED TO VALIDATE - START ***
If we need the host name to be fetched within the java then we need to set the hostname in setenv.sh when including the JAVA_OPTS for tomcat. This will be the JVM parameters
export APP_HOSTNAME=`hostname`
#if the tomcat is in Linux the above will execute the hostname command and set the value to APP_HOSTNAME variable.
in JAVA_OPTS along with other variables like -Xms78m -Xmx1024m we can set the above value as
JAVA_OPTS= .... -Dhostname=${DSS_HOSTNAME}
*** NEED TO VALIDATE - END ***
Standalone code to test the log4j2.xml working from a main class.
Create a simple java project in Eclipse, add the log4j2.xml in the resource folder (created as source folder, to be available within classpath)
Create a class and use the below code
Note: use the above log4j2.xml, just comment below lines which will actually sent email. if you have valid smtp enabled within the machine. you would receive an email if this is not commented.
<appender-ref ref="smtpMailer" level="error"/>
|
package com.test;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public final class LogTestMain {
public static Logger logger = LogManager.getRootLogger();
public static void main(String args[]){
logger.error("This
is an statement for testing the application from psvm block");
}
}
|
There are other concepts within log4j2.xml.