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

在日志中动态添加Appender

司空昊阳
2023-03-14
package com.worksap.company.hue.com.bizcore.outputengine.devtools;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.sift.MDCBasedDiscriminator;
import ch.qos.logback.classic.sift.SiftingAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.core.sift.AppenderFactory;

public class Utils {

    public static Logger putNewAppender(String file, org.slf4j.Logger log) {

        LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
        Logger logger = lc.getLogger(log.getName());
        SiftingAppender sa = new SiftingAppender();
        sa.setName("SIFT");
        sa.setContext(lc);

        MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator();
        discriminator.setKey("logFileName");
        discriminator.setDefaultValue("head0");
        discriminator.start();

        sa.setDiscriminator(discriminator);

        sa.setAppenderFactory(new AppenderFactory<ILoggingEvent>() {

            @Override
            public Appender<ILoggingEvent> buildAppender(Context context, String discriminatingValue)
                    throws JoranException {
                RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
                appender.setName("ROLLINGFILE-" + discriminatingValue);
                appender.setContext(context);
                appender.setFile(discriminatingValue + ".log");

                TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<>();
                policy.setContext(context);
                policy.setMaxHistory(5);
                policy.setFileNamePattern(discriminatingValue + "-%d{yyyy-MM-dd-HH-mm}-%i.log.gz");
                policy.setParent(appender);
                policy.start();

                SizeAndTimeBasedFNATP<ILoggingEvent> innerpolicy = new SizeAndTimeBasedFNATP<>();
                innerpolicy.setContext(context);
                innerpolicy.setMaxFileSize("512KB");
                innerpolicy.setTimeBasedRollingPolicy(policy);
                innerpolicy.start();

                policy.setTimeBasedFileNamingAndTriggeringPolicy(innerpolicy);
                policy.start();

                appender.setRollingPolicy(policy);

                PatternLayoutEncoder pl = new PatternLayoutEncoder();
                pl.setContext(context);
                pl.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
                pl.start();
                appender.setEncoder(pl);

                appender.start();
                return appender;
            }
        });

        sa.start();
        logger.addAppender(sa);
        logger.setAdditive(false);

        return logger;

    }
}
@Slf4j
public class IfxOutputJobToolTest {

    @Test
    public void outputTest() throws Exception {

        Logger logger2 = Utils.putNewAppender("C:\\Users\\works\\Downloads\\somename", log);
        MDC.put("logFileName", "somename");
        logger2.info("something is getting logged");
        logger2.error("somerghing");
        logger2.warn("somrgklsajg");
        logger2.debug("ser");
        MDC.remove("logFileName");

        LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
        for (ch.qos.logback.classic.Logger logger3 : context.getLoggerList()) {
            for (Iterator<Appender<ILoggingEvent>> index = logger3.iteratorForAppenders(); index.hasNext();) {
                Appender<ILoggingEvent> appender = index.next();
                System.out.println(appender);
            }
        }
    }
}
ch.qos.logback.classic.sift.SiftingAppender[SIFT]
ch.qos.logback.core.ConsoleAppender[CONSOLE]
ch.qos.logback.core.ConsoleAppender[CONSOLE]
ch.qos.logback.core.ConsoleAppender[CONSOLE_SPRING]
16:40:08,943 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use gz compression
16:40:08,946 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern somename-%d{yyyy-MM-dd-HH-mm}-%i.log for the active file
16:40:08,956 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - The date pattern is 'yyyy-MM-dd-HH-mm' from file name pattern 'somename-%d{yyyy-MM-dd-HH-mm}-%i.log.gz'.
16:40:08,956 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Roll-over every minute.
16:40:08,957 |-INFO in c.q.l.core.rolling.DefaultTimeBasedFileNamingAndTriggeringPolicy - Setting initial period to Tue Jun 06 16:35:47 JST 2017
16:40:08,962 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@77a4bac - The date pattern is 'yyyy-MM-dd-HH-mm' from file name pattern 'somename-%d{yyyy-MM-dd-HH-mm}-%i.log.gz'.
16:40:08,962 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@77a4bac - Roll-over every minute.
16:40:08,962 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@77a4bac - Setting initial period to Tue Jun 06 16:35:47 JST 2017
16:40:08,964 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use gz compression
16:40:08,964 |-INFO in c.q.l.core.rolling.TimeBasedRollingPolicy - Will use the pattern somename-%d{yyyy-MM-dd-HH-mm}-%i.log for the active file
16:40:08,965 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@77a4bac - The date pattern is 'yyyy-MM-dd-HH-mm' from file name pattern 'somename-%d{yyyy-MM-dd-HH-mm}-%i.log.gz'.
16:40:08,966 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@77a4bac - Roll-over every minute.
16:40:08,966 |-INFO in ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP@77a4bac - Setting initial period to Tue Jun 06 16:35:47 JST 2017
16:40:08,969 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[ROLLINGFILE-somename] - Active log file name: somename.log
16:40:08,969 |-INFO in ch.qos.logback.core.rolling.RollingFileAppender[ROLLINGFILE-somename] - File property is set to [somename.log]
16:40:08,975 |-INFO in c.q.l.co.rolling.helper.RenameUtil - Renaming file [somename.log] to [somename.log91512733365898.tmp]
16:40:08,979 |-INFO in ch.qos.logback.core.rolling.helper.SizeAndTimeBasedArchiveRemover@96be1ae - first clean up after appender initialization
16:40:08,979 |-INFO in ch.qos.logback.core.rolling.helper.SizeAndTimeBasedArchiveRemover@96be1ae - periodsElapsed = 336
16:40:08,979 |-INFO in ch.qos.logback.core.rolling.helper.Compressor - GZ compressing [somename.log91512733365898.tmp] as [somename-2017-06-06-16-35-0.log.gz]

