slf4j logger多次使用logback日志,具体取决于线程数

时间:2017-07-05 01:26:18

标签: multithreading logback slf4j sifting-appender

我正在使用Spring。当请求来自控制器时,我会在这些线程中创建多个线程并记录内容。但是,第二个线程的内容记录2次,第三个线程记录3次,依此类推。

如果线程为async,则可能会在所有日志文件中多次写入。

另外,在停止Tomcat之前,我无法删除日志文件。

以下是我的代码:

LogUtil.java

public class LogUtil {


    public static Marker getMarker() {
        Marker marker = MarkerFactory.getMarker("Finalize");
        marker.add(ClassicConstants.FINALIZE_SESSION_MARKER);
        return marker;
    }

    public static void addSiftingAppender(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("batch0");
        discriminator.start();

        sa.setDiscriminator(discriminator);

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

            @Override
            public Appender<ILoggingEvent> buildAppender(Context context,
                    String discriminatingValue) throws JoranException {
                FileAppender<ILoggingEvent> appender = new FileAppender<ILoggingEvent>();
                appender.setName("BATCH-EXECUTION-" + discriminatingValue);
                appender.setContext(context);
                appender.setFile(discriminatingValue + ".log");
                appender.setAppend(true);
                if (appender.isStarted()) {
                    appender.stop();
                }

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

                appender.start();
                return appender;
            }
        });
        if (sa.isStarted()) {
            sa.stop();
        }
        sa.start();
        logger.addAppender(sa);
    }

}

Head.java

public class Head implements Runnable {

    // static Logger logger = LoggerFactory.getLogger(Head.class);

    private Logger log;

    private String name;

    Head(Logger logger, String name) {
        this.log = logger;
        this.name = name;
    }

    @Override
    public void run() {
        LogUtil.addSiftingAppender(log);
        MDC.put("logFileName", getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        log.info("something" + getName());
        log.info(LogUtil.getMarker(), "ended");
        MDC.remove("logFileName");

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setLogger(Logger log) {
        this.log = log;
    }

}

IfxDesignerController

@Slf4j
public class IfxDesignerController{

 @RequestMapping(value = "/testsomething", method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String
            testsomething()
                    throws IllegalStateException, IOException {

        ExecutorService executor = Executors.newCachedThreadPool();

        int count2 = 1;
        while (count2 <= 2) {
            Head head = new Head(log, "somename" + count2);
            head.setName("head-nested" + count2);
            head.setLogger(log);
            executor.execute(head);
            count2++;
        }
        return null;
    }

}

GET发出testsomething请求时生成的日志文件如下:

头nested1.log

10:15:50.869 [pool-217-thread-1] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - somethinghead-nested1
10:15:50.869 [pool-217-thread-1] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - somethinghead-nested1
10:15:50.887 [pool-217-thread-1] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - ended
10:15:50.887 [pool-217-thread-1] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - ended

头nested2.log

10:15:50.955 [pool-217-thread-2] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - somethinghead-nested2
10:15:50.955 [pool-217-thread-2] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - somethinghead-nested2
10:15:50.957 [pool-217-thread-2] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - ended
10:15:50.957 [pool-217-thread-2] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - ended

我应该在logback配置中做出哪些更改,以便输出如下(Desired Output):

头nested1.log

10:15:50.869 [pool-217-thread-1] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - somethinghead-nested1
10:15:50.887 [pool-217-thread-1] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - ended

头nested2.log

10:15:50.955 [pool-217-thread-2] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - somethinghead-nested2
10:15:50.957 [pool-217-thread-2] INFO  c.w.c.h.c.c.i.d.IfxDesignerController - ended

此外,我应该能够在执行线程后删除日志文件

0 个答案:

没有答案