Java log4j properties file

The log4j.properties file

The log4j.properties file sets the logging properties.

You can modify the log4j.properties file to change the properties for the log4j loggers.

Default log4j properties

log4j.rootLogger=ERROR,stdout log4j.logger.com.endeca=INFO # Logger for crawl metrics log4j.logger.com.endeca.itl.web.metrics=INFO log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%p\t%d\t%r\t%c\t[%t]\t%m%n

The presence of only the ConsoleAppender means that the standard output is directed to the console, not to a log file.

Logging to a file

You can change the default log4j.properties configuration so that messages are logged only to a file or to both the console and a file. For example, you would change the above configuration to a configuration similar to this:

# initialize root logger with level ERROR for stdout and fout log4j.rootLogger=ERROR,stdout,fout # set the log level for these components log4j.logger.com.endeca=INFO log4j.logger.com.endeca.itl.web.metrics=INFO # add a ConsoleAppender to the logger stdout to write to the console log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # use a simple message format log4j.appender.stdout.layout.ConversionPattern=%m%n # add a FileAppender to the logger fout log4j.appender.fout=org.apache.log4j.FileAppender # create a log file log4j.appender.fout.File=crawl.log log4j.appender.fout.layout=org.apache.log4j.PatternLayout # use a more detailed message pattern log4j.appender.fout.layout.ConversionPattern=%p\t%d\t%r\t%c\t[%t]\t%m%n

In the example, the FileAppender appends log events to the log file named crawl.log (which is created in the current working directory). The ConsoleAppender writes to the console using a simple pattern in which only the messages are printed, but not the more verbose information (logging level, timestamp, and so on).

  • DEBUG designates fine-grained informational events that are most useful to debug a crawl configuration.
  • TRACE designates fine-grained informational events than DEBUG .
  • ERROR designates error events that might still allow the crawler to continue running.
  • FATAL designates very severe error events that will presumably lead the crawler to abort.
  • INFO designates informational messages that highlight the progress of the crawl at a coarse-grained level.
  • OFF has the highest possible rank and is intended to turn off logging.
  • WARN designates potentially harmful situations.
Читайте также:  Php цикл по времени

