Log4j
Log4j

Introduction to Logger and Log4j

Log information is very important for Software development. It provides very important data for further analysis. Logging is an important aspect of any modern software development. A log generation helps the coders to test their code quickly, helps fast debugging, easy maintenance and understand the code better.

Log statements are better than print statements that give the better status of the project execution.

Popular Logging Frameworks

  • SLF4j
  • Log4j

What needs to be logged in Software Development?

We must be careful what to log in the log file. Unnecessary logs create lots of side effects during a debug process. Logging can be too verbose and cause scrolling blindness. The frequently used log statements are as follows:

  • Any Application start-ups and shutdowns information.
  • Auditing any software
  • Profiling for software
  • Information accumulation
  • Any configuration changes detected.
  • Any application errors or exceptions.
  • Authorization and authentication failures.
  • User input validation.
  • Troubleshooting for application and testing.
  • Identifying application bottleneck.
  • Step info to easy debug.
  • Assert statement to verify internally.
  • Verification data- additional information about bugs.
  • Any other required data- generating statistics.

What is the issue with System.out.println()?

In general, we debug using System.out.println () method. But code printing units have limitations –

  1. The log printed in the console vanished as the console is closed (A single-threaded environment).
  2. The log printed in the console is not stored anywhere. So, we cannot refer to any further point in time.

What not to log via logger?

The below items should not be logged during via logging mechanism.

  • Any personal details like user id and password.
  • Any database connection strings.
  • Any encryption and decryption keys.
  • Any sensitive personal data.
  • Any access token values.
  • Session id, session identification tokens or values.
  • Any source code.

What are the logging best practices we need to follow?

  • Use several files for complex applications and test scenarios.
  • Use logging implementation in a development environment first then to the production environment.
  • Take a balanced approach to log information. (Not too little or not too fat)
  • Generated logs should be human-readable and log parser friendly.
  • The logs information must be well structured,context-based and level-based.
  • Finally, the log message should be meaningful.

Log4j

Log4j is a very quick, most trustworthy and extremely flexible software that is commonly used for efficient logging of events. This framework is built on top of Java and provides several APIs to help users to log the events.

Log4j is having Apache Software licence. Due to its efficiency, this small but powerful software is also used across several other languages like Java, C, C++, Perl, C#, Ruby, Eiffel etc.

Log4j development started in 1996 for Secure Electronic Marketplace for Europe project and it is available here.

Log4j Features

  1. Log4j is threadsafe and optimized for speed.
  2. Log4j is based on named logger hierarchy.
  3. Log4j supports multiple appenders for each logger.
  4. Log4j supports internationalization.
  5. Log4j supports runtime configuration file through which we can set multiple logging events dynamically.
  6. Log4j supports java exceptions.
  7. Log4j supports several levels of logging- ALL,TRACE,DEBUG,INFO,WARN,ERROR,FATAL.
  8. Log4j supports Layout class to change the report format as per our need.
  9. Log4j supports appender interface to change the log writing strategy on the file, network, socket etc.
  10. Log4j is failsafe
  11. Log4j is Open-source
  12. Log4j can redirect logs to files or to database
  13. Log4j Can be used in large and small projects.
Learn log4j from udemy
Learn log4j from udemy

Install Log4j in Unix

To install Log4j in Unix, we need to download the required downloadable from Apache Log4j download page. Then we need to follow the below steps:

  • Download the apache-log4j-x.y.z.tar.gz
  • Unzip the same under /usr/local directory by the command
$gunzip apache-log4j-x.y.z.tar.gz
$tar-xvf apache=log4j-x.y.z.tar
  • During the unzipping process, log4j will create a separate directory as apache-log4j-x.y.z
  • Now in order to make it work, we need to download all the supporting files.
  • Now we need to set up the classpath
$export CLASSPATH=$CLASSPATH: /usr/local/apache-log4j-x.y.z/log4j-x.y.z
$export PATH=$PATH: /usr/local/apache-log4j-x.y.z/

