Log4J 2 introduces configuration support through JSON and YAML in addition to properties file and XML. If you are new to Log4J 2, I suggest reading my introductory post on Log4J 2, Introducing Log4J 2 – Enterprise Class Logging. For Log4J 2 configuration using properties file, read my post Log4J 2 Configuration: Using Properties File, and for using XML, Log4J 2 Configuration: Using XML.
As our default properties file name is log4j.properties, we no need to import properties file explicitly into Client.java, by default our java class will verify for the properties file named log4j.properties. Log4j.rootLogger is at the top of all the logger hierarchy, just like we have Object in java classes. So whenever you are logging and there is no match with a logger configuration, root logger configuration will be used. Log4j.rootLogger example. Let’s understand this with a simple example. Suppose we have a log4j.properties file like below. Log4j tutorial for beginners and professionals with examples in eclipse on java log4j example code, log4j logging levels, log4j.properties, log4j.xml, log4j file appender, log4j multiple appenders, log4j tutorial pdf download, file logging and more.
In this post, I discuss how to configure Log4J 2 using JSON.
Maven Dependencies for JSON Configuration
To use Log4J2, you need to add the required Log4J 2 dependencies in your Maven POM, as described here. For JSON configuration, you also need Jackson, a suite of>log4j2.json or
log4j2.jsn
in the project classpath.The following figure shows the skeleton of a JSON configuration file in the IntelliJ editor.
As shown in the preceding figure, a
log4j2.json
file is composed of nested JSON objects. At the top is the configuration
object that contains the following objects:properties
: Defines one or more properties as a JSON array of name-value pairs. The properties can be referred by their names from the different parts of the configuration file.appenders
: Configures one or more appenders, such asConsole
,File
, andRollingFile
.Loggers
: Configures the root logger represented byroot
along with zero or more application-specific loggers, each represented bylogger
.
We will configure two appenders to write log messages to the console and a file. We’ll also configure an application-specific logger along with the root logger to use the appenders, like this:
In the configuration code above:
- Line 4 – Line 15: We declared two properties as name-value pairs in the
property
JSON array. - Line 16 – Line 31: We configured the
Console
andFile appenders
. - Line 32 – Line 43: We configured an application-specific logger for all the logger classes of the
guru.springframework.blog.log4j2json
package. This logger writeserror
and higher level log messages to the file appender. We also configured the root logger to logdebug
and higher level messages to the console appender.
If we run the
Log4J2JsonConfTest
test class, Log4J 2 will generate log messages and send them to both the console and a file, as shown in this figure.Configuring a Rolling File Appender via JSON
If you use the file appender for writing logs, the size of log file will grow with time. This can have significant consequences in enterprise applications that typically have very large code bases containing a significant amount of logging code. A long running application can easily produce millions and millions of lines of logging information which can cause the files to become very large. Imagine scanning through a log file with 10s of thousands of lines of log statements to find a specific statement. In order to avoid that situation, you should use the rolling file appender.
A rolling file appender supports writing to a file and rolls the file over according to one of your pre-defined policies. For example, you can define a size-based triggering policy that causes a rollover once the file has reached a specified size. You can also define a time-based triggering policy that causes a rollover once the date/time pattern is no longer applies to the active log file. You can refer the Log4J 2 manual to learn more about the rolling file.
The code to configure a rolling file appender is this.
In the code above:
- Line 3: We used the
name
property ofRollingFile
to define a name of this appender that loggers can use. - Line 4- Line 5: We used the
fileName
andfilePattern
properties to define the name of the file to write to and the pattern of the file name of the archived log file respectively. - Line 9 -Line 13: We used
Policies
to define a sized-based triggering. For testing purpose, we set themax property
to roll the log file once its size exceeds1 KB
for. - Line 14 – Line 16: We used
DefaultRolloverStrategy
to instruct Log4J 2 to keep up to 30 rolling files before deleting them.
To use the rolling file appender, add the appender reference to the logger, like this.
In Line 11 of the configuration code above, we added a reference to the rolling file appender. Note that we used a JSON array to define the appender references. This is required because, without an array, Log4J 2 will only catch one appender – the last one.
On running the
Log4J2JsonConfTest
test class, a rollingfile.log
file is generated in the logs
folder with debug
and higher level log messages. Now if you run the Log4J2JsonConfTest
test class couple of more times till the size of the rollingfile.log
file exceeds 1 KB, Log4J 2 creates a .gz
archive of the generated rolling file in the archive
directory.Logging Additivity
If you have noticed, till now we haven’t used the console appender in our application-specific logger, but log messages are still getting sent to the console. It’s due to additivity. Log messages are getting sent additively to the console by the root logger. You can override this default behavior by setting the
additivity
property of a logger to false
.The complete code of the
log4j2.json
file with additivity disabled is this:In Line 54 of the code above, we configured a console appender with the level
info
for our logger. We also disabled additivity in Line 52 by adding the additivity
property with a false
value.Now, when we run the test class, our logger will use the newly configured console appender instead of the one in the root logger. You can run the test class again to check that
info
and higher log messages are now getting sent to the console, as shown in this figure.Additivity can be somewhat confusing. I suggest reviewing the Log4J 2 documentation on the subject, where they have some good examples how this works.
Summary
JSON is the natural choice for data-interchange in enterprise applications, particularly Web 2.0 applications. There is no evident performance advantage or disadvantage from logging perspective between the various Log4J2 supported formats: properties file, XML, JSON, and YAML. Many argue from configuration perspective that presence of schemas and associated schema validation, which is undoubtedly huge for enterprises, gives XML the edge. Many others support JSON or YAML as they are not only more compact and readable, as compared to XML, but also faster in transmission because it does not come with the extra baggage of tags.
I suggest, as a developer, you should not get tied to a particular format. You may have your own preference, but every enterprise is different. Some may standardize on a format, some may not. Some development teams may prefer JSON over XML, others will like XML over JSON.
In this tutorial, we will show you how to use the classic log4j 1.2.x to log a debug or error message in a Java application.
1. Project Directory
Review the final project structure, a standard Maven style Java project.
2. Get Log4j
Declares the following dependencies :
pom.xml
For non-Maven user, visit log4j official page, download the jar and put it in the project library path manually.
3. log4j.properties
Create a
Notelog4j.properties
file and put it into the resources folder. Refer to the step #1 above.- For standalone Java app, make sure the
log4j.properties
file is under theproject/classes
directory - For Java web applications, make sure the
log4j.properties
file is under theWEB-INF/classes
directory
Note
To understand the symbols in the
To understand the symbols in the
ConversionPattern
, please refer to this log4j PatternLayout guide.Let break it down :
- %d{yyyy-MM-dd HH:mm:ss} = Date and time format, refer to SimpleDateFormat JavaDoc.
- %-5p = The logging priority, like DEBUG or ERROR. The -5 is optional, for the pretty print format.
- %c{1} = The logging name we set via getLogger(), refer to log4j PatternLayout guide.
- %L = The line number from where the logging request.
- %m%n = The message to log and line break.
Log message examples :
4. Demo – How to log a Message?
To log a message, first, create a
final static
logger and define a name for the logger, normally, we use the full package class name. Then, logs messages with different priorities, for example, debug, info, warn, error and fatal. Normally, you just need to use debug or error.
4.1 Example : Logger is set to debug priority.
HelloExample.java
Output
4.2 Example – Logger is set to error priority.
Run the
HelloExample
again, you will get the following outputReview the log4j’s
Priority
class.Priority.java
If priority is defined in
log4j.properties
, only the same or above priority message will be logged.5. Demo – How to log an Exception
An example to show you how to use log4j to log an exception.
Output
Done.
Download Source Code
Download Source Code – log4j-hello-world-example.zip(8 KB)