springboot學習(八): 日誌輸出log4j2的使用
阿新 • • 發佈:2018-11-19
說明
在學習springboot時,學習了log4j2日誌檔案的使用,使用AOP統一處理web請求日誌,將日誌記錄到MongoDB中等內容,通過本篇博文,記錄總結下springboot中日誌的輸出以及log4j2的配置、
正文
引入依賴
去除web自帶的日誌,引入log4j2的依賴,aop和mongo依賴
<dependencies> <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-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!--mongodb-driver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> </dependency> <!-- log4j-nosql --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-nosql</artifactId> <version>2.9.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>compile</scope> </dependency> </dependencies>
配置檔案log4j2.xml
在引入log4j2後,需要下resources目錄下建立配置檔案log4j2.xml檔案,通過官方文件,可以對配置檔案的結構有一個大概的瞭解,更詳細的內容見:官方文件
<?xml version="1.0" encoding="UTF-8"?>; <Configuration> <Properties> <Property name="name1">value</property> <Property name="name2" value="value2"/> </Properties> <Filter type="type" ... /> <Appenders> <Appender type="type" name="name"> <Filter type="type" ... /> </Appender> ... </Appenders> <Loggers> <Logger name="name1"> <Filter type="type" ... /> </Logger> ... <Root level="level"> <AppenderRef ref="name"/> </Root> </Loggers> </Configuration>
這裡通過配置檔案,將日誌資訊分類儲存到不同的檔案,並且將日誌資訊輸出到MongoDB中
<?xml version="1.0" encoding="UTF-8"?> <!--啟動項設定為 trace,載入 springboot 啟動內部各種詳細輸出--> <Configuration status="WARN"> <Properties> <Property name="file_path">F:\StudyProject\springboot_study\log4j2\logs</Property> </Properties> <Appenders> <!--新增一個控制檯追加器--> <Console name="Console" target="SYSTEM_OUT" follow="true"> <PatternLayout> <!--<pattern>%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</pattern>--> <pattern>[%d] - [%c] - [%highlight{%level}] - [%method] - [%t] - %msg%n</pattern> </PatternLayout> </Console> <!--新增一個文字追加器--> <File name="File" fileName="C:\Users\wds\Desktop\springboot_study\log4j2\log.log"> <PatternLayout> <pattern>[%-5p] %d %c - %m%n</pattern> </PatternLayout> </File> <RollingFile name="RollingFileInfo" fileName="${file_path}/info/info.log" filePattern="${file_path}/$${date:yyyy-MM}/info/info-%d{yyyy-MM-dd}-%i.log.gz"> <!--<Filters>--> <ThresholdFilter level="INFO" onMatch="DENY" onMismatch="NEUTRAL"></ThresholdFilter> <!--<ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"></ThresholdFilter>--> <!--</Filters>--> <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" /> <Policies> <!--歸檔每天的檔案--> <TimeBasedTriggeringPolicy interval="1" modulate="true"/> <!--限制單個檔案的大小--> <SizeBasedTriggeringPolicy size="2MB"></SizeBasedTriggeringPolicy> </Policies> <!-- 限制每天的檔案個數 --> <DefaultRolloverStrategy compressionLevel="0" max="10"></DefaultRolloverStrategy> </RollingFile> <RollingFile name="RollingFileWarn" fileName="${file_path}/warn/warn.log" filePattern="${file_path}/$${date:yyyy-MM}/warn/warn-%d{yyyy-MM-dd}-%i.log.gz"> <!--<Filters>--> <!--<ThresholdFilter level="WARN"></ThresholdFilter>--> <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"></ThresholdFilter> <!--</Filters>--> <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" /> <Policies> <!--歸檔每天的檔案--> <TimeBasedTriggeringPolicy interval="1" modulate="true"/> <!--限制單個檔案的大小--> <SizeBasedTriggeringPolicy size="2MB"></SizeBasedTriggeringPolicy> </Policies> <DefaultRolloverStrategy compressionLevel="0" max="10"></DefaultRolloverStrategy> </RollingFile> <RollingFile name="RollingFileError" fileName="${file_path}/error/error.log" filePattern="${file_path}/$${date:yyyy-MM}/error/error-%d{yyyy-MM-dd}-%i.log.gz"> <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"></ThresholdFilter> <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" /> <Policies> <!--歸檔每天的檔案--> <TimeBasedTriggeringPolicy interval="1" modulate="true"/> <!--限制單個檔案的大小--> <SizeBasedTriggeringPolicy size="2MB"></SizeBasedTriggeringPolicy> </Policies> <DefaultRolloverStrategy compressionLevel="0" max="10"></DefaultRolloverStrategy> </RollingFile> <NoSql name="databaseAppender"> <MongoDB databaseName="test" collectionName="newlog" server="127.0.0.1" port="27017"></MongoDB> </NoSql> </Appenders> <Loggers> <Logger name="com.example.log4j2" level="DEBUG" additivity="true"> <AppenderRef ref="File"></AppenderRef> </Logger> <Logger name="mongolog" level="trace" additivity="true"> <AppenderRef ref="databaseAppender"/> </Logger> <Root level="INFO"> <AppenderRef ref="Console" /> <AppenderRef ref="RollingFileInfo" /> <AppenderRef ref="RollingFileWarn" /> <AppenderRef ref="RollingFileError" /> <AppenderRef ref="databaseAppender"/> </Root> </Loggers> </Configuration>
AOP處理web請求日誌
通過對controller設定切面來記錄日誌資訊
@Aspect
@Component
public class WebLogAspect {
private Logger logger = LogManager.getLogger(this.getClass());
ThreadLocal<Long> startTime = new ThreadLocal<>();
@Pointcut("execution(public * com.example.log4j2.controller..*.*(..))")
public void webLog(){
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable{
//接受到請求,記錄請求內容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = (HttpServletRequest) attributes.getRequest();
logger.info("URL : " + request.getRequestURL().toString());
logger.info("HTTP_METHOD : " + request.getMethod());
logger.info("IP : " + request.getRemoteAddr());
logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
startTime.set(System.currentTimeMillis());
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable{
logger.info("RESPONSE : " + ret);
logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
}
@Around("webLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
logger.info(System.currentTimeMillis());
Object object = proceedingJoinPoint.proceed();
System.out.println(object);
logger.info(System.currentTimeMillis());
return object;
}
}
原始碼地址:https://github.com/Edenwds/springboot_study/tree/master/log4j2
參考資料:
http://blog.didispace.com/springbootaoplog/
https://logging.apache.org/log4j/2.x/manual/configuration.html#Loggers