Install Log4j  in Windows

To install Log4j in Windows, we need to download the required downloadable from Apache Log4j download page. Then we need to follow the below steps:

  • Download the zip file from the URL.
  • Unzip to the local folder.
  • Edit the environment variable to add path to the log4j folder. Follow the link to edit path and classpath in windows.

 

Log4j Architecture

Log4j architecture consists of two objects. They are as follows:

  • Core Objects– Mandatory objects for log4j framework.
  • Supporting Objects- Additional and optional objects for log4j framework.

Core Objects or Log4j Building blocks

    • Logger object- Logger object is responsible for logging information or events and report them in the namespace hierarchy. It sends the logging information to Appenders.

Logger by default level is INFO. In case the user does not provide any level, the default INFO will be taken.

Logger Methods

Logger class provides several methods for logging. It provides two basic static methods for getting the logger object. We can not instantiate them using the new keyword.They are as follows:

public static Logger getRootLogger();
public static Logger getLogger(String name);

Apart from these the other methods are as follows:

Method  Meaning
 public void debug(Object message)  prints messages with the level Level.DEBUG
 public void error(Object message)  prints messages with the level Level.ERROR
 public void fatal(Object message)  prints messages with the level Level.FATAL
 public void info(Object message)  prints messages with the level Level.INFO
 public void warn(Object message)  prints messages with the level Level.WARN.
 public void trace(Object message)  prints messages with the level Level.TRACE.
READ  Class TooManyListenersException in java
Concept of Root Logger

Log4j provides a built-in logger called Root logger. Root logger is always applicable and accessible even if it is not explicitly configured.

It is useful when we do not want any specific logger to log a message. The tag, we need to use in this context, is the additivity. If we set additivity=”false”, the particular logger will not report to root.

Logger Hierarchy

Loggers follow inheritance principles. So if a parent logger is set to INFO level, the child loggers created from the parent logger will also have the same level as INFO.

log4j components
log4j components
  • Layout Object-Layout Object is responsible for formatting and makes the log stylish. (make sure they are human-readable).

Layout types

There are several layouts provided by log4j. Layout class is an abstract class, so we can not use this class directly.

Layout Methods

Layout class provides the following methods:

 Layout Methods Description 
 public abstract boolean ignoresThrowable()  Checks if the logging can handle  java.lang.Throwable object. If it is a throwable object, it returns false.
 public abstract String format(LoggingEvent event)  Implements layout subclass specific formatting.

Different Layouts

  • DateLayout-  This put date format into a log.
  • HTMLLayout- This puts logs as HTML table
  • PatternLayout– This puts logs as a pattern defined by the user.
  • SimpleLayout– This puts logs as a simple output format. Prints log level followed by a dash and log message.
  • XMLLayout- This puts logs as XML output.
  • PatternLayout-  Stilify the log as per the pattern provided by the user.

If none of the Layout is specified in the code, the log4j will consider the PatternLayout as default.

Layout Methods

The layout creates an outline for the log. It provides two abstract methods:

 Method Meaning
 public abstract String format(LoggingEvent event)  Individual layout subclasses need to implement this method to format specific things.
 public abstract boolean ignoresThrowable()  talks about the logging setup if they can handle java.lang.Throwable object with the logging event. 

If the Layout object is able to handle the Throwable object, then the Layout object does not ignore it and returns false.

The other methods are as follows:

Method Name  Description 
public String getContentType() The base class returns the default content type but the specific class returns the specific content type used by the Layout object.
public String getFooter() Returns the footer information of the logging message.
public String getHeader() Returns the header information of the logging message.

However, any subclass can return class-specific implementation details.

HTMLLayout

Log4j framework supports several options to format the log file. Log4j can create text log, run log, HTML log. In order to get the logfile directly to HTML file, we need to use org.apache.HTMLLayout class.

