gpt4 book ai didi

java - 以编程方式设置 Logback Appender 路径

转载 作者:太空狗 更新时间:2023-10-29 22:31:16 27 4
gpt4 key购买 nike

我正在尝试以编程方式设置 Logback appender 路径。 (RollingFileAppender 与 FixedWindowRollingPolicy 是准确的)

我这样做是因为我想让我的用户能够在首选项对话框 (Eclipse RCP) 中设置日志路径

我试过类似的方法,但我没有更改配置文件中定义的日志路径:

Logger logback_logger = (ch.qos.logback.classic.Logger)LoggerFactory
.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
RollingFileAppender<ILoggingEvent> rfappender =
(RollingFileAppender<ILoggingEvent>)logback_logger.getAppender("FILE");
rfappender.setFile(newFile);
FixedWindowRollingPolicy rollingPolicy =
(FixedWindowRollingPolicy)rfappender.getRollingPolicy();
rollingPolicy.setFileNamePattern(newPattern);

最佳答案

一旦您以编程方式配置了您的 appender,您需要调用它的 start() 方法。如果 appender 有子组件,首先在子组件上调用 start()。然后将附加程序添加到您选择的记录器中。

这是一个例子:

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;

public class Main {
public static void main(String[] args) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

RollingFileAppender rfAppender = new RollingFileAppender();
rfAppender.setContext(loggerContext);
rfAppender.setFile("testFile.log");
FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
rollingPolicy.setContext(loggerContext);
// rolling policies need to know their parent
// it's one of the rare cases, where a sub-component knows about its parent
rollingPolicy.setParent(rfAppender);
rollingPolicy.setFileNamePattern("testFile.%i.log.zip");
rollingPolicy.start();

SizeBasedTriggeringPolicy triggeringPolicy = new ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy();
triggeringPolicy.setMaxFileSize("5MB");
triggeringPolicy.start();

PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(loggerContext);
encoder.setPattern("%-4relative [%thread] %-5level %logger{35} - %msg%n");
encoder.start();

rfAppender.setEncoder(encoder);
rfAppender.setRollingPolicy(rollingPolicy);
rfAppender.setTriggeringPolicy(triggeringPolicy);

rfAppender.start();

// attach the rolling file appender to the logger of your choice
Logger logbackLogger = loggerContext.getLogger("Main");
logbackLogger.addAppender(rfAppender);

// OPTIONAL: print logback internal status messages
StatusPrinter.print(loggerContext);

// log something
logbackLogger.debug("hello");
}
}

以上代码是 logback 的 XML 配置器(即 Joran)在解析 RollingFixedWindow.xml 时采取的步骤的编程表达式。文件。

关于java - 以编程方式设置 Logback Appender 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3803184/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com