当我们在集群中部署应用之后,应用请求的日志被分散记录在了不同应用服务器的文件系统上,这样分散的存储并不利于我们对日志内容的检索。解决日志分散问题的方案多种多样,本文思路以扩展log4j实现将日志写入MongoDB。
以springboot【19】日志管理之使用AOP统一处理Web请求日志 为基础,进行本功能的改造。该工程实现了一个简单的REST接口,一个对web层的切面,并在web层切面前后记录http请求的日志内容。
思路:log4j提供的输出器实现自Appender接口,要自定义appender输出到MongoDB,只需要继承AppenderSkeleton类,并实现几个方法即可完成。
在pom.xml中引入下面依赖
org.mongodb
mongodb-driver
3.2.2
编写MongoAppender.java类继承AppenderSkeleton,实现如下:
package com.lyd.log;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
import org.bson.codecs.BsonRegularExpressionCodec;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoAppender extends AppenderSkeleton{
private MongoClient mongoClient;
private MongoDatabase mongoDatabase;
private MongoCollection logsCollection;
private String connectionUrl;
private String databaseName;
private String collectionName;
@Override
protected void append(LoggingEvent loggingEvent) {
if(mongoDatabase == null){
MongoClientURI connectionString = new MongoClientURI(connectionUrl);
mongoClient = new MongoClient(connectionString);
mongoDatabase = mongoClient.getDatabase(databaseName);
logsCollection = mongoDatabase.getCollection(collectionName, BasicDBObject.class);
}
logsCollection.insertOne((BasicDBObject) loggingEvent.getMessage());
}
@Override
public void close() {
if(mongoClient != null){
mongoClient.close();
}
}
@Override
public boolean requiresLayout() {
return false;
}
// get/set方法
public String getConnectionUrl() {
return connectionUrl;
}
public void setConnectionUrl(String connectionUrl) {
this.connectionUrl = connectionUrl;
}
public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
}
定义MongoDB的配置参数,可通过log4j.properties配置:
定义MongoDB的连接和操作对象,根据log4j.properties配置的参数初始化:
重写append函数:
重写close函数:关闭mongodb的
设置名为mongodb的logger:
# LOG4J配置
log4j.rootCategory=INFO, stdout
log4j.logger.mongodb==INFO, mongodb
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n
# mongodb输出
log4j.appender.mongodb=com.lyd.log.MongoAppender
log4j.appender.mongodb.connectionUrl=mongodb://localhost:27017
log4j.appender.mongodb.databaseName=logs
log4j.appender.mongodb.collectionName=logs_request
修改后的代码如下,主要做了以下几点修改:
package com.lyd.aspect;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.mongodb.BasicDBObject;
@Aspect
@Order(1)
@Component
public class WebLogAspect {
private Logger logger = Logger.getLogger("mongodb");
ThreadLocal startTime = new ThreadLocal<>();
@Pointcut("execution(public * com.lyd.web..*.*(..))")
public void webLog(){}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable{
startTime.set(System.currentTimeMillis());
//接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//获取要记录的日志内容
BasicDBObject logInfo = getBasicDBObject(request, joinPoint);
logger.info(logInfo);
}
private BasicDBObject getBasicDBObject(HttpServletRequest request,JoinPoint joinPoint){
//基本信息
BasicDBObject r = new BasicDBObject();
r.append("requestURL", request.getRequestURL().toString());
r.append("requestURI", request.getRequestURI());
r.append("queryString", request.getQueryString());
r.append("remoteAddr", request.getRemoteAddr());
r.append("remoteHost", request.getRemoteHost());
r.append("remotePort", request.getRemotePort());
r.append("localAddr", request.getLocalAddr());
r.append("localName", request.getLocalName());
r.append("method", request.getMethod());
r.append("headers", getHeadersInfo(request));
r.append("parameters", request.getParameterMap());
r.append("classMethod", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
r.append("args", Arrays.toString(joinPoint.getArgs()));
return r;
}
private Map getHeadersInfo(HttpServletRequest request){
Map map = new HashMap<>();
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()){
String key = (String) headerNames.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
return map;
}
}
上述内容主要提供一个思路去实现自定义日志的输出和管理。我们可以通过jdbc实现日志记录到mongodb,也可以通过spring-data-mongo来记录到mongodb,当然我们也可以输出到其他数据库,或者输出到消息队列等待其他后续处理等。
对于日志记录到mongodb,也可以直接使用log4mongo实现更为方便快捷。
下面是完整项目结构: