首页 > 解决方案 > 运行时 log4j.PropertyConfigurator 错误说找不到合适的方法用于配置(FileInputStream)

问题描述

我在 Log4j 的构建阶段收到以下错误。它说没有为configure(FileInputSteam)找到这样的方法。

以下是错误的完整上下文。

任务:编译Java失败

E:\GadleDemoProj\src\main\java\com\hal\brands\helper\Logger\LoggerHelper.java:28: error: no suitable method found for configure(FileInputStream)
                        PropertyConfigurator.configure(inputStream);
                                            ^
    method PropertyConfigurator.configure(Properties) is not applicable
      (argument mismatch; FileInputStream cannot be converted to Properties)
    method PropertyConfigurator.configure(String) is not applicable
      (argument mismatch; FileInputStream cannot be converted to String)
    method PropertyConfigurator.configure(URL) is not applicable
      (argument mismatch; FileInputStream cannot be converted to URL)

我的 Logger 类如下:

 public class LoggerHelper {
    
    private static boolean root = false;
    
    public static Logger getLogger(Class clas) {
        if(root)
            return Logger.getLogger(clas);
        
        /*PropertyConfigurator.configure(ResourceHelper
                .getResourcePath("configfile/log4j.properties"));*/
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(System.getProperty("user.dir")+"\\src\\main\\resources\\configFile\\log4j.properties");
            
            PropertyConfigurator.configure(inputStream);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        root = true;
        return Logger.getLogger(clas);
    }

}

标签: javagradlelog4jbuild.gradle

解决方案


将代码更新为此:

public class LoggerHelper {
    
    private static boolean root = false;
    
    public static Logger getLogger(Class clas) {
        if(root)
            return Logger.getLogger(clas);
        
        /*PropertyConfigurator.configure(ResourceHelper
                .getResourcePath("configfile/log4j.properties"));*/
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(System.getProperty("user.dir")+"\\src\\main\\resources\\configFile\\log4j.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            
            PropertyConfigurator.configure(properties);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        root = true;
        return Logger.getLogger(clas);
    }

}

推荐阅读