Load the lo4j.properties log file

1. Look at the directory structure of my project project (maven projects, resource files are generally placed in the src/main/resources directory, if it is a non-maven java project, it can be placed in the src root directory)


2. The maven project configuration file pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>hello</groupId>
	<artifactId>test</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	<name>test</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<!-- slf4j -->
		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.5.5</version>
		</dependency>

	</dependencies>
</project>

 

3. Code

public class TestLog {
	
	public static final Logger log = LoggerFactory.getLogger(TestLog.class);
	
	public static void main(String[] args) {
		//int count = 0;
		log.info("-------begin----");
		//if(log.isDebugEnabled()){
		//	log.debug("debug");
		//}
		log.debug("debug{}");
		log.info("-------end------");
		
	}
}

 

4. But sometimes we need to put the log4j.properties log configuration file in the specified directory, such as the cfg directory in the project directory, and move the log4j.properties file to the cfg directory, the following error occurs

log4j:WARN No appenders could be found for logger (hello.test.TestLog).
log4j:WARN Please initialize the log4j system properly.

 5. According to the above information, the log4j.properties file is not found, just modify the code.

public static void main(String[] args) {
		 PropertyConfigurator.configure("./cfg/log4j.properties");//Specify the path of the log configuration file
		//int count = 0;
		log.info("-------begin----");
		//if(log.isDebugEnabled()){
		//	log.debug("debug");
		//}
		log.debug("debug{}");
		log.info("-------end------");
		
	}

 6. Output results

2017-07-31 22:47:48,662-5p TestLog  - -------begin----
2017-07-31 22:47:48,665-5p TestLog  - debug{}
2017-07-31 22:47:48,665-5p TestLog  - -------end------

 

 

 


 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327039996&siteId=291194637