编辑

删除这一行logger.setAdditive(false);后,将在控制台上打印日志。但是,我看不到正在创建的文件。

共有1个答案

田鸿彩
2023-03-14

看起来你在appender工厂中构建appender的方式有些问题。不确定,确切的问题是什么,但我尝试了下面的代码,它起作用了。`

sa.setAppenderFactory(new AppenderFactory(){

                 public Appender<ILoggingEvent> buildAppender(Context context, String discriminatingValue)
                         throws JoranException {
                     PatternLayoutEncoder ple = new PatternLayoutEncoder();

                    ple.setPattern("%date [%thread] [%file:%line] %msg%n");
                    ple.setContext(context);
                    ple.start();


                    RollingFileAppender<ILoggingEvent> logFileAppender = new RollingFileAppender();
                            logFileAppender.setContext(context);
                            logFileAppender.setName("File-"+discriminatingValue);
                            logFileAppender.setEncoder(ple);
                            logFileAppender.setFile(filename+"-"+discriminatingValue+".txt");

                            SizeAndTimeBasedRollingPolicy<ILoggingEvent> logFilePolicy = new SizeAndTimeBasedRollingPolicy();
                            logFilePolicy.setContext(context);
                            logFilePolicy.setParent(logFileAppender);
                            logFilePolicy.setFileNamePattern(filename+"-"+discriminatingValue+"-%d{yyyy-MM-dd}.%i.txt");
                            logFilePolicy.setMaxHistory(5);
                            logFilePolicy.setMaxFileSize(FileSize.valueOf("512kb"));
                            logFilePolicy.setTotalSizeCap(FileSize.valueOf("1gb"));
                            logFilePolicy.start();

                            logFileAppender.setRollingPolicy(logFilePolicy);
                            logFileAppender.start();

                          logFileAppender.start();
                     return logFileAppender;
                 }
             });

`

 类似资料:
  • 我试着在附加程序上操作级别过滤器,但似乎没有太大作用

  • 问题内容: 我知道我可以通过执行以下操作来向对象动态添加实例方法: 稍后我可以打电话给我,自我将被正确绑定,一切正常。 现在,我的问题是:如何做完全相同的事情来获得用@property装饰新方法的行为? 我猜是这样的: 但是,这样做会返回一个属性对象。 问题答案: 在描述对象需要住 类 , 未 在 实例中 ,有你想要的效果。如果您不想更改现有的类以避免更改其他实例的行为,则需要创建“每个实例的类”

  • 问题内容: 如何在jpanel中动态添加组件?当我单击按钮时,我应该有添加按钮,组件应该添加到JPanel。 我的问题是,当我单击添加按钮时,将文本字段和按钮添加到jpanel时,用户可以根据需要将它们添加到jpanel中的任意次数单击添加按钮。我已将scrollerpane添加到我的jpanel,并且jpanel布局管理器设置为null。 问题答案: 像往常一样,除了必须调用: 完成后,因为容器

  • 问题内容: 在我的应用程序中,组件必须动态更改。我有一个数据表,其中我有两列,首先是菜单中的a我有两个数据(数据分别为1和2),如果选择了1,则应出现a,如果选择了2,则应出现。需要帮助吗? 我的JSF 我的豆类 问题答案: 我的建议是:不要动态添加/删除组件。用另一种方法解决您的问题: 切换组件的 可见性 重新绑定属于组件的 数据 动态添加/删除组件始终是麻烦的源头,而且您有可能以另一种简单得多

  • 我正在尝试构建一个在JavaFX中实现群聊的聊天应用程序。我想在边框窗格内创建一个滚动窗格,该窗格将包含用户所属的所有组。当用户加入时,需要将组图标(ImageViews)动态添加(在场景生成器中无法完成)到滚动窗格(在HBox内)。 目前,我正在使用一个SceneController类,该类负责所有阶段和场景更改。 我已经创建了一个FXML文件(使用场景生成器),其中包含一个边框窗格和一个滚动窗

  • 我目前正在开发一个图像编辑器应用程序。我试图在我的应用程序中提供一个选项来处理不同的层,比如GIMP或Photoshop。我的方法是为用户添加的每个层添加一个。一切都很好,但不知怎么的,我动态添加的画布没有出现。 在我的类构造函数中,我添加了1个通用画布,它包含一个背景图像,不能编辑。这个画布(它是全球性的)确实显示出来并正常工作。所有可以编辑的层都存储在