Springboot 日誌管理模塊編寫記錄

/**
    配置類
**/

@Component
@Order(value=1)
public class MyApplicationRunner implements ApplicationRunner{
/*
	private static final Logger logger = LoggerFactory.getLogger(MyApplicationRunner.class);

	@Autowired
	private MemoryService memoryService; 
	
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		logger.info("==服務啓動後,初始化數據操作==");
		memoryService.getResources();
	}*/
	 
}

添加日誌的配置類

package com.run.runlpwebdemo.config;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.run.runlpwebdemo.bean.Log;
import com.run.runlpwebdemo.bean.Resource;
import com.run.runlpwebdemo.service.LogService;
import com.run.runlpwebdemo.service.MemoryService;

@Aspect
@Component
public class WebLogAspect {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    @Autowired
    private MemoryService memoryService;
    @Autowired
    private LogService logService;

    @Pointcut("execution(public * com.run.runlpwebdemo.controller..*.*(..))")
    public void webLog() {
    }


    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
    	
    	// 接收到請求,記錄請求內容

        logger.info("WebLogAspect.doBefore()");

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = 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()));

    	saveLog(request);
    }
    
    private void saveLog(HttpServletRequest request) {
		Log log = new Log();
		String currentUrl = getCurrentURL(request);
		String parameterJson = getCurrentParameters(request);		

		

		Resource resource = memoryService.getResource(currentUrl);
		//需要記錄日誌的資源則記錄日誌
		if(null!=resource&&resource.getIsLog()==1) {
			String description = "";
			description +=resource.getResourceName();
			if (StringUtils.hasText(parameterJson)) {
				description += (StringUtils.hasText(description) ? "," : "") + "參數:" + parameterJson;
			}
			log.setDescription(description);
			log.setUserIp(request.getRemoteAddr());
			String moduleName = memoryService.getModuleName(currentUrl);
			if (StringUtils.hasText(moduleName)) {
				log.setModuleName(moduleName);
			}
			logService.insert(log);
		}
	}
    
    /**
	 * 獲取當前url
	 * 
	 * @return
	 */
	public String getCurrentURL(HttpServletRequest request) {
		String currentURL = request.getRequestURI();
		String contextPath = request.getContextPath();
		if (currentURL.startsWith(contextPath)) {
			currentURL = currentURL.replaceFirst(contextPath, "");
		}

		return currentURL;
	}

	/**
	 * 獲取當前請求參數的Json
	 * 
	 * @return
	 */
	public String getCurrentParameters(HttpServletRequest request) {
		String parameterJson = "";
		ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = new HashMap<>();
		Enumeration<?> parameterEnum = request.getParameterNames();
		while (parameterEnum.hasMoreElements()) {
			String paramName = (String) parameterEnum.nextElement();
			String[] values = request.getParameterValues(paramName);
			for (int i = 0; i < values.length; i++) {
				map.put(paramName, values);
			}
		}
		if (map.size() > 0) {
			try {
				parameterJson = mapper.writeValueAsString(map);
			} catch (JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return parameterJson;
	}
    
}

Service層代碼編寫

package com.run.runlpwebdemo.service;

import java.util.List;

import com.run.runlpwebdemo.bean.Resource;


/**
 * <p>Title:內存持久化服務接口</p> 
 * <p>Description:  </p>
 * <p>Copyright: Copyright (c) 2003 - 2014 </p>
 * <p>Company: Run Technology Co.Ltd. Beijing </p>
 * <p>bulid: 2014-4-30 下午03:41:43 </p>
 * @author 王鬆 E-mail:[email protected]
 * @version 1.0 
 */
public interface MemoryService {
    
	/**
	 * 獲取訪問資源列表
	 */
	public List<Resource> getResources();
	
	/**
	 * 根據Id獲取訪問資源
	 * @param resourceId
	 * @return
	 */
	public Resource getResource(int resourceId);
	
	/**
	 * 刷新訪問資源
	 * @param resourceId
	 */
	public void flushResource(int resourceId);
	
	/**
	 * 內存刪除訪問資源
	 * @param resourceId
	 */
	public void removeResource(int resourceId);
	
	/**
	 * 根據URL獲取訪問資源
	 * @param url
	 */
	public Resource getResource(String url);
	

	
	/**
	 * 判斷url是否是公共資源
	 * @param permissionUrl
	 */
	public boolean isCommon(String permissionUrl);
	
	/**
	 * 判斷url是否記錄日誌
	 * @param roleId
	 * @param permissionUrl
	 */
	public boolean isLog(String permissionUrl);
	
	/**
	 * 獲取模塊名稱
	 * @param permissionUrl
	 */
	public String getModuleName(String permissionUrl);
		
	
	
}

serviceImp代碼層的編寫

package com.run.runlpwebdemo.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.run.runlpwebdemo.bean.Resource;
import com.run.runlpwebdemo.constant.Memory;
import com.run.runlpwebdemo.constant.MemoryKey;
import com.run.runlpwebdemo.dao.ResourceDao;
import com.run.runlpwebdemo.query.ResourceQuery;
import com.run.runlpwebdemo.service.MemoryService;
import com.run.runlpwebdemo.utils.StringUtil;



/**
 * <p>
 * Title:內存持久化服務方法
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2003 - 2014
 * </p>
 * <p>
 * Company: Run Technology Co.Ltd. Beijing
 * </p>
 * <p>
 * bulid: 2014-4-30 下午03:12:41
 * </p>
 * 
 * @author 王鬆 E-mail:[email protected]
 * @version 1.0
 */
@Service("memoryService")
public class MemoryServiceImpl implements MemoryService{
	

	@Autowired
	private ResourceDao resourceDao;

	/**
	 * 獲取訪問資源列表
	 */
	public List<Resource> getResources() {
		String key = MemoryKey.RESOURCE_ALLID_KEY;
		String resourceIds = "";
		List<Resource> resources = new ArrayList<Resource>();

		String resourceKey = "";
		if (Memory.containsKey(key)) {
			resourceIds = (String) Memory.get(key);
			if (StringUtils.hasText(resourceIds)) {
				Resource resource = null;
				int[] rIds = StringUtil.getIds(resourceIds);
				for (int resourceId : rIds) {
					resourceKey = MemoryKey.RESOURCE_ID_PREFIX + resourceId;
					resource = (Resource) Memory.get(resourceKey);
					if (resource != null) {
						resources.add(resource);
					}
				}
			}
		} else {// 資源沒有內存持久化
			ResourceQuery query = new ResourceQuery();
			query.setPage(false);
			resources = resourceDao.getResources(query);// 讀取全部資源

			if (resources != null && resources.size() > 0) {
				for (Resource resource : resources) {
					resourceIds += (StringUtils.hasText(resourceIds) ? "," : "")
							+ resource.getResourceId();
					resourceKey = MemoryKey.RESOURCE_ID_PREFIX + resource.getResourceId();
					Memory.put(resourceKey, resource);
					resourceKey = MemoryKey.RESOURCE_URL_PREFIX + resource.getUrl();
					Memory.put(resourceKey, resource);
				}
			}
		}

		return resources;
	}

	/**
	 * 根據Id獲取訪問資源
	 * 
	 * @param resourceId
	 * @return
	 */
	public Resource getResource(int resourceId) {
		String key = MemoryKey.RESOURCE_ID_PREFIX + resourceId;
		Resource resource = null;
		if (Memory.containsKey(key)) {
			resource = (Resource) Memory.get(key);
		} else {
			resource = resourceDao.getResource(resourceId);
			Memory.put(key, resource);
			if (resource != null) {
				key = MemoryKey.RESOURCE_URL_PREFIX + resource.getUrl();
				Memory.put(key, resource);
			}
		}
		return resource;
	}

	/**
	 * 刷新訪問資源
	 * 
	 * @param resourceId
	 */
	public void flushResource(int resourceId) {
		removeResource(resourceId);
		getResource(resourceId);
	}

	/**
	 * 內存刪除訪問資源
	 * 
	 * @param resourceId
	 */
	public void removeResource(int resourceId) {
		String key = MemoryKey.RESOURCE_ID_PREFIX + resourceId;
		Resource resource = getResource(resourceId);
		if (Memory.containsKey(key)) {
			Memory.remove(key);
		}

		if (resource != null) {
			key = MemoryKey.RESOURCE_URL_PREFIX + resource.getUrl();
			if (Memory.containsKey(key)) {
				Memory.remove(key);
			}
		}
	}

	/**
	 * 根據URL獲取訪問資源
	 * 
	 * @param url
	 */
	public Resource getResource(String url) {
		String key = MemoryKey.RESOURCE_URL_PREFIX + url;
		Resource resource = null;
		if (Memory.containsKey(key)) {
			resource = (Resource) Memory.get(key);
			
		} else {
			ResourceQuery query = new ResourceQuery();
			query.setPage(false);
			query.setUrl(url);
			List<Resource> resources = resourceDao.getResources(query);// 讀取資源
			if (resources != null && resources.size() > 0) {
				resource = resources.get(0);
				Memory.put(key, resource);
				key = MemoryKey.RESOURCE_ID_PREFIX + resource.getResourceId();
				Memory.put(key, resource);
			}
		}
		return resource;
	}

	

	
	/**
	 * 判斷url是否是公共資源
	 * 
	 * @param permissionUrl
	 */
	public boolean isCommon(String permissionUrl) {
		boolean rtn = false;
		Resource resource = getResource(permissionUrl);
		if (resource != null) {
			if (resource.getIsCommon() == 1) {
				rtn = true;
			}
		}
		return rtn;
	}

	/**
	 * 判斷url是否記錄日誌
	 * 
	 * @param permissionUrl
	 */
	public boolean isLog(String permissionUrl) {
		boolean rtn = false;
		Resource resource = getResource(permissionUrl);
		if (resource != null) {
			if (resource.getIsLog() == 1) {
				rtn = true;
			}
		}
		return rtn;
	}

	/**
	 * 獲取模塊名稱
	 * 
	 * @param permissionUrl
	 */
	public String getModuleName(String permissionUrl) {
		String moduleName = "";
		Resource resource = getResource(permissionUrl);
		if (resource != null) {
			if (resource.getIsNav() == 1) {
				moduleName = resource.getResourceName();
			} else {
				resource = getResource(resource.getParentId());
				if (resource != null) {
					if (resource.getIsNav() == 1) {
						moduleName = resource.getResourceName();
					}
				}
			}
		}
		return moduleName;
	}
}

Mapper映射文件以及Dao編寫

package com.run.runlpwebdemo.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.run.runlpwebdemo.bean.Resource;
import com.run.runlpwebdemo.query.ResourceQuery;

/**
 * <p>Title:訪問資源DAO方法</p> 
 * <p>Description:  </p>
 * <p>Copyright: Copyright (c) 2018 - 2028 </p>
 * <p>Company: Run Technology Co.Ltd. Beijing </p>
 * <p>bulid: 2018-7-20 下午03:12:41 </p>
 * @author 
 * @version 1.0 
 */
//@Repository
public interface ResourceDao {
	/**
	 * 主鍵查詢訪問資源
	 * @param resourceId
	 * @return
	 */
	public Resource getResource(int resourceId);
	
	/**
	 * 複雜條件查詢訪問資源
	 * @param query 包含查詢和排序條件
	 * @return
	 */
	public List<Resource> getResources(ResourceQuery query);
	
	
	
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.run.runlpwebdemo.dao.ResourceDao">
	<!-- 訪問資源表-->
	<sql id="RESOURCE_TABLE">SYS_RESOURCE</sql>
	
	<!-- 資源查詢條件 -->
	<sql id="sqlFilter">
		<trim prefix="where" prefixOverrides="and |or">  
   	        <if test="updateResourceId != null and updateResourceId != 0">  
				<![CDATA[R.RESOURCE_ID<>#{updateResourceId}]]>   
			</if>
			<if test="keyword != null and keyword != ''">  
				AND R.RESOURCE_NAME LIKE '%'||#{keyword}||'%'
			</if>
			<if test="parentIds != null">  
				R.PARENT_ID in 
				<foreach item="item" index="index" collection="parentIds" open="(" separator="," close=")">
					#{item}
		        </foreach>
			</if>
	        <if test="resourceName != null and resourceName != ''">  
				AND R.RESOURCE_NAME=''||#{resourceName}||''
			</if>
	        <if test="parentId != null and parentId >= 0">  
	            AND R.PARENT_ID=#{parentId}  
	        </if> 
	        
	        <if test="url != null and url != ''">  
				AND R.URL=''||#{url}||''
			</if>
	        <if test="isCommon != null and isCommon >= 0">  
	            AND R.IS_COMMON=#{isCommon}  
	        </if>
			<if test="isNav != null and isNav >= 0">  
	            AND R.IS_NAV=#{isNav}  
			</if>
			<if test="isButton != null and isButton >= 0">  
	            AND R.IS_BUTTON=#{isButton}  
			</if>
			<if test="navNum != null and navNum > 0">  
	            AND R.NAV_NUM=#{navNum}  
			</if>
			<if test="isRoleResource != null and isRoleResource == 1">  
	            <![CDATA[AND R.RESOURCE_ID > 1]]>   
			</if>
	    </trim>
	</sql>
	
	<!-- 主鍵查詢 -->
	<select id="getResource" parameterType="int" resultType="com.run.runlpwebdemo.bean.Resource">
		SELECT R.RESOURCE_ID, R.RESOURCE_NAME, R.PARENT_ID, R.URL, R.IS_COMMON, 
			   R.IS_NAV, R.IS_BUTTON, R.IS_LOG, R.NAV_NUM
			   FROM <include refid="RESOURCE_TABLE"/> R
			   WHERE R.RESOURCE_ID=#{resourceId}
	</select>
	<!-- 條件查詢-->
	<select id="getResources" parameterType="com.run.runlpwebdemo.query.ResourceQuery" resultType="com.run.runlpwebdemo.bean.Resource">
		<if test="isPage">
			SELECT * FROM (SELECT TABLE_A.*,ROWNUM AS MY_ROWNUM FROM (
		</if>
		
		SELECT R.RESOURCE_ID, R.RESOURCE_NAME, R.PARENT_ID, R.URL, R.IS_COMMON, 
			   R.IS_NAV, R.IS_BUTTON, R.IS_LOG, R.NAV_NUM
			   FROM <include refid="RESOURCE_TABLE"/> R
		<include refid="sqlFilter"/>

		<if test="orderField != null and orderField != ''">
			ORDER BY  ${orderField}
			<if test="orderField != null and orderField != ''">
				${orderType}
			</if>
		</if> 
		
		<if test="isPage">
			<![CDATA[ ) TABLE_A WHERE ROWNUM <= #{maxnum} ) WHERE MY_ROWNUM > #{minnum} ]]>
		</if>
	</select>
	

</mapper>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章