【问题标题】:log4j properties file bundled into jar in spark app is ignored在 spark 应用程序中捆绑到 jar 中的 log4j 属性文件被忽略
【发布时间】:2026-01-18 05:05:02
【问题描述】:

我需要从 src/resources 中读取自定义 log4j.properties,但这不起作用

try{
  val  inStream :InputStream= className.this.getClass.getClassLoader.getResourceAsStream("log4j.properties");

  logCfgProps.load(inStream)

} catch {
  case e: Throwable=>
    e.printStackTrace()
    log.error("log.properties file not present")
}

PropertyConfigurator.configure(logCfgProps)

表示jar中捆绑的log4j被忽略。

我无法触摸 spark home 的 conf 目录中的 log4j 属性。

还有哪些其他选择?

编辑 一定有什么问题(在类路径中?) 既然这样做了

val resource:URL = Thread.currentThread().getContextClassLoader()
  .getResource("log4j.properties");
System.out.println("resource = " + resource); 

它指向我无法修改的conf目录中的log4j,我需要忽略它。

怎么做?

【问题讨论】:

    标签: intellij-idea apache-spark sbt classloader getresource


    【解决方案1】:
    1. 您可以只为您的文件指定另一个名称(并在代码中使用它),因此与conf/log4j.properties 没有冲突。

    2. 您可以使用ClassLoader.getResources("log4j.properties") 获取类路径中具有给定名称的所有资源,然后选择您想要的。

    【讨论】: