当前位置: 首页 > 知识库问答 >
问题:

如何创建第二个单独的log4j2记录器?

钱元徽
2023-03-14

我试图创建一个完全独立的第二个上下文/配置/记录器-而不是现有配置/上下文中的记录器。日志消息将发送到STDOUT。

当前代码

ConfigurationBuilder<BuiltConfiguration> _configurationBuilder = ConfigurationBuilderFactory.newConfigurationBuilder();
_configurationBuilder.setConfigurationName("SMDR_DEBUG_" + pName);
LoggerContext _loggerContext = new LoggerContext("SMDR_DEBUG_" + pName);
_configurationBuilder.setLoggerContext(_loggerContext);
_configurationBuilder.setStatusLevel(Level.TRACE);


// Create the appender
AppenderComponentBuilder log4jFileAppenderBuilder = _configurationBuilder.
        newAppender(pName + "_SmdrDailyRollingFileAppender", "RollingFile");
log4jFileAppenderBuilder.addAttribute("filename", pLogFilename);
log4jFileAppenderBuilder.addAttribute("filePattern", pLogFilenamePattern);

// Setup roll-over
ComponentBuilder triggeringPolicy = _configurationBuilder.newComponent("Policies")
        .addComponent(_configurationBuilder.newComponent("TimeBasedTriggeringPolicy").
                addAttribute("interval", "1"));
log4jFileAppenderBuilder.addComponent(triggeringPolicy);

// Configure the PatternLayout
LayoutComponentBuilder layoutComponentBuilder = _configurationBuilder.newLayout("PatternLayout").
        addAttribute("pattern", DEBUG_PATTERN_LAYOUT_STRING);
log4jFileAppenderBuilder.add(layoutComponentBuilder);

// Add it back into configuration
_configurationBuilder.add(log4jFileAppenderBuilder);

// https://logging.apache.org/log4j/2.x/manual/customconfig.html
RootLoggerComponentBuilder loggerBuilder = _configurationBuilder.newRootLogger(Level.DEBUG);
loggerBuilder.add(_configurationBuilder.newAppenderRef(pName + "_SmdrDailyRollingFileAppender"));
loggerBuilder.addAttribute("additivity", false);
_configurationBuilder.add(loggerBuilder);

LoggerContext _lc = Configurator.initialize(_configurationBuilder.build());

System.out.println("***** SRJ SRJ SMDR context from initialize is " + _lc);

Logger _g = _loggerContext.getRootLogger();
System.out.println("***** SRJ SRJ SMDR rootlogger from context is " + _g);
_g.error("***** SRJ SRJ ROOT LOGGER IN SMDR_DEBUG.txt");

Logger _gg = _loggerContext.getLogger(pName);
System.out.println("***** SRJ SRJ SMDR logger "+pName+" from context is " + _gg);
_gg.error("***** SRJ SRJ "+pName+" LOGGER IN SMDR_DEBUG.txt");

上面的.error()调用转到标准输出。请注意,我尝试使用reconfigure()而不是initialize(),但这会打乱我的原始配置。

当我打印出来时,记录器似乎是错误的,它们的名称和上下文似乎是正确的,但处于错误级别。还有一些事情要做,不要做附加物。

***** SRJ SRJ SMDR rootlogger from context is :ERROR in SMDR_DEBUG_Global
16:23:59.989 [main] ERROR  - ***** SRJ SRJ ROOT LOGGER IN SMDR_DEBUG.txt   <-- should be in log file
***** SRJ SRJ SMDR logger Global from context is Global:ERROR in SMDR_DEBUG_Global
16:23:59.990 [main] ERROR Global - ***** SRJ SRJ Global LOGGER IN SMDR_DEBUG.txt   <-- should be in log file

从生成器生成的XML:

