转载至:
https://blog.csdn.net/vbirdbest/article/details/71751835
如下是maven项目中的实例:
首先pom.xml中引入如下依赖,注意看都是2.××××开头的版本,所以就是log4j2需要的依赖。
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.11.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-api</artifactId> <version>2.11.2</version> </dependency>
package com.yuanqiao.spring;
/**
* 这个包的路径一定要对才行。
*/
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import com.yuanqiao.mbean.beans.SpringPersonMBean;
public class SpringApplicationContext {
static Logger logger=LogManager.getLogger("Console");
public static void main(String[] args) {
logger.debug("this is the debug message");
logger.info("this is the debug message");
logger.error("this is the debug message");
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
SpringPersonMBean bean = (SpringPersonMBean)applicationContext.getBean("personMBean");
System.out.println(bean.getName());
}
}
在maven项目中的src/main/resoures下面建一个log4j2.xml文件,里面的内容如下:
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN"> <Appenders> <Console name="Console" target="SYSTEM_OUT"> <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" /> </Console> <RollingFile name="RollingFile" filename="log/test.log" filepattern="${logPath}/%d{YYYYMMddHHmmss}-fargo.log"> <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" /> <Policies> <SizeBasedTriggeringPolicy size="10 MB" /> </Policies> <DefaultRolloverStrategy max="20" /> </RollingFile> </Appenders> <Loggers> <Root level="info"> <AppenderRef ref="Console" /> <AppenderRef ref="RollingFile" /> </Root> </Loggers> </Configuration>