Being an abstract class, we cannot use its method format () directly. We need to override for HTML style. HTMLLayout is the common layout we use in the framework. HTMLLayout displays the below information:

  • The actual time elapsed from the start of the application before a particular logging event was generated.
  • The thread name that requested the logging request.
  • Level associated with this logging request.
  • Name of the logger and logging message.
  • The location information for the program file and the line number from which this logging was invoked.

HTMLLayout provides the following methods:

S. No. Method Description
1. setContentType(String) Sets the content type of the text/html HTML content. Default is text/html.
2. setLocationInfo(String) Set the location information for the logging event. Default is false.
3. setTitle(String) Set the title for the HTML file. Default is log4j Log Messages.

HTMLLayout example

# Define the root logger with appender file  
log = /usr/home/log4j  
log4j.rootLogger = DEBUG, FILE  
  
# Define the file appender  
log4j.appender.FILE=org.apache.log4j.FileAppender  
log4j.appender.FILE.File=${log}/htmlLayout.html  
  
# Define the layout for file appender  
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout  
log4j.appender.FILE.layout.Title=HTML Layout Example  
log4j.appender.FILE.layout.LocationInfo=true 

Appender Object-

Appender Object is responsible for publishing logging information to several destinations. The destination can be a file, socket, console etc.

Appenders  types

  • ConsoleAppender- Logs information to standard output or console. The default console is System.out. More. Log4j.ConsoleAppender will print to console.
  • FileAppender– Logs information to files. More
  • RollingFileAppender- It extends FileAppender to the backup log file when they reach their maximum size. More. og4j.following FileAppender will print logs to a file. Log4j.Appender. file. File = File path (like C.//at//logFile.log).
  • AppenderSkeleton– Provides threshold filtering and general filtering. More
  • AsyncAppender– Logs events asynchronously. They use separate threads to put the logs.  More
  • DailyRollingFileAppender– DailyRollingFileAppender is a continuous logging mechanism which keeps rolling over in a predefined frequency. This Appender has synchronization and data loss issue.   More
  • ExternallyRolledFileAppender– This appender sends a log message to a socket and uses an efficient Roller to return the acknowledgement. It is operating system independent, faster and reliable.  More
  • JDBCAppender- This appended is used to send log messages to the database directly. It is not very efficient in terms of getting specific logs. More
  • JMSAppender- This appended pushes logs to as JMS topics. Logs are serialized then transmitted as JMS topics. More
  • LF5Appender- This appended logs events to a swing based console. More
  • NTEventLogAppender-This appended logs events to NT event logging System. More
  • NullAppender- This appended never sends any message. More
  • SMTPAppender-  This appended sends email based on ERROR or FATAL error. More
  • SocketAppender- This appended sends logs to a remote server via SocketNode. More
  • SocketHubAppender– This appended sends logs to a remote server via SocketNode. More
  • SyslogAppender-  This appended sends logs to a Remote Sys deamon. More
  • TelnetAppender-  This appended sends telnet friendly logs to the read-only socket. More
  • WriterAppender- This appended sends logs to an output stream or a writer. More

A logger can have multiple appenders associated with it. This is required to send the logging information to various different destinations.

Appender Hierarchy

Appender also follows inheritance. So if a logger is associated with single or multiple appenders, the child logger derived from the base logger will also have the same appenders associated with it.

Appender Property

The below written appended property can be attached to an appender:

Property Meaning
Layout Layout objects help to make the pattern to format the logging information
target target is responsible to redirect the logs to a console, a file, and I/O streams or a socket
level The level helps in filtering logging information
threshold the threshold level can be independently associated with an appender.
All messages having a level lower than the threshold level are ignored.
filter filters the logging message to put or discarded.

 

FileAppender

The commonly used Appender in FileAppender to write to a File. For this, we need to import org.apache.log4j.FileAppender to our project.

 FileAppender Property Meaning 
 immediateFlush By default this flag is true, it says the output stream will be flushed with every append operation.
 encoding It represents character-encoding. By default, it is the platform-specific encoding scheme.
 threshold It represents the threshold limit of the appender.
 Filename It represents the name of the file where logs will be stored.
 fileAppend By default this flag is true, it says the logger will use the same file to append logging info at the end of the file.
 bufferedIO It represents if the logger needs buffer writing enabled. By default, it is set to false.
 bufferSize If the bufferedIO is enabled, this can be further set. By default it is 8KB

RollingFileAppender- How to write Multiple files?

RollingFileAppender is the second most used appender in our daily life. RollingFileAppender allows us to write logs into multiple files, if the file size reached a predefined threshold. For this, we need to use org.apache.log4j.RollingFileAppender class.

RollingFileAppender uses all properties defined in the FileAppender. Apart from them, there are two properties extra provided by RollingFileAppender. They are as follows:

RollingFileAppender Property  Meaning 
 maxFileSize The file size after that the file will be rolled. Default is 10MB.
 maxBackupIndex This property denotes the number of backup files to be created. The default value is 1.

DailyRollingFileAppender

DailyRollingFileAppender is responsible for taking logs on a daily basis. For this, we have to use org.apache.log4j.DailyRollingFileAppender class.

DailyRollingFileAppender supports all properties of the FileAppender but provides one more. It is as follows:

DailyRollingFileAppender Property  Meaning 
 DatePattern  DatePattern controls the rollover schedule

Several DatePattern

DatePattern controls the rollover using the following patterns

DatePattern  Meaning 
 yyyy-MM  Rolls over monthly at the end of the month.
 yyyy-MM-dd  Rolls over daily at midnight.
 yyyy-MM-dd-a  Rolls over midday and midnight every day.
 yyyy-MM-dd-HH  Rolls over every hour.
 yyyy-MM-dd-HH-mm  Rolls over every minute
 yyyy-ww  Rolls over the first day of every week. It depends on the locale

If we want to set up a DailyRollingAppender with every hour the code will be:

log4j.appender.FILE.DatePattern='.' yyyy-MM-dd-HH

JDBCAppender

JDBCAppender is responsible to push logs directly to the database. For that, we need to use SQL statements. JDBCAppender does not require a pattern but the underlying SQL statement will have pattern statement in which we will be pushing logs.

For this appended, we need to use org.apache.log4j.jdbc.JDBCAppender. The JDBCAppender properties are as follows:

 JDBCAppender Property Meaning 
 bufferSize Talks about the buffer size. Default is 1.
 driver Talks about drivers string. Default is sun.jdbc.odbc.JdbcOdbcDriver.
 layout Specific layout to be used. Default is org.apache.log4j.PatternLayout.
 URL The JDBC url
 sql SQL statement
 password Talks about DB password
 user Talks about DB username

A sample XML with JDBCAppender is given as:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>

<appender name="DB" class="org.apache.log4j.jdbc.JDBCAppender">
   <param name="url" value="jdbc:mysql://hostname/DBNAME"/>
   <param name="driver" value="com.mysql.jdbc.Driver"/>
   <param name="user" value="user_id"/>
   <param name="password" value="password"/>
   <param name="sql" value="INSERT INTO LOGS VALUES('%x','%d','%C','%p','%m')"/>
   
   <layout class="org.apache.log4j.PatternLayout">
   </layout>
</appender>

<logger name="log4j.rootLogger" additivity="false">
   <level value="DEBUG"/>
   <appender-ref ref="DB"/>
</logger>

</log4j:configuration>

Another JDBCAppender configuration file:

JDBC appender:
# Define the root logger with appender file
log4j.rootLogger = DEBUG, DATABASE
# Define the DATABASE appender
log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender
# Set JDBC URL
log4j.appender.DATABASE.URL= jdbc:oracle:thin:@::
# Set Database Driver
log4j.appender.DATABASE.driver=com.oracle.jdbc.Driver
# Set database user name and password
log4j.appender.DATABASE.user=db_user_name
log4j.appender.DATABASE.password=db_password
# Set the SQL statement to be executed.
log4j.appender.DATABASE.sql=INSERT INTO LOGS_REP VALUES('%x','%d','%C','%p','%m')
# Define the layout for file appender
log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout

Support  Objects

  • Level Object- Level Object is responsible for defining the details and priority information. The levels are ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
Level Meaning
OFF This Level turns off the logging
FATAL Logs severe error message that may cause system crash
ERROR Logs runtime errors and unexpected conditions
WARN Logs information regarding System’s unexpected conditions
INFO Logs information messages
DEBUG Logs information on debugging messages
ALL Logs all details information

Log table

ALL FATAL ERROR WARN INFO DEBUG TRACE AIL
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
OFF

Examples

log.info("Test Infomation");
log.error("An error message");
log4j for professional
log4j for professional

Log4j Conversion Characters

Log4j also supports conversion characters pattern for log messages. The conversion characters should be preceded by a % symbol.

Conversion Character Meaning 
c(Small letter) output the category of the logging event.
C(Capital letter) output the fully qualified class name that issues logging request.
d(Small letter) output the date of the logging event.
F(Capital letter) output the file name requesting the logging request.
l(Small letter) output the location information of the caller requesting logging event.
L(Capital letter) output the line number from where logging request is raised.
m(Small letter) output the application supplied message along with the message event.
M(Capital letter) output the method name from where the logging request raised.
n(Small letter) output the platform-dependent line separator character(s).
p(Small letter) output the priority of the logging event.
r(Small letter) output the number of milliseconds elapsed from the layout construction

until the log event creation

t(Small letter) output the name of the thread that requested the logging event.
X(Capital letter) output the mapped diagnostic context associated with the thread that

requested the logging event.

x(Small letter) output the nested diagnostic context associated with the thread that

requested the logging event.

% is the sequence %% outputs a single % sing.

The code for the pattern is as follows:

log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
How does a level work in log4j?

A logging request of level X in a logger with level Y is enabled if X>=Y. This essentially brings level priority into the picture.

The level hierarchy is as follows:

OFF>FATAL>ERROR>WARN>INFO>DEBUG>ALL

So if a logging request is set to WARN then, INFO, DEBUG and ALL will not get printed rather WARN, ERROR, FATAL messages will be printed. This is the reason why we should set the logger level wisely.

Can we set the logger level by coding?

Yes, we can set the logger level by coding. Below is the code:

private static org.apache.log4j.Logger logger=Logger.getLogger(xyz.class);
logger.setLevel(level.WARN);
Can we set the logger level by properties file?

We can also change the level by using a .properties file. In that case, we have to mention the following code in the file.

log4j.rootLogger=WARN
Beware of DEBUG Level issue

DEBUG level logging has some disadvantages. It can provide customers’ personal information like user id, password, credit card details etc. It is always better not to use DEBUG level in production. It can be used in lower-level environments. like deployment or testing.

  • Filter Object- Filter object is responsible for analyzing the logging information and make a further decision about logging. an Appender object may have several filter objects associated with it. All filter objects need to approve the logging information before it goes to the final report.
  • Object Renderer-  Object Renderer is responsible for providing String representation of an object. The layout objects use this String representation prepare final logging information that will be published to the report.
Log4j Architecture
Log4j Architecture
  • Log Manager- Log Manager manages the overall logging framework. It reads the initial configuration parameters from the configuration file or configuration class.

What is the configurator file in log4j?

Log4j is opensource and easily configurable across any java or java-based or any other languages. Basic configurator file in log4j is as follows:

  • .properties file
  • .XML file
  • .JSON
  • .YAML

Basic Configurator

To work with the basic configurator, we need to follow the following steps:

  • Create an instance for the logger class using the getLogger() method. The method accepts the class name for which logs has to be generated. The class name should be followed by the “.class” extension.
  • Use the BasicConfigurator.config() method to automatically generate the log files in the pre-defined layout format.
  • Use the logger reference variable to generate user-defined log messages that will be posted to the log file.

Example:

Logger logger=Logger.getLogger(xyz.class);
BasicConfigurator.configure();
logger.info("Logging info");
//step-1
logger.info("Step-1 completed");
//step-2
logger.info("Step-2 completed");

Note:

  • Using Basic Configurator, the log will go to the console window.
  • The default pattern layout is [%t]%-5p%c-%m%n
  • By default, the root logger is set to DEBUG level.
log4j complete Guide
log4j complete Guide

In our day by day life, we configure log4j via an external file. for that the options we have as follows:

  • log4j.configuration
  • log4j.properties file

Log4j .properties file

To work with the properties file, we need to follow the following steps:

  • Create a class file.
  • Create an instance of the logger class and pass the .class file name to getLogger() method. The logger will generate logs for this file.
Logger logger=Logger.getLogger(xyz.class);
logger.info("Logging info");
//step-1
logger.info("Step-1 completed");
//step-2
logger.info("Step-2 completed");
  • Create a log4j properties file.
  • Write the below entries to log4j.properties file
log4j.rootLogger=DEBUG
log4j.rootCategory=INFO, file,console, stdout
# configuration to print into file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:TestTestlogging.log
log4j.appender.file.MaxFileSize=20MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# configuration to print on console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

The same can be done for XML configuration file.

Log4j.xml file

To work with the log4j.xml file, we need to follow the following steps:

  • Create a class file.
  • Create a file called log4j.xml
  • The entries will be as follows:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
  xmlns:log4j='http://jakarta.apache.org/log4j/'>
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
	    <layout class="org.apache.log4j.PatternLayout">
		<param name="ConversionPattern" value="%d{MM-dd-yyyy HH:mm:ss} %F %-5p [%t] %c{2} %L - %m%n" />
	    </layout>
	</appender>
	<appender name="file" class="org.apache.log4j.RollingFileAppender">
	    <param name="append" value="false" />
	    <param name="maxFileSize" value="10MB" />
	    <param name="maxBackupIndex" value="10" />
	    <param name="file" value=".LogsTestLogs.log" />
	    <layout class="org.apache.log4j.PatternLayout">
		<param name="ConversionPattern" value=%d{ISO8601} %5p %F [%t] %c{1}:%L - %m%n />
	    </layout>
	</appender>
	<root>
		<level value="INFO" />
		<appender-ref ref="console" />
		<appender-ref ref="file" />
	</root>
</log4j:configuration>

How to Disable additivity to prevent duplicate logging?

When we derive logger from a base logger, due to additivity, the extra logging capabilities come to the derived one. In this case, root logger always receives duplicate entries.

look at the below example:


log4j.logger.com.test=info,printConsole
log4j.logger.com.test.extension=debug,printConsole

In this case, when com.test gets executed, the statements get executed twice due to additivity.
To disable this, we need to add an extra line


log4j.logger.com.test=info,printConsole
log4j.logger.com.test.extension=debug,printConsole
log4j.additivity.com.test.extension=false
Best Log4j book
Best Log4j book

This is how we will block the duplicate logging into the logger.

How to setup Log4j with Eclipse?

To connect Log4j with Eclipse, we need to follow the following steps:

  • Open Eclipse.
  • Navigate to the project or create a new project.
  • Right-click on the project
  • Go to build path
  • Click on Configure Build path
  • Open external jar buttons
  • Point to log4j.jar and any associated jars
  • Click on Ok
  • Click on Finish.

How to connect Log4j with Selenium?

To connect Log4j with Selenium, we need to follow the following steps:

  • Create a java project from the IDE(Like Eclipse)
  • Create a logger instance in a .java file
  • Configure the log4j with selenium project(By navigating configure build path->add external jars–> select log4j and additional jars->Select ok)
  • Output the log file

Can log4j Send an email?

Yes, Log4j can send an email too. The configuration is as follows:

log4j.rootLogger=ERROR, mail
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
[email protected]
[email protected]
log4j.appender.mail.SMTPHost=mail.yourdomain.com
log4j.appender.mail.Threshold=ERROR
log4j.appender.mail.BufferSize=1
log4j.appender.mail.Subject=Application Error
log4j.appender.Mail.layout=org.apache.log4j.PatternLayout 
log4j.appender.Mail.layout.ConversionPattern=%d %-5p %c %x - %m%n

Can log4j send logs to a remote machine?

Yes, log4j can send our logs to the remote machine. For this, we have to use SocketAppender. The code will be as follows:

Send logs to remote:
log4j.rootLogger=DEBUG, server
log4j.appender.server=org.apache.log4j.net.SocketAppender
log4j.appender.server.Port=4712
log4j.appender.server.RemoteHost=loghost
log4j.appender.server.ReconnectionDelay=10000
Receiver end:
log4j.rootLogger=DEBUG, file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=logfile.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d] [%t] [%m]%n