<?xml version="1.0" ?>
<Configuration name="SMDR_DEBUG_Global" status="TRACE">
    <Appenders>
        <RollingFile name="Global_SmdrDailyRollingFileAppender" filename="ps/debug/SMDR_DEBUG.txt"
                     filePattern="ps/debug/SMDR_DEBUG_%d{yyyyMMdd}.txt.gz">
            <Policies>
                <TimeBasedTriggeringPolicy interval="1"/>
            </Policies>
            <PatternLayout pattern="%d{MM.DD.yy-HH:mm:ss} %m%n"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="DEBUG" additivity="false">
            <AppenderRef ref="Global_SmdrDailyRollingFileAppender"/>
        </Root>
    </Loggers>
</Configuration>

从生成器跟踪:

2022-05-19 16:23:59,921 main DEBUG PluginManager 'Converter' found 45 plugins
2022-05-19 16:23:59,922 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false-3
2022-05-19 16:23:59,940 main INFO Log4j appears to be running in a Servlet environment, but there's no log4j-web module available. If you want better web container support, please add the log4j-web JAR to your web archive or server lib directory.
2022-05-19 16:23:59,941 main DEBUG Apache Log4j Core 2.17.1 initializing configuration org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration@3a3e78f
2022-05-19 16:23:59,942 main DEBUG Installed 1 script engine
2022-05-19 16:23:59,963 Thread Context Data Task DEBUG Initializing Thread Context Data Service Providers
2022-05-19 16:23:59,964 Thread Context Data Task DEBUG Thread Context Data Service Provider initialization complete
2022-05-19 16:23:59,969 main DEBUG Oracle Nashorn version: 1.8.0_252, language: ECMAScript, threading: Not Thread Safe, compile: true, names: [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript], factory class: jdk.nashorn.api.scripting.NashornScriptEngineFactory
2022-05-19 16:23:59,969 main DEBUG PluginManager 'Core' found 127 plugins
2022-05-19 16:23:59,969 main DEBUG PluginManager 'Level' found 0 plugins
2022-05-19 16:23:59,970 main DEBUG PluginManager 'Lookup' found 16 plugins
2022-05-19 16:23:59,970 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2022-05-19 16:23:59,971 main DEBUG createAppenderRef(ref="Global_SmdrDailyRollingFileAppender", level="null", Filter=null)
2022-05-19 16:23:59,971 main DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2022-05-19 16:23:59,972 main DEBUG createLogger(additivity="false", level="DEBUG", includeLocation="null", ={Global_SmdrDailyRollingFileAppender}, ={}, Configuration(SMDR_DEBUG_Global), Filter=null)
2022-05-19 16:23:59,972 main DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2022-05-19 16:23:59,973 main DEBUG createLoggers(={root})
2022-05-19 16:23:59,973 main DEBUG Building Plugin[name=TimeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy].
2022-05-19 16:23:59,975 main DEBUG TimeBasedTriggeringPolicy$Builder(interval="1", modulate="null", maxRandomDelay="null")
2022-05-19 16:23:59,975 main DEBUG Building Plugin[name=Policies, class=org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy].
2022-05-19 16:23:59,975 main DEBUG createPolicy(={TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false)})
2022-05-19 16:23:59,975 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2022-05-19 16:23:59,976 main DEBUG PatternLayout$Builder(pattern="%d{MM.DD.yy-HH:mm:ss} %m%n", PatternSelector=null, Configuration(SMDR_DEBUG_Global), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2022-05-19 16:23:59,976 main DEBUG PluginManager 'Converter' found 45 plugins
2022-05-19 16:23:59,982 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.RollingFileAppender].
2022-05-19 16:23:59,983 main DEBUG RollingFileAppender$Builder(fileName="ps/debug/SMDR_DEBUG.txt", filePattern="ps/debug/SMDR_DEBUG_%d{yyyyMMdd}.txt.gz", append="null", locking="null", Policies(CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false)])), Strategy=null, advertise="null", advertiseUri="null", createOnDemand="null", filePermissions="null", fileOwner="null", fileGroup="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d{MM.DD.yy-HH:mm:ss} %m%n), name="Global_SmdrDailyRollingFileAppender", Configuration(SMDR_DEBUG_Global), Filter=null, ={})
2022-05-19 16:23:59,984 main TRACE New file 'ps/debug/SMDR_DEBUG.txt' created = true
2022-05-19 16:23:59,984 main DEBUG Returning file creation time for /opt/SecureLogix/ETM/ps/debug/SMDR_DEBUG.txt
2022-05-19 16:23:59,984 main DEBUG Starting RollingFileManager ps/debug/SMDR_DEBUG.txt
2022-05-19 16:23:59,985 main DEBUG PluginManager 'FileConverter' found 2 plugins
2022-05-19 16:23:59,985 main DEBUG Setting prev file time to 2022-05-19T16:23:59.000+0100
2022-05-19 16:23:59,985 main DEBUG Initializing triggering policy CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false)])
2022-05-19 16:23:59,986 main DEBUG Initializing triggering policy TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=1, modulate=false)
2022-05-19 16:23:59,987 main TRACE PatternProcessor.getNextTime returning 2022/05/20-00:00:00.000, nextFileTime=2022/05/19-00:00:00.000, prevFileTime=1970/01/01-01:00:00.000, current=2022/05/19-16:23:59.986, freq=DAILY
2022-05-19 16:23:59,988 main TRACE PatternProcessor.getNextTime returning 2022/05/20-00:00:00.000, nextFileTime=2022/05/19-00:00:00.000, prevFileTime=2022/05/19-00:00:00.000, current=2022/05/19-16:23:59.988, freq=DAILY
2022-05-19 16:23:59,988 main DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2022-05-19 16:23:59,988 main DEBUG createAppenders(={Global_SmdrDailyRollingFileAppender})
2022-05-19 16:23:59,989 main DEBUG Configuration org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration@3a3e78f initialized

