log4j2分层输出日志
程序员文章站
2022-07-04 12:36:36
在java mvc框架开发过程中,我们经常的将代码分为类似controller(控制层)、service(业务层)、rpc(远程接口调用层)、dao(数据层)等层级,如果将所有层级的日志全部都打到一个文件,一个是导致单个日志文件过大,另外不方便查看,所以下面考虑用log4j2根据不同层级生成对应的l ......
在java mvc框架开发过程中,我们经常的将代码分为类似controller(控制层)、service(业务层)、rpc(远程接口调用层)、dao(数据层)等层级,如果将所有层级的日志全部都打到一个文件,一个是导致单个日志文件过大,另外不方便查看,所以下面考虑用log4j2根据不同层级生成对应的log文件:
1. maven配置
<dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-log4j12</artifactid> </dependency> <dependency> <groupid>org.apache.logging.log4j</groupid> <artifactid>log4j-1.2-api</artifactid> <version>2.10.0</version> </dependency>
2. log4j2配置文件
<?xml version="1.0" encoding="utf-8"?> <configuration status="warn" monitorinterval="30"> <properties> <!-- 文件输出格式 --> <property name="pattern">%d{yyyy-mm-dd hh:mm:ss.sss} |-%-5level [logid:%x{logid}] [%thread] %c#%m [%l] -| %msg%n</property> <property name="filepath">/export/logs/domains/myapp</property> </properties> <appenders> <console name="console" target="system_out"> <patternlayout pattern="${pattern}" /> </console> <rollingrandomaccessfile name="rpcfile" filename="${filepath}/rpc.log" filepattern="${filepath}/rpc-%d{yyyy-mm-dd}.log"> <patternlayout pattern="${pattern}"/> <policies> <timebasedtriggeringpolicy modulate="true" interval="1"/> </policies> </rollingrandomaccessfile> <rollingrandomaccessfile name="servicefile" filename="${filepath}/service.log" filepattern="${filepath}/service-%d{yyyy-mm-dd}.log"> <patternlayout pattern="${pattern}"/> <policies> <timebasedtriggeringpolicy modulate="true" interval="1"/> </policies> </rollingrandomaccessfile> <rollingrandomaccessfile name="controllerfile" filename="${filepath}/controller.log" filepattern="${filepath}/controller-%d{yyyy-mm-dd}.log"> <patternlayout pattern="${pattern}"/> <policies> <timebasedtriggeringpolicy modulate="true" interval="1"/> </policies> </rollingrandomaccessfile> </appenders> <loggers> <!--过滤信息--> <logger name="org.springframework" level="warn"></logger> <logger name="rpc" level="info" > <appenderref ref="rpcfile" /> </logger> <logger name="service" level="info" > <appenderref ref="servicefile" /> </logger> <logger name="controller" level="info" > <appenderref ref="controllerfile" /> </logger> <root level="info"> <appenderref ref="console" /> <appenderref ref="exceptionfile" /> </root> </loggers> </configuration>
3. 输出日志工具类
import org.slf4j.logger; import org.slf4j.loggerfactory; public class logutil { /** * rpc层日志记录 */ public static final logger rpc = loggerfactory.getlogger("rpc"); /** * service业务层日志记录 */ public static final logger service = loggerfactory.getlogger("service"); /** * controller业务层日志记录 */ public static final logger controller = loggerfactory.getlogger("controller"); }
4. 输出日志
logutil.controller.error("error message={}", e); logutil.service.warn("warn message={}", msg); ....