Note the default log4j.properties file contains a number of suggested component loggers that are commented out. To use any of these loggers, remove the comment ( # ) character.

Oracle® Endeca CAS Web Crawler Guide · Version 3.0.2 · March 2012

Источник

Log4J 2 Configuration: Using Properties File

Spring Framework Guru

Spring Framework Guru

Log4J 2 is a logging framework designed to address the logging requirements of enterprise applications. Its predecessor Log4J 1.x has been around for more than one and a half decade and is still one of the most widely used Java logging framework. Log4J has even been ported to the .NET world. Log4net is one of the most popular logging frameworks for Microsoft’s .NET environment.

Log4J 2 goes steps ahead by removing the inherent architectural flaws of Log4J 1.x. Since the initial release of Log4J 2 on August 2015, it’s quickly being adopted by the developer community. I wrote an introductory post on Log4J 2 here. If you have not read it, I recommend starting with the introductory post first. In this post, I will discuss how to configure Log4J 2 using a properties configuration file. This is just one of several ways you can configure Log4J 2.

What are Log4J 2 Configuration Files?

Log4J 2 provides various components, such as loggers, appenders, and layouts that work together to perform logging in an application. As different applications have different logging requirements, you’re able configure LogJ 2 accordingly. Also, you will often need to keep changing Log4J 2 configurations of an application across its deployment lifecycle. For example, it is common to set the logging level to DEBUG during development, and later switch it to ERROR to avoid filling your logs with excessive debug information. Similarly, during local development, you can work with the console appender to avoid file I/O overheads and in other deployment environments, set a file appender or some other persistent destination to preserve log messages.

You can configure Log4J 2 either programmatically in your application or through configuration files, such as properties, XML, JSON, and YAML residing on your project classpath. Through the use of configuration files, you have the flexibility of changing the various configuration options without modifying your application code. In this post we’re going to look at using properties file.

Setting up Log4J 2 to Use Properties File

Unlike its predecessor Log4J 1.x, Log4J 2 did not support configuration through properties file when it was initially released. It was from Log4J 2.4 that support for properties file was again added, but with a completely different syntax.

Log4J4 Maven Dependencies

To use Log4J 2 in your application, you need to ensure that the Log4J 2 jars are on your project classpath. If you intend to use properties file, give extra attention to ensure that you have the Log4J 2.4 or greater jars on the classpath. Otherwise, your properties file will not get picked.
When using Maven, specify the following Log4J 2 dependencies.

. . . org.apache.logging.log4j log4j-api 2.5  org.apache.logging.log4j log4j-core 2.5  . . .

Log4J 2 Spring Boot Dependencies

If you want to use Log4J 2 in a Spring Boot project, things can be a bit tricky. Simply adding the dependencies above won’t work as Spring Boot will first find the default Logback classic on the classpath, and will use it. Therefore, you need to exclude the default dependency of the Spring Boot starter on Logback classic, and instead include the Spring Boot starter dependency on Log4J 2, like this.

. . . org.springframework.boot spring-boot-starter  org.springframework.boot spring-boot-starter-logging    org.springframework.boot spring-boot-starter-log4j2  . . .

This will configure Spring Boot to use Log4J 2, but with a catch – You still won’t be able to use properties file for configuration. As of Spring Boot 1.3.3 Release, Spring Boot starter dependency on Log4J 2 is for Log4J 2.1, and as I have already mentioned it is from Log4J 2.4 onward that properties file is supported. Therefore, you need to explicitly specify dependencies of Log4J 2.4 or above after excluding Spring Boot starter logging, like this.

. . . org.springframework.boot spring-boot-starter  org.springframework.boot spring-boot-starter-logging    org.apache.logging.log4j log4j-api 2.5  org.apache.logging.log4j log4j-core 2.5  . . .

The above dependencies will set up Log4J 2 to use properties file in a Spring Boot application.

Spring Framework 5

Configuring Log4J 2 using Properties File

By default, Log4J 2 looks for a properties file with the name log4j2.properties in the classpath. In a Spring Boot application, the log4j2.properties file will typically be in the resources folder.

Before we start configuring Log4J 2, we will write a Java class to generate log messages via Log4J 2.

Log4J2PropertiesConf.java

//package guru.springframework.blog.log4j2properties; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log4J2PropertiesConf < private static Logger logger = LogManager.getLogger(); public void performSomeTask()< logger.debug("This is a debug message"); logger.info("This is an info message"); logger.warn("This is a warn message"); logger.error("This is an error message"); logger.fatal("This is a fatal message"); >>

To test the Log4J2PropertiesConf class above, we will write a JUnit test class.

Log4J2PropertiesConfTest.java

We will now configure Log4J 2 using a properties file. Like any other Java properties file, a log4j2.properties file are a set of key value pairs with options to configure the various components of Log4J 2, such as loggers, appenders, and layouts. A basic log4j2.properties file starts with a name, optional properties to be used in other parts of the file, and appender declarations.

name=PropertiesConfig property.filename = logs appenders = console, file . . .

The preceding code declares two appenders, named console and file . Next, let’s configure both the appenders to write log messages to the console and a file. The configuration code for the appenders is this.

. . . appender.console.type = Console appender.console.name = STDOUT appender.console.layout.type = PatternLayout appender.console.layout.pattern = [%-5level] %d [%t] %c - %msg%n appender.file.type = File appender.file.name = LOGFILE appender.file.fileName=$/propertieslogs.log appender.file.layout.type=PatternLayout appender.file.layout.pattern=[%-5level] %d [%t] %c - %msg%n . . .

In the code above we configured two appenders: One to write log messages to the console and the other to a log file. Both the appenders use pattern layouts that are configurable with conversion pattern strings to format log messages. The appender.console.layout.pattern property specifies the pattern string. You can learn more about the pattern layout and conversion pattern strings here. For the file appender, we used the appender.file.fileName property to specify the name and location of the log file that Log4J 2 will generate. Here, notice the $ declaration that we used as a substitution for the property.filename property we declared earlier.

Next we will configure the loggers, starting from the root logger.

. . . rootLogger.level = debug rootLogger.appenderRefs = stdout rootLogger.appenderRef.stdout.ref = STDOUT . . .

Log4J 2 Messages in InteliJ Console

In the code above, we configured the root logger to log debug and its lower level messages to the console (stdout). When we run the Log4J2PropertiesConfTest test class, the output in the IntelliJ console will be similar to this.

The complete log4j2.properties file is this.

log4j2.properties

//name=PropertiesConfig property.filename = logs appenders = console, file appender.console.type = Console appender.console.name = STDOUT appender.console.layout.type = PatternLayout appender.console.layout.pattern = [%-5level] %d [%t] %c - %msg%n appender.file.type = File appender.file.name = LOGFILE appender.file.fileName=$/propertieslogs.log appender.file.layout.type=PatternLayout appender.file.layout.pattern=[%-5level] %d [%t] %c - %msg%n loggers=file logger.file.name=guru.springframework.blog.log4j2properties logger.file.level = debug logger.file.appenderRefs = file logger.file.appenderRef.file.ref = LOGFILE rootLogger.level = debug rootLogger.appenderRefs = stdout rootLogger.appenderRef.stdout.ref = STDOUT

When we run the Log4J2PropertiesConfTest test class now, log messages will be sent to the logs/propertieslogs.log by the file logger and additively to the console by the root logger. The following figure shows the log messages sent to the file and console in IntelliJ.

Log4J 2 Output in IntelliJ

In the example above, it is due to logger additivity that caused log messages to be sent to the file by the logger and additively to the console by the root logger. You can override this default behavior by setting the additivity flag of a logger to false.

. . . logger.file.additivity = false . . .

The property above configures our file appender so that it is no longer additive. Thus, log messages will only be sent to the file.

Appender 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

Using properties file is one of the several options you have to configure Log4J 2. Log4J 2 is gradually moving to XML configuration and the new JSON and YAML configurations. Properties configuration cannot handle some advanced features, such as custom error handlers, time-based rolling policies, nested appenders, and special types of appenders, such as async appenders. However, properties configuration is still being extensively used. Often you don’t need many of the more advanced logging features of Log4J 2. So you’re fine using the simplicity of the properties file configuration.

In future posts, I will cover using other configuration options for Log4J 2. This is to address logging configurations with more complex requirements.

Источник

Оцените статью