How to initiate log4j from the command line?

To initiate the log4j- file the command line the command will be as follows –

java -classpath log4j-path.jar org.apache.log4j.net.SimpleSocketServer 4852
log4j-reciever.properties

How to connect Maven with Log4j

A maven is a build tool and it is powered by POM.xml file. In order to connect Maven with log4j, we need to put the log4j entry to the POM.xml in the following manner.

Maven repository- https://mvnrepository.com/artifact/log4j/log4j

<dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>x.y.z</version>
</dependency>
The complete log4j Manual
The complete log4j Manual

How to read the log dump?

A notepad++ or simple notepad can read the log files. But for easy viewing, we can download any log analyzer tool or log reader tool. Example- LogExpert

Advantages of logging

  • Quick debugging-A well structured and beautifully written log can make the debug process very easy and quick. That reduces the resource cost.
  • Problem Identification- A log provides hidden issues in the application code as well as test code.
  • Easy maintenance- As stated earlier, a log can enable easy debugging hence the maintenance effort and cost are significantly reduced.

Disadvantages of Logging

  • Loggers are runtime overhead as the computer has to generate them apart from running regular lines of code. On top of that logs needs to be pushed to any I/O devices that is another overhead.
  • Logging is coder overhead to write additional code inside application or test code.
  • If proper planning is not done, the logger can generate log mess that creates further confusion during a debug process.
  • Bad logging codes can degrade execution performance.

