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

如何在Log4j 2.0.1中集成程序化配置并满足指定日志需求?

Log4j 2.0.1 Configuration for Your Exact Needs

Got it, let's work through this since you can't upgrade Log4j due to company policies. I've put together a tailored XML configuration that covers all your requirements: dynamic debug logging based on the customDebug environment variable, two separate log files, and size-based rolling. Here's what you need:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <!-- Define appenders for main and error logs -->
    <Appenders>
        <!-- Main log: captures INFO/DEBUG (based on env var) with size rolling -->
        <RollingFile name="MainLog" fileName="logs/app-main.log"
                     filePattern="logs/app-main-%i.log.gz">
            <!-- Filter logic: allow DEBUG only if customDebug is true -->
            <ScriptFilter>
                <Script language="JavaScript">
                    const debugEnabled = System.getenv("customDebug") === "true";
                    const logLevel = logEvent.getLevel();
                    return debugEnabled ? logLevel.isMoreSpecificThan(Level.DEBUG) : logLevel.isMoreSpecificThan(Level.INFO);
                </Script>
            </ScriptFilter>
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
            <!-- Size-based rolling: roll when file hits 10MB, keep up to 5 compressed backups -->
            <SizeBasedTriggeringPolicy size="10MB"/>
            <DefaultRolloverStrategy max="5"/>
        </RollingFile>

        <!-- Error log: only captures ERROR/FATAL logs with size rolling -->
        <RollingFile name="ErrorLog" fileName="logs/app-error.log"
                     filePattern="logs/app-error-%i.log.gz">
            <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
            <SizeBasedTriggeringPolicy size="10MB"/>
            <DefaultRolloverStrategy max="5"/>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Root level="ALL">
            <AppenderRef ref="MainLog"/>
            <AppenderRef ref="ErrorLog"/>
        </Root>
    </Loggers>
</Configuration>

Key Breakdown:

  • Dynamic Debug Toggle: The ScriptFilter in the main log appender checks the customDebug environment variable. If set to true, it allows DEBUG and all higher levels; if not, it only lets through INFO and above.
  • Main Log Behavior: Rolls over to a new compressed file once it reaches 10MB, keeping up to 5 backup files to avoid disk bloat.
  • Error Log Isolation: This appender only captures ERROR and FATAL logs, with the same size-based rolling rules as the main log—so you can troubleshoot issues without sifting through routine logs.
  • Dependency Check: Double-check your build config includes both log4j-core and log4j-api 2.0.1 (as you specified) since this config relies on both modules.

Quick Usage Tip:

To enable debug logging, set the environment variable before starting your app:

  • Linux/macOS: export customDebug=true
  • Windows (Command Prompt): set customDebug=true
  • Windows (PowerShell): $env:customDebug = "true"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:15:11