You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Log4j2配置File appender时报fileName为null异常如何解决

问题描述

运行应用程序时出现File Name is null报错,对应Log4j报错信息为:

Log4j - Getting fileName is Null {The parameter is null: fileName}

运行时抛出的具体异常信息如下:

org.apache.logging.log4j.core.config.ConfigurationException: Arguments given for element File are invalid: field 'fileName' has invalid value 'null'
    at org.apache.logging.log4j.core.config.plugins.util.PluginBuilder.injectFields(PluginBuilder.java:208)

当前使用的log4j2.yaml配置如下:

Configuration:
  status: debug
  packages: com.xyz.x.log

  appenders:
    Console:
      name: LogToConsole
      PatternLayout:
        #Pattern: "%reqId%msg%n"
         Pattern: "%d{YYYY-MM-DD HH:mm:ss.SSS} [%-5level] %C{1} %L - %m%n"
    File:
      name: LogToFile
      PatternLayout:
        Pattern: "%d{YYYY-MM-DD HH:mm:ss.SSS} [%-5level]  %C{1} %L - %m%n"

  Loggers:
    logger:
      - name: com.xyz.x
        level: debug
        additivity: false
        AppenderRef:
          - ref: LogToConsole
          - ref: LogToFile
      - name: org.springframework.security
        level: debug
        additivity: false
        AppenderRef:
          - ref: LogToConsole
          - ref: LogToFile
    Root:
      level: error
      AppenderRef:
        ref: LogToConsole
异常原因

Log4j2的File类型Appender用于将日志输出到磁盘文件,fileName是该Appender的必填配置项,作用是指定日志文件的具体存储路径。
当前配置中LogToFile这个File Appender仅配置了名称和日志输出格式,缺失必填的fileName字段,导致Log4j2初始化Appender插件时检测到非法空值,直接抛出参数无效的异常。

额外提示:当前配置里的日期格式占位符也存在隐性问题:YYYY代表周年、DD代表当年的第几天,不是日常使用的自然年/月内日,会在周跨年、月边界场景打印错误的日期,需要一并修正。

修复方案

在File Appender配置块中补充fileName字段,填写实际需要存储日志的文件路径,同时修正日期格式占位符即可。
修正后的完整配置参考如下:

Configuration:
  status: debug
  packages: com.xyz.x.log

  appenders:
    Console:
      name: LogToConsole
      PatternLayout:
        #Pattern: "%reqId%msg%n"
         Pattern: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] %C{1} %L - %m%n"
    File:
      name: LogToFile
      # 补充必填的日志文件路径,可根据实际部署需求修改路径
      fileName: ./logs/application.log
      PatternLayout:
        Pattern: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level]  %C{1} %L - %m%n"

  Loggers:
    logger:
      - name: com.xyz.x
        level: debug
        additivity: false
        AppenderRef:
          - ref: LogToConsole
          - ref: LogToFile
      - name: org.springframework.security
        level: debug
        additivity: false
        AppenderRef:
          - ref: LogToConsole
          - ref: LogToFile
    Root:
      level: error
      AppenderRef:
        ref: LogToConsole

内容的提问来源于stack exchange,提问作者RYX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 15:15:33