共有1个答案

晋承运
2023-03-14

你的问题来自这一行:

LoggerContext _lc = Configurator.initialize(_configurationBuilder.build());

配置程序。initialize方法检索与当前代码相关联的记录器上下文(请参阅ContextSelector),并使用给定的配置对其进行配置。这与loggerContext不同,loggerContext未初始化并使用默认配置(控制台上的错误)。

要配置loggerContext,请使用:

_loggerContext.setConfiguration(_configurationBuilder.build());
 类似资料:
  • 我需要支持将特定包登录到聊天中。将错误记录到错误中。日志如何做到这一点?到目前为止,我在几个appender中创建了阈值过滤器,但出现了错误。日志保持为空并进行聊天。日志有一个条目,它不属于特定的包。毕竟,我仔细阅读了log4j的文档,也尝试了2天来解决这个问题,并在网站和youtube上学习了一些教程。我还尝试了以下方法:使用Log4j2进行apachelog4j2包特定的日志记录。xml我也尝

  • 因此,我希望以编程方式创建单独的appender和单独的logger,以便每个appender只附加到它自己的线程,然后在一个线程中创建的logger只在该线程中创建appender。 请让我知道如何一步步实现。

  • ,日志记录将进入一个文件; (路径)/service_name/service_name.log 我想用logback复制这种行为,但在logback.xml配置中获取“logger”名称时遇到了真正的困难。它可以在log encoder.pattern中看到,即“%d%-5level%logger{35}-%msg%n”。

  • 我定义了多个记录器,如下所示(com.xyz和org.xyz)。Log4j2忽略了第一个记录器定义,只加载第二个。在示例中,org.xyz未加载。 在log4j2调试消息下方查找。 我的配置正确吗?

  • 问题内容: 我在应用程序中使用log4j2。 我想要的是将要进行调试的所有内容都放入控制台,将要进行“信息”的所有内容都进入myapp.log,仅将“信息”的所有内容都进入“ myapp- audit.log”。 原因是,INFO主要由成功的数据修改组成(例如,“用户创建”,“用户更新”,“用户删除”等)。如果有效,则为数据修改的审核日志。 但是我不知道该怎么做。 如何仅获取“信息”以登录到“ m

  • 我使用带有路由附加器和包装器的log4j2xml配置。我将传递不同的appender,以记录项目不同部分的不同文件。我的配置看起来像这样。 问题是,我在第二个路由中获得了外部库日志(那些没有附加程序的)和我的项目日志,尽管我只想要外部日志。