1. 警告信息

错误输出信息:

log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

在这里插入图片描述

2. 错误解读

如果找不到默认配置文件log4j.properties和log4j.xml,并且应用程序不执行显式配置,就会发生这种情况。log4j使用Thread.getContextClassLoader().getResource()定位默认配置文件,而不直接检查文件系统。要知道放置log4j.properties或log4j.xml的适当位置,就需要了解使用中的类加载器的搜索策略。log4j不提供默认配置,因为在某些环境中可能禁止输出到控制台或文件系统。

2.1 未引入log4j的依赖

在pom.xml文件中插入如下代码。

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

2.2 未配置log4j.properties文件

log4j.rootLogger=debug, stdout, R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log

log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=5

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n

实际上,还是推荐把这个文件夹放在src/main/resources下。

2.3 还是出现警告

手动写一个初始化的方法吧,一劳永逸。

package util;

import org.apache.log4j.PropertyConfigurator;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class initLogRecord {
    public static void initLog() {
        FileInputStream fileInputStream = null;
        try {
            Properties properties = new Properties();
            fileInputStream = new FileInputStream("src/main/resources/log4j.properties");
            properties.load(fileInputStream);
            PropertyConfigurator.configure(properties);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

实际上,最重要的就是
fileInputStream = new FileInputStream("src/main/resources/log4j.properties");
根据自己的需要指定这个配置文件的路径吧。

记得在运行主程序之前,调用这个方法进行log4j的初始化!!!

在这里插入图片描述

3. 完美解决

在这里插入图片描述
以上就完美解决了log4j.properties配置问题。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