SSM项目Log4j和MongoDB整合进行日志管理

1.添加依赖

<!--MongoDB-->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.4.2</version>
</dependency>
<dependency>
    <groupId>org.log4mongo</groupId>
    <artifactId>log4mongo-java</artifactId>
    <version>0.7.4</version>
</dependency>

2.修改log4j.properties

log4j.logger.mongoDB=INFO,mongoDB
log4j.appender.mongoDB=org.log4mongo.MongoDbAppender
log4j.appender.mongoDB.hostname=localhost
log4j.appender.mongoDB.port=27017
log4j.appender.mongoDB.databaseName=sysLog
log4j.appender.mongoDB.collectionName=operationLog
log4j.appender.mongoDB.layout=org.apache.log4j.PatternLayout
log4j.appender.mongoDB.layout.ConversionPattern=%d %-5p [%t] (%13F:%L) %3x - %m%n
3.开发工具类

工具类一:

package com.iborch.health.common;

import com.iborch.health.util.ConfigureFileHelper;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 * Created by lhp on 2017/9/29.
 */
public class MongoDBUtil {

    private static MongoClient mongoClient= null;

    static {
        String hostName = ConfigureFileHelper.getProperty("hostName");
        int port = Integer.parseInt(ConfigureFileHelper.getProperty("port"));
        mongoClient = new MongoClient(hostName,port);
    }

    /**
     *获取指定Collection
     * @param dataBaseName
     * @param collectionName
     * @return
     */
    public static MongoCollection<Document> getMongoCollectionLists(String dataBaseName,String collectionName){
        MongoDatabase mongoDatabase =mongoClient.getDatabase(dataBaseName);
        return mongoDatabase.getCollection(collectionName);
    }

    /**
     * 关闭Mongodb
     */
    public static void close() {
        if (mongoClient != null) {
            mongoClient.close();
            mongoClient = null;
        }
    }
}

工具类二:

package com.iborch.health.common;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by lhp on 2017/9/27.
 */
public class SystemLogUtil {

    //保存日志
    public static void saveSystemLog(String moduleName,String type,String description){
        org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger("mongoDB");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String userId = "";
        //IP地址
        String ip = ClientIpAddress.getIpAddr(request);
        String date = simpleDateFormat.format(new Date());
        StackTraceElement stack[] = Thread.currentThread().getStackTrace();
        String className = stack[2].getClassName();
        String methodName = stack[2].getMethodName();
        int lineNumber = stack[2].getLineNumber();
        StringBuilder builder = new StringBuilder().append("{\"userId\":\""+userId+"\"").append(",\"date\":\""+date+"\"").append(",\"className\":\""+className+"\"")
                .append(",\"methodName\":\""+methodName+"\"").append(",\"lineNumber\":\""+lineNumber+"\"").append(",\"ip\":\""+ip+"\"")
                .append(",\"moduleName\":\""+moduleName+"\"").append(",\"type\":\""+type+"\"").append(",\"description\":\""+description+"\""+"}");
        log.info(builder.toString());
    }
}

4.获取列表方法

public List<SystemLog> getSystemLogLists( int currentPage,int pageSize,String moduleName,String userName,String startDate,String endDate) {
    List<SystemLog> systemLogList = new ArrayList<SystemLog>();
    MongoCollection<Document> collection = MongoDBUtil.getMongoCollectionLists("sysLog", "operationLog");
    BasicDBObject query = new BasicDBObject();

    Pattern patternUserName = Pattern.compile("^.*" + userName + ".*$", Pattern.CASE_INSENSITIVE);
    query.put("message", patternUserName);
    if (null != startDate && !"".equals(startDate)){
        String startDt = StringUtil.urlDecode(startDate);
        String endDt = StringUtil.urlDecode(endDate);
        int startYear = Integer.parseInt(startDt.split("/")[0]);
        int startMonth = Integer.parseInt(startDt.split("/")[1]);
        int startDay = Integer.parseInt(startDt.split("/")[2]);
        System.out.println("startYear...:" + startYear + "startMonth...:" + startMonth+ "startDay...:" + startDay);
        int endYear =0;
        int endMonth =0;
        int endDay =0;
        if (null == endDt || "".equals(endDt)){
            endYear = Integer.parseInt(endDt.split("/")[0]);
            endMonth = Integer.parseInt(endDt.split("/")[1])+1;
            endDay = 1;
        } else {
            endYear = Integer.parseInt(endDt.split("/")[0]);
            endMonth = Integer.parseInt(endDt.split("/")[1]);
            endDay = Integer.parseInt(endDt.split("/")[2])+2;
            System.out.println("endYear...:" + endYear + "endMonth...:" + endMonth+ "endDay...:" + endDay);
        }
        query.put("timestamp", BasicDBObjectBuilder.start("$gte", new Date(startYear - 1900, startMonth - 1, startDay)).add("$lt", new Date(endYear - 1900, endMonth - 1, endDay)).get());
    }else {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String patternDate = simpleDateFormat.format(new Date());
        String patternMonth = patternDate.substring(0, patternDate.lastIndexOf("-"));
        Pattern pattern = Pattern.compile("^.*" + patternMonth + ".*$", Pattern.CASE_INSENSITIVE);
        query.put("message", pattern);
    }

    Pattern patternModule = Pattern.compile("^.*" + moduleName + ".*$", Pattern.CASE_INSENSITIVE);
    query.put("message", patternModule);

    FindIterable<Document> findIterable = collection.find(query).skip(currentPage).limit(pageSize);
    MongoCursor<Document> mongoCursor = findIterable.iterator();
    while(mongoCursor.hasNext()) {
        Document document = mongoCursor.next();
        JSONObject jsonObject = JSONObject.fromObject(document.get("message"));
        SystemLog systemLog=(SystemLog)JSONObject.toBean(jsonObject, SystemLog.class);
        systemLog.setId(UUID.randomUUID().toString());
        systemLogList.add(systemLog);
    }
    return systemLogList;
}

5.使用方法

在需要添加日志的地方,添加如下:

SystemLogUtil.saveSystemLog("logout","logout","用户注销系统");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值