前言
其實我們前面已經配置了日志,但是最近總感覺日志日志格式看的不舒服,並且每次打包都是一個jar 文件,lib都包含在jar 中,每次做很小的修改都需要重新替換jar文件,jar文件會比較大,傳輸起來比較慢。所以做一些改進。
配置log4j2
好了,廢話不多說了,先來在Springboot中配置log4j2吧。
pom.xml
springboot 項目默認的是使用logback 的,所以我們想要使用log4j ,需要將原來的logback 框架屏蔽掉,再引入log4j.
首先我們在pom.xml 文件中加入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions><!-- 去掉默認配置 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
編寫log4j2.xml
<Configuration status="WARN" monitorInterval="300" packages="cn.mastercom.cat">
<properties>
<property name="MtnoWebRoot" >${sys:user.dir}/logs</property>
<property name="INFO_FILE">zlflovemm_log</property>
<property name="ERROR_FILE">zlflovemm__error</property>
</properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<ThresholdFilter level="ALL" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<RollingRandomAccessFile name="infolog"
fileName="${MtnoWebRoot}/${INFO_FILE}.log"
filePattern="${MtnoWebRoot}/${INFO_FILE}-%d{yyyy-MM-dd}-%i.log">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] [%X{sessionID}] [%X{imei}] %-5level %logger{36} - %msg%n" />
<!-- -->
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
<SizeBasedTriggeringPolicy size="2MB" />
</Policies>
<DefaultRolloverStrategy max="1000">
<Delete basePath="${MtnoWebRoot}" maxDepth="1">
<IfFileName glob="${INFO_FILE}*.log" />
<IfLastModified age="30d" />
</Delete>
</DefaultRolloverStrategy>
</RollingRandomAccessFile>
<RollingRandomAccessFile name="errorlog"
fileName="${MtnoWebRoot}/${ERROR_FILE}.log"
filePattern="${MtnoWebRoot}/${ERROR_FILE}-%d{yyyy-MM-dd}-%i.log">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
<SizeBasedTriggeringPolicy size="200MB" />
</Policies>
<DefaultRolloverStrategy max="1000">
<Delete basePath="${MtnoWebRoot}" maxDepth="1">
<IfFileName glob="${INFO_FILE}*.log" />
<IfLastModified age="30d" />
</Delete>
</DefaultRolloverStrategy>
</RollingRandomAccessFile>
<Async name="Async">
<AppenderRef ref="infolog"/>
<AppenderRef ref="errorlog"/>
</Async>
</Appenders>
<Loggers>
<asyncRoot level="INFO">
<AppenderRef ref="infolog"/>
<AppenderRef ref="errorlog" level="error"/>
<AppenderRef ref="Console" />
</asyncRoot>
</Loggers>
</Configuration>
上面配置的是生成日志的格式,大家可以自行修改。以及配置了單個日志文件最大為200M ,只保留最近30天的文件。
application.properties 配置
#日志配置
logging.config=classpath:log4j2.xml
debug=false
實現上面這三步,就輕松的在項目中使用log4j日志啦。
打包外置配置文件
上面配置的日志,先不測試了,等這個打包的配置也配置好了,再來一起測試。
如果我們直接使用自帶的mvn package 的話,會將我們依賴的jar 包已經配置文件統統打包成可運行的jar 文件。這樣雖然方便,但是這樣的話每次都需要重新打包,並且傳輸起來比較麻煩,所以我們就需要將lib 和配置文件從jar 文件中分離。這樣項目修改了,只需要替換一下比較小的部分就可以了。
pom.xml 修改
打開我們的pom.xml 文件,最下面我們的
<build>
<!--打包后的項目名稱-->
<resources>
<resource>
<directory>src/main/resources</directory>
<targetPath>${project.build.directory}${file.separator}classes</targetPath>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<!--這里必須包含.xml否則Mybatis的xml無法打包-->
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!--java編譯插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
<fork>true</fork>
</configuration>
</plugin>
<!--打jar包的插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib</classpathPrefix>
<!--程序啟動入口-->
<mainClass>com.quellan.zlflovemm.ZlflovemmApplication</mainClass>
</manifest>
<manifestEntries>
<Class-Path>./</Class-Path>
</manifestEntries>
</archive>
<excludes>
<exclude>config/**</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<!--not append assembly id in release file name-->
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<!--注意這里的路徑-->
<descriptor>src/main/build/package.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Docker -->
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.0.0</version>
<!-- 將插件綁定在某個phase執行 -->
<executions>
<execution>
<id>build-image</id>
<!-- 用戶只需執行mvn package ,就會自動執行mvn docker:build -->
<phase>package</phase>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- 指定生成的鏡像名 -->
<imageName>${docker.image.prefix}/${project.artifactId}:${project.version}</imageName>
<!-- 指定標簽 -->
<imageTags>
<imageTag>${project.version}</imageTag>
</imageTags>
<!-- 指定 Dockerfile 路徑 -->
<dockerDirectory>src/main/docker</dockerDirectory>
<!-- 指定遠程 docker api地址 -->
<dockerHost>http://127.0.0.1:2375</dockerHost>
<resources>
<resource>
<targetPath>/</targetPath>
<!-- jar包所在的路徑此處配置的對應target目錄 -->
<directory>${project.build.directory}</directory>
<!-- 需要包含的jar包,這里對應的是Dockerfile中添加的文件名 -->
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
</plugins>
</build>
需要注意的是,如下兩個地方,第一個di地方需要需改成我們自己項目的啟動類。第二個地方需要配置我們的package.xml 文件路徑。內容我們待會講。
package.xml
我們在pom.xml 中配置好了后,我們在src/main 目錄下創建一個build 包,早build 目錄下創建package.xml 文件。路徑就是上面配置的,大家可以按照自己的喜好來。
內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
<id>package</id>
<formats>
<format>zip</format>
</formats>
<!-- 改為false不會出現兩層相同的目錄 -->
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>bin</directory>
<outputDirectory>${file.separator}</outputDirectory>
</fileSet>
<fileSet>
<directory>src/main/resources</directory>
<outputDirectory>${file.separator}</outputDirectory>
<excludes>
<exclude>static/**</exclude>
<exclude>templates/**</exclude>
</excludes>
</fileSet>
<fileSet>
<directory>${project.build.directory}</directory>
<outputDirectory>${file.separator}</outputDirectory>
<includes>
<include>*.jar</include>
</includes>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<useProjectArtifact>true</useProjectArtifact>
<outputDirectory>lib</outputDirectory>
<scope>runtime</scope>
<!--<unpack>false</unpack> -->
<excludes>
<!--<exclude>${project.name}-${project.version}</exclude> -->
<exclude>${groupId}:${artifactId}</exclude>
</excludes>
</dependencySet>
</dependencySets>
</assembly>
測試
好啦,上面的已經配置好啦,我們來測試一下。
直接mvn package成功后會生成如下文件,包含jar 和zip 文件。
zip 文件解壓后,就是我們第一次部署的文件,后面修改代碼只用替換jar文件就可以了。
我們生成的日志文件
番外
好了,就說這么多啦
代碼上傳到github:
https://github.com/QuellanAn/zlflovemm
后續加油♡
歡迎大家關注個人公眾號 "程序員愛酸奶"
分享各種學習資料,包含java,linux,大數據等。資料包含視頻文檔以及源碼,同時分享本人及投遞的優質技術博文。
如果大家喜歡記得關注和分享喲❤