执行jar包上次遇到过一个问题,这次又出现一个,同样是idea执行没问题,达成jar包运行jar包出现问题
log4j2 是采用的插件式编程,当log4j2包编译时,或者含有log4j2插件的包编译时,会将需要加载的插件信息放在META-INF/org/apache/logging/log4j/core/config/plugins/Log4j2Plugins.dat这个文件中(包括官方logj42的原生插件),然后项目启动的时候,log4j2会在各个jar包的META-INF目录下扫描这个插件信息文件,然后去加载插件。
但是当项目被打成一个jar包时,如果两个不同的jar包中都有Log4j2Plugins.dat 这个文件,就会出现问题,其中一个文件会被另一个覆盖,导致项目启动的时候有一个文件中的插件不能被正常加载,导致报错。
解决这个问题就是当所有jar包被打成一个jar包时,需要对各个jar包中的Log4j2Plugins.dat进行合并,这就是maven-shade-plugin.log4j2-cachefile-transformer这个包所做的事情了。
解决
使用mavenShadePlugin.log4j2CacheTransformer打jar包
<transformer implementation="com.github.edwgiz.mavenShadePlugin.log4j2CacheTransformer.PluginsCacheFileTransformer"/>
在plugin中加上依赖,要不然上面的类会找不到
<dependencies>
<dependency>
<groupId>com.github.edwgiz</groupId>
<artifactId>maven-shade-plugin.log4j2-cachefile-transformer</artifactId>
<version>2.6.1</version>
</dependency>
</dependencies>
完整的
<build>
<finalName>my-python</finalName>
<plugins>
<!-- Maven Shade Plugin -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="com.github.edwgiz.mavenShadePlugin.log4j2CacheTransformer.PluginsCacheFileTransformer"/>
</transformers>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.github.edwgiz</groupId>
<artifactId>maven-shade-plugin.log4j2-cachefile-transformer</artifactId>
<version>2.6.1</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
dependencies在build里有时会导致找不到包,在pom依赖添加依赖
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.12.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-jcl</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.github.edwgiz</groupId>
<artifactId>maven-shade-plugin.log4j2-cachefile-transformer</artifactId>
<version>2.6.1</version>
</dependency>