Best practices on log4j

  1. Always declare logger as Static. This will save CPU cycle that eventually means you will save time.
Private Static final Logger log = Logger.getlogger (MyClass)
  1. Enable log4j’ internal Debug logging-If we are facing challenges with very specific appender, we can enable log4j internal debugger by the following command-
java - Dlog4j.debug-cp. Com.MyClass
  1. Do not send the logs to the database with JDBC appender –

With JDBC appender we can always send logs to the database. But issues arise when we query the database for a huge volume. It is always good to put logs to a file instead of a database.

  1. Triggering email for every exception as failure is not a valid option. We have seen how it can spam the mailbox.
  2. Use NTEventLogAppender to handle alerts for any exceptions.
  3. Use log management System often to review the logs across various servers. It will help us to find the correct log file for us from several servers. Otherwise, it will very time-consuming task.
  4. Use appropriate filters to unnecessary log statements.
  5. Use custom log4j Appender.
  6. Always customise log4j layout.
  7. Use contexts wisely to log additional details.
  8. Use log4j.NDC to push additional logs.

Supporting libraries

  • JavaMail API: To send an email upon failure and error in log4j, we need the Java Mail API (mail.jar) 
  • JavaBeans Activation Framework: The Java Mail API will also require that the JavaBeans Activation Framework (activation.jar)
  • Java Message Service: In order to make use of the JMS-compatible features of log4j, it requires JMS and Java Naming and Directory Interface JNDI.
  • XML Parser: we need a  JAXP-compatible XML parser to use log4j like-Xerces.jar

Ref:

Oracle site for log4j- https://docs.oracle.com/cd/E29578_01/webhelp/cas_webcrawler/src/cwcg_config_log4j_file.html

LEAVE A REPLY

Please enter your comment!
Please enter your name here