spring amqp log4j2 logger thread无声地死掉

时间:2017-10-18 15:25:19

标签: java logging rabbitmq log4j2 spring-amqp

修改

问题实际上是在现有的应用程序中,而不是在日志记录sytsem中。 如果有人正在寻找一个例子,我在这里发布的代码正在运作。

原始

我必须将现有的java8应用程序集成到一个高效的环境中。一个要求是将所有错误日志附加到现有(并且高效工作)RabbitMQ。应用程序使用slf4j和log4j2进行日志记录。

要将消息附加到RabbitMQ,我使用了org.springframework.amqp:spring-rabbit,消息将在正确的交换和发布中发布。然而,队列中记录消息的线程会以静默方式死掉,整个java进程之后就不会退出。

我创建了一个稍微简单的示例来重新创建问题。

的build.gradle

group 'logtest'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'maven'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}
ext {
    slf4jVersion = '1.7.25'
}
configurations.all {
    exclude module: 'slf4j-log4j12'
}
dependencies {
    compile("org.slf4j:slf4j-api:$slf4jVersion")
    compile group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.9.1'
    compile group: 'com.lmax', name: 'disruptor', version: '3.3.4'

    compile('org.springframework.amqp:spring-amqp:2.0.0.RELEASE') {
        exclude group: 'org.springframework', module: 'spring-core'
    }
    compile 'org.springframework.amqp:spring-rabbit:2.0.0.RELEASE'
}

