Log4j2 dependency
To use Log4j2 (an upgrade of Log4j), we need to add following dependencies:
pom.xml<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.25.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
<version>2.25.2</version>
</dependency>
Note that log4j-jcl is not needed after Spring 5 because new module spring-jcl takes care of the bridging of log4J2 to JCL.
log4j2.properties
src/main/resources/log4j2.propertiesstatus = error
name = PropertiesConfig
filters = threshold
filter.threshold.type = ThresholdFilter
filter.threshold.level = info
appenders = console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yy-MM-dd HH:mm:ss:SSS} %-5p %c{1}:%L - %m%n
rootLogger.level = info
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT
Configuration can be done in XML, JSON, YAML, or properties format. Check out different configuration options here.
Example Bean
package com.logicbig.example;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class MyBean {
private static Log log = LogFactory.getLog(MyBean.class);
public void doSomething() {
log.info("doing something");
}
}
Main class
package com.logicbig.example;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.Collections;
@Configuration
public class ExampleMain {
@Bean
public MyBean myBean() {
return new MyBean();
}
public static void main(String[] args) {
ConfigurableApplicationContext context =
new AnnotationConfigApplicationContext(ExampleMain.class);
MyBean bean = context.getBean(MyBean.class);
bean.doSomething();
}
}
Output25-11-11 07:21:16:143 INFO MyBean:10 - doing something
Example ProjectDependencies and Technologies Used: - spring-context 6.2.12 (Spring Context)
Version Compatibility: 3.2.3.RELEASE - 6.2.12 Version compatibilities of spring-context with this example: Versions in green have been tested.
- log4j-core 2.25.2 (A versatile, industrial-grade, and reference implementation of the Log4j API.
It bundles a rich set of components to assist various use cases:
Appenders targeting files, network sockets, databases, SMTP servers;
Layouts that can render CSV, HTML, JSON, Syslog, etc. formatted outputs;
Filters that can be configured using log event rates, regular expressions, scripts, time, etc.
It contains several extension points to introduce custom components, if needed. [Description from log4j-core-2.25.2.pom])
- log4j-jcl 2.25.2 (The Apache Log4j Commons Logging Adapter)
- JDK 25
- Maven 3.9.11
|
|