vertx 环境下,如何使用log4j2+slf4j日志框架读取外部的日志配置文件?

列车
  • 47

我想在基于vertx的java的maven项目下使用log4j2+slf4j日志框架。log4j2日志配置文件在项目文件下的config文件夹里,并不在resources文件夹中。加载日志配置文件的方法会先于创建vertx对象之前而调用

<dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.30</version>
        </dependency>
        
    
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>2.14.1</version>
    </dependency>
        
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.14.1</version>
        </dependency>
                
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.14.1</version>
        </dependency>

以下是log4j配置代码
java代码配置,读取项目相对路径下的config文件夹内的log4j配置文件

 ConfigurationSource source;  
        try {  
 
            String path=Config.Path("log4j2.xml"); 
            System.out.println(path);
            File config=new File(path);
                  source = new ConfigurationSource(new FileInputStream(config),config);
        
            Configurator.initialize(null, source);                
          Logger logger = LoggerFactory.getLogger(LogConfig.class); 
            
            logger.info("加载log4j2"); 
        } catch (Exception e) {  
            e.printStackTrace();  
        }     

xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration >

  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} sss [%t] %-5level %logger{36}: %n%msg%n"/>
    </Console>
  </Appenders>
  
<Loggers>
    <Root level="info">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
  
  
</Configuration>

然后启动vertx项目

以下是控制台输出内容
09:54:24.377 [main] INFO config.log.LogConfig - 加载log4j2
09:54:24.390 [main] DEBUG io.vertx.core.logging.LoggerFactory - Using io.vertx.core.logging.SLF4JLogDelegateFactory
09:54:24.618 [main] DEBUG io.netty.util.internal.logging.InternalLoggerFactory - Using SLF4J as the default logging framework
09:54:24.620 [main] DEBUG io.netty.util.internal.PlatformDependent - Platform: Windows
09:54:24.621 [main] DEBUG io.netty.util.internal.PlatformDependent0 - -Dio.netty.noUnsafe: false
09:54:24.621 [main] DEBUG io.netty.util.internal.PlatformDependent0 - Java version: 8
09:54:24.622 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.theUnsafe: available
09:54:24.622 [main] DEBUG io.netty.util.internal.PlatformDependent0 - sun.misc.Unsafe.copyMemory: available
09:54:24.622 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Buffer.address: available
09:54:24.623 [main] DEBUG io.netty.util.internal.PlatformDependent0 - direct buffer constructor: available
09:54:24.623 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.Bits.unaligned: available, true
09:54:24.623 [main] DEBUG io.netty.util.internal.PlatformDependent0 - jdk.internal.misc.Unsafe.allocateUninitializedArray(int): unavailable prior to Java9
09:54:24.623 [main] DEBUG io.netty.util.internal.PlatformDependent0 - java.nio.DirectByteBuffer.<init>(long, int): available
09:54:24.623 [main] DEBUG io.netty.util.internal.PlatformDependent - sun.misc.Unsafe: available
09:54:24.624 [main] DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.tmpdir: C:\Users\Administrator\AppData\Local\Temp (java.io.tmpdir)
09:54:24.624 [main] DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.bitMode: 64 (sun.arch.data.model)
09:54:24.625 [main] DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.maxDirectMemory: 1886912512 bytes
09:54:24.625 [main] DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.uninitializedArrayAllocationThreshold: -1
09:54:24.625 [main] DEBUG io.netty.util.internal.CleanerJava6 - java.nio.ByteBuffer.cleaner(): available
09:54:24.625 [main] DEBUG io.netty.util.internal.PlatformDependent - -Dio.netty.noPreferDirect: false
09:54:24.638 [main] DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.level: simple
09:54:24.638 [main] DEBUG io.netty.util.ResourceLeakDetector - -Dio.netty.leakDetection.targetRecords: 4
09:54:24.652 [main] DEBUG io.netty.channel.MultithreadEventLoopGroup - -Dio.netty.eventLoopThreads: 8
09:54:24.666 [main] DEBUG io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.initialSize: 1024
09:54:24.666 [main] DEBUG io.netty.util.internal.InternalThreadLocalMap - -Dio.netty.threadLocalMap.stringBuilder.maxSize: 4096
09:54:24.671 [main] DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.noKeySetOptimization: false
09:54:24.671 [main] DEBUG io.netty.channel.nio.NioEventLoop - -Dio.netty.selectorAutoRebuildThreshold: 512
09:54:24.677 [main] DEBUG io.netty.util.internal.PlatformDependent - org.jctools-core.MpscChunkedArrayQueue: available
09:54:24.707 [main] DEBUG io.netty.resolver.dns.DefaultDnsServerAddressStreamProvider - Default DNS servers: [/114.114.114.114:53] (sun.net.dns.ResolverConfiguration)
09:54:24.711 [main] DEBUG io.netty.util.NetUtil - -Djava.net.preferIPv4Stack: false
09:54:24.711 [main] DEBUG io.netty.util.NetUtil - -Djava.net.preferIPv6Addresses: false
09:54:24.874 [main] DEBUG io.netty.util.NetUtilInitializations - Loopback interface: lo (Software Loopback Interface 1, 127.0.0.1)
09:54:24.875 [main] DEBUG io.netty.util.NetUtil - Failed to get SOMAXCONN from sysctl and file \proc\sys\net\core\somaxconn. Default: 200
09:54:24.935 [MLog-Init-Reporter] INFO com.mchange.v2.log.MLog - MLog clients using slf4j logging.
09:54:24.939 [MLog-Init-Reporter] DEBUG com.mchange.v2.log.MLog - Reading VM config for path list /com/mchange/v2/log/default-mchange-log.properties, /mchange-commons.properties, /c3p0.properties, hocon:/reference,/application,/c3p0,/, /mchange-log.properties, /
09:54:24.939 [MLog-Init-Reporter] DEBUG com.mchange.v2.log.MLog - The configuration file for resource identifier '/mchange-commons.properties' could not be found. Skipping.
09:54:24.939 [MLog-Init-Reporter] DEBUG com.mchange.v2.log.MLog - The configuration file for resource identifier '/c3p0.properties' could not be found. Skipping.
09:54:24.939 [MLog-Init-Reporter] DEBUG com.mchange.v2.log.MLog - The configuration file for resource identifier 'hocon:/reference,/application,/c3p0,/' could not be found. Skipping.
09:54:24.939 [MLog-Init-Reporter] DEBUG com.mchange.v2.log.MLog - The configuration file for resource identifier '/mchange-log.properties' could not be found. Skipping.
09:54:24.941 [vert.x-worker-thread-0] DEBUG com.mchange.v2.cfg.MConfig - The configuration file for resource identifier '/mchange-commons.properties' could not be found. Skipping.
09:54:24.941 [vert.x-worker-thread-0] DEBUG com.mchange.v2.cfg.MConfig - The configuration file for resource identifier '/mchange-log.properties' could not be found. Skipping.
09:54:24.941 [vert.x-worker-thread-0] DEBUG com.mchange.v2.cfg.MConfig - The configuration file for resource identifier 'hocon:/reference,/application,/c3p0,/' could not be found. Skipping.
09:54:24.941 [vert.x-worker-thread-0] DEBUG com.mchange.v2.cfg.MConfig - The configuration file for resource identifier '/c3p0.properties' could not be found. Skipping.
……

控制台输出了很多我不想看到的内容。很明显是log4j2配置失败了,并没有加载log4j2配置文件的内容,但是log4j2配置文件的路径是正确的,不是文件路径有问题.有一些敏感输出信息我去除掉了。

回复
阅读 1.3k
1 个回答

不用那么麻烦,slf4j是找的是classpath的中的log4j配置文件,所以不管你的配置文件在哪,最终你在构建的时候把它加到classpath不就行了?resources只是默认的classpath路径而已,实际构建工具会把resources的文件拷贝到jar包中。

因此你要做的就是在你的项目构建配置中把config目录加一个copy就完事了,其他代码中啥也不用管。

至于具体怎么配,就得看你的构建工具是maven还是gradle了,参考对应的文档就行了。

最后如果你期望配置文件彻底外部化,允许加载外部的log4j2配置,那么运行的时候加个system property -Dlog4j.configurationFile=path/to/log4j2.xml就行了,写死到程序启动参数或者干脆写到main函数中也行,参考log4j2官方文档: https://logging.apache.org/lo...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