task buildLogTest(type: Jar) {
    manifest {
        attributes 'Implementation-Title': 'LogTest',
                'Implementation-Version': 1.0,
                'Main-Class': 'LogTest'
    }
    baseName = 'LogTest'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

LogTest.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogTest {
    public static void main(String... args) throws InterruptedException {
        Logger log = LoggerFactory.getLogger(LogTest.class);

        Thread t = new Thread(()->{
            log.trace("trace");
            log.debug("debug");
            log.info("info");
            log.warn("warn");
            log.error("error");
            log.trace("trace");
        });

        t.setName("bg_logger");
        t.setDaemon(true);
        t.start();

        Thread.sleep(1000 * 60);
    }
}

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
<Appenders>
    <RollingFile name="RollingFile">
        <FileName>log_file.log</FileName>
        <FilePattern>log/time-based-logs/%d{yyyy-MM-dd}.log.zip</FilePattern>
        <PatternLayout pattern="%d %-5p [%t] %C (%F:%L) - %m%n"/>
        <Policies>
            <TimeBasedTriggeringPolicy interval="2" modulate="true" />
        </Policies>
        <DefaultRolloverStrategy max="5" />
    </RollingFile>
    <Console name="STDOUT" target="SYSTEM_OUT">
        <PatternLayout pattern="%d %-5p %C{2} - %m%n"/>
    </Console>
    <RabbitMQ name="rabbitmq"
              addresses="host.local:5672"
              user="panoptesLogAgent"
              password="password"
              virtualHost="lab"
              exchange="LogExchange"
              applicationId="panoptesAutoSegmentation"
              routingKeyPattern="Critical"
              contentType="text/plain"
              contentEncoding="UTF-8"
              generateId="false"
              deliveryMode="NON_PERSISTENT"
              exchangeType="direct"
              charset="UTF-8"
              senderPoolSize="1" maxSenderRetries="1">
        <PatternLayout pattern="%d %-5p [%t] %C (%F:%L) - %m%n"/>
    </RabbitMQ>
</Appenders>
<Loggers>
    <AsyncLogger name="asyncRabbitMQ" level="trace" includeLocation="true">
        <AppenderRef ref="rabbitmq"/>
    </AsyncLogger>
    <Root level="trace">
        <AppenderRef ref="rabbitmq" level="ERROR"/>
        <AppenderRef ref="RollingFile" level="DEBUG"/>
        <AppenderRef ref="STDOUT" level="INFO"/>
    </Root>
</Loggers>
</Configuration>

STDOUT记录器的输出示例:

2017-10-18 16:49:16,986 main DEBUG Initializing configuration XmlConfiguration[location=C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml]
2017-10-18 16:49:16,986 main DEBUG Installed 1 script engine
2017-10-18 16:49:17,376 main DEBUG Oracle Nashorn version: 1.8.0_131, language: ECMAScript, threading: Not Thread Safe, compile: true, names: [nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript], factory class: jdk.nashorn.api.scripting.NashornScriptEngineFactory
2017-10-18 16:49:17,376 main DEBUG PluginManager 'Core' found 116 plugins
2017-10-18 16:49:17,376 main DEBUG PluginManager 'Level' found 0 plugins
2017-10-18 16:49:17,376 main DEBUG PluginManager 'Lookup' found 13 plugins
2017-10-18 16:49:17,376 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2017-10-18 16:49:17,392 main DEBUG PluginManager 'TypeConverter' found 26 plugins
2017-10-18 16:49:17,408 main DEBUG PatternLayout$Builder(pattern="%d %-5p [%t] %C (%F:%L) - %m%n", PatternSelector=null, Configuration(C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2017-10-18 16:49:17,408 main DEBUG PluginManager 'Converter' found 42 plugins
2017-10-18 16:49:17,423 main DEBUG Building Plugin[name=TimeBasedTriggeringPolicy, class=org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy].
2017-10-18 16:49:17,439 main DEBUG TimeBasedTriggeringPolicy$Builder(interval="2", modulate="true", maxRandomDelay="null")
2017-10-18 16:49:17,439 main DEBUG Building Plugin[name=Policies, class=org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy].
2017-10-18 16:49:17,439 main DEBUG createPolicy(={TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=2, modulate=true)})
2017-10-18 16:49:17,439 main DEBUG Building Plugin[name=DefaultRolloverStrategy, class=org.apache.logging.log4j.core.appender.rolling.DefaultRolloverStrategy].
2017-10-18 16:49:17,439 main DEBUG DefaultRolloverStrategy$Builder(max="5", min="null", fileIndex="null", compressionLevel="null", ={}, stopCustomActionsOnError="null", tempCompressedFilePattern="null", Configuration(C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml))
2017-10-18 16:49:17,439 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.RollingFileAppender].
2017-10-18 16:49:17,454 main DEBUG RollingFileAppender$Builder(fileName="panoptes.log", filePattern="log/time-based-logs/%d{yyyy-MM-dd}.log.zip", append="null", locking="null", Policies(CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=2, modulate=true)])), DefaultRolloverStrategy(DefaultRolloverStrategy(min=1, max=5, useMax=true)), advertise="null", advertiseUri="null", createOnDemand="null", filePermissions="null", fileOwner="null", fileGroup="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d %-5p [%t] %C (%F:%L) - %m%n), name="RollingFile", Configuration(C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml), Filter=null)
2017-10-18 16:49:17,454 main DEBUG Starting RollingFileManager panoptes.log
2017-10-18 16:49:17,470 main DEBUG PluginManager 'FileConverter' found 2 plugins
2017-10-18 16:49:17,470 main DEBUG Setting prev file time to 2017-10-18T16:49:17.454+0200
2017-10-18 16:49:17,470 main DEBUG Initializing triggering policy CompositeTriggeringPolicy(policies=[TimeBasedTriggeringPolicy(nextRolloverMillis=0, interval=2, modulate=true)])
2017-10-18 16:49:17,470 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2017-10-18 16:49:17,470 main DEBUG PatternLayout$Builder(pattern="%d %-5p %C{2} - %m%n", PatternSelector=null, Configuration(C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2017-10-18 16:49:17,470 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
2017-10-18 16:49:17,470 main DEBUG ConsoleAppender$Builder(target="SYSTEM_OUT", follow="null", direct="null", bufferedIo="null", bufferSize="null", immediateFlush="null", ignoreExceptions="null", PatternLayout(%d %-5p %C{2} - %m%n), name="STDOUT", Configuration(C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml), Filter=null)
2017-10-18 16:49:17,470 main DEBUG Jansi is not installed, cannot find org.fusesource.jansi.WindowsAnsiOutputStream
2017-10-18 16:49:17,470 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
2017-10-18 16:49:17,470 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2017-10-18 16:49:17,470 main DEBUG PatternLayout$Builder(pattern="%d %-5p [%t] %C (%F:%L) - %m%n", PatternSelector=null, Configuration(C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", disableAnsi="null", noConsoleNoAnsi="null", header="null", footer="null")
2017-10-18 16:49:17,470 main DEBUG Building Plugin[name=appender, class=org.springframework.amqp.rabbit.log4j2.AmqpAppender].
2017-10-18 16:49:17,486 main DEBUG createAppender(Configuration(C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml), name="rabbitmq", PatternLayout(%d %-5p [%t] %C (%F:%L) - %m%n), Filter=null, ignoreExceptions="false", uri="null", host="null", port="null", addresses="host.local:5672", user="panoptesLogAgent", password="password", virtualHost="lab", useSsl="false", sslAlgorithm="null", sslPropertiesLocation="null", keyStore="null", keyStorePassphrase="null", keyStoreType="null", trustStore="null", trustStorePassphrase="null", trustStoreType="null", senderPoolSize="1", maxSenderRetries="1", applicationId="panoptesAutoSegmentation", routingKeyPattern="Critical", generateId="false", deliveryMode="NON_PERSISTENT", exchange="LogExchange", exchangeType="direct", declareExchange="false", durable="false", autoDelete="false", contentType="text/plain", contentEncoding="UTF-8", clientConnectionProperties="null", async="false", charset="UTF-8")
2017-10-18 16:49:17,486 main DEBUG Starting AmqpManager rabbitmq
2017-10-18 16:49:17,658 main DEBUG Not in a ServletContext environment, thus not loading WebLookup plugin.
2017-10-18 16:49:17,658 main DEBUG PluginManager 'Converter' found 42 plugins
2017-10-18 16:49:17,658 main DEBUG Jansi is not installed, cannot find org.fusesource.jansi.WindowsAnsiOutputStream
2017-10-18 16:49:17,658 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false-2
2017-10-18 16:49:17,704 main DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2017-10-18 16:49:17,704 main DEBUG createAppenders(={RollingFile, STDOUT, rabbitmq})
2017-10-18 16:49:17,704 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2017-10-18 16:49:17,704 main DEBUG createAppenderRef(ref="rabbitmq", level="null", Filter=null)
2017-10-18 16:49:17,704 main DEBUG Building Plugin[name=asyncLogger, class=org.apache.logging.log4j.core.async.AsyncLoggerConfig].
2017-10-18 16:49:17,704 main DEBUG createLogger(additivity="null", level="trace", name="asyncRabbitMQ", includeLocation="true", ={rabbitmq}, ={}, Configuration(C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml), Filter=null)
2017-10-18 16:49:17,704 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2017-10-18 16:49:17,704 main DEBUG createAppenderRef(ref="rabbitmq", level="ERROR", Filter=null)
2017-10-18 16:49:17,704 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2017-10-18 16:49:17,704 main DEBUG createAppenderRef(ref="RollingFile", level="DEBUG", Filter=null)
2017-10-18 16:49:17,720 main DEBUG Building Plugin[name=AppenderRef, class=org.apache.logging.log4j.core.config.AppenderRef].
2017-10-18 16:49:17,720 main DEBUG createAppenderRef(ref="STDOUT", level="INFO", Filter=null)
2017-10-18 16:49:17,720 main DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2017-10-18 16:49:17,720 main DEBUG createLogger(additivity="null", level="TRACE", includeLocation="null", ={rabbitmq, RollingFile, STDOUT}, ={}, Configuration(C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml), Filter=null)
2017-10-18 16:49:17,720 main DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2017-10-18 16:49:17,720 main DEBUG createLoggers(={asyncRabbitMQ, root})
2017-10-18 16:49:17,720 main DEBUG Configuration XmlConfiguration[location=C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml] initialized
2017-10-18 16:49:17,720 main DEBUG Starting configuration XmlConfiguration[location=C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml]
2017-10-18 16:49:17,767 main DEBUG Starting AsyncLoggerConfig disruptor for this configuration with ringbufferSize=4096, waitStrategy=TimeoutBlockingWaitStrategy, exceptionHandler=org.apache.logging.log4j.core.async.AsyncLoggerConfigDefaultExceptionHandler@f5f7f...
2017-10-18 16:49:17,767 main DEBUG Started configuration XmlConfiguration[location=C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml] OK.
2017-10-18 16:49:17,767 main DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
2017-10-18 16:49:17,767 main DEBUG Shut down OutputStreamManager SYSTEM_OUT.false.false-1, all resources released: true
2017-10-18 16:49:17,767 main DEBUG Appender DefaultConsole-1 stopped with status true
2017-10-18 16:49:17,767 main DEBUG Stopped org.apache.logging.log4j.core.config.DefaultConfiguration@2e1f26 OK
2017-10-18 16:49:17,829 main DEBUG Registering MBean org.apache.logging.log4j2:type=b4aac2
2017-10-18 16:49:17,829 main DEBUG Registering MBean org.apache.logging.log4j2:type=b4aac2,component=StatusLogger
2017-10-18 16:49:17,829 main DEBUG Registering MBean org.apache.logging.log4j2:type=b4aac2,component=ContextSelector
2017-10-18 16:49:17,829 main DEBUG Registering MBean org.apache.logging.log4j2:type=b4aac2,component=Loggers,name=
2017-10-18 16:49:17,829 main DEBUG Registering MBean org.apache.logging.log4j2:type=b4aac2,component=Loggers,name=asyncRabbitMQ
2017-10-18 16:49:17,829 main DEBUG Registering MBean org.apache.logging.log4j2:type=b4aac2,component=Loggers,name=asyncRabbitMQ,subtype=RingBuffer
2017-10-18 16:49:17,829 main DEBUG Registering MBean org.apache.logging.log4j2:type=b4aac2,component=Appenders,name=STDOUT
2017-10-18 16:49:17,829 main DEBUG Registering MBean org.apache.logging.log4j2:type=b4aac2,component=Appenders,name=rabbitmq
2017-10-18 16:49:17,829 main DEBUG Registering MBean org.apache.logging.log4j2:type=b4aac2,component=Appenders,name=RollingFile
2017-10-18 16:49:17,829 main DEBUG Reconfiguration complete for context[name=b4aac2] at URI C:\Users\marek.arnold\IdeaProjects\logtest\build\resources\main\log4j2.xml (org.apache.logging.log4j.core.LoggerContext@156d4d4) with optional ClassLoader: null
2017-10-18 16:49:17,829 main DEBUG Shutdown hook enabled. Registering a new one.
2017-10-18 16:49:17,829 main DEBUG LoggerContext[name=b4aac2, org.apache.logging.log4j.core.LoggerContext@156d4d4] started OK.
2017-10-18 16:49:17,845 INFO  LogTest - info
2017-10-18 16:49:17,845 WARN  LogTest - warn
Okt 18, 2017 4:49:17 PM org.springframework.amqp.rabbit.connection.CachingConnectionFactory createBareConnection
INFORMATION: Created new connection: SpringAMQP#131f24d:0/SimpleConnection@2fd3f6 [delegate=amqp://panoptesLogAgent@172.16.13.186:5672/lab, localPort= 52013]
2017-10-18 16:49:17,845 ERROR LogTest - error

该过程不会自行退出。如果在主线程中完成日志记录而不是单独的线程,则在将日志消息发送到RabbitMQ之后,主线程将以静默方式死亡(在threaddump中不可见)。对于这两个选项,RabbitMQ都会收到正确的消息。

提前感谢您的帮助!如果您需要更多信息,我很乐意提供。

0 个答案:

没有答案