Browse Source

优化日志发送工具

NorthLan 6 years ago
parent
commit
4a4da31182

+ 14 - 38
zen-api/src/main/kotlin/com/gxzc/zen/logging/aop/LogDBInterceptor.kt

@@ -2,11 +2,8 @@ package com.gxzc.zen.logging.aop
 
 import com.alibaba.dubbo.common.logger.LoggerFactory
 import com.baomidou.mybatisplus.toolkit.PluginUtils
-import com.gxzc.zen.common.properties.PlatformProperties
 import com.gxzc.zen.logging.constants.LogConstants
-import com.gxzc.zen.logging.model.LogDB
 import com.gxzc.zen.logging.util.MQLogUtil
-import com.gxzc.zen.umps.util.SSOUtil
 import net.sf.jsqlparser.parser.CCJSqlParserUtil
 import net.sf.jsqlparser.schema.Table
 import net.sf.jsqlparser.statement.delete.Delete
@@ -20,7 +17,6 @@ import org.apache.ibatis.mapping.MappedStatement
 import org.apache.ibatis.mapping.SqlCommandType
 import org.apache.ibatis.plugin.*
 import org.apache.ibatis.reflection.SystemMetaObject
-import org.springframework.beans.factory.annotation.Autowired
 import org.springframework.stereotype.Component
 import java.sql.Connection
 import java.util.*
@@ -43,12 +39,9 @@ open class LogDBInterceptor : Interceptor {
         private val tableNameMapping = ConcurrentHashMap<String, String>()
     }
 
-    @Autowired
-    private lateinit var platformProperties: PlatformProperties
-
     override fun intercept(invocation: Invocation): Any {
         logger.debug("操作数据库日志记录开始...")
-        val startTime = System.currentTimeMillis()
+        val startTime = Date()
         val statementHandler = PluginUtils.realTarget(invocation.target) as StatementHandler
         val metaObject = SystemMetaObject.forObject(statementHandler)
         // 获取SQL操作类型
@@ -58,25 +51,12 @@ open class LogDBInterceptor : Interceptor {
             return invocation.proceed()
         }
 
-        // 构造消息体
-        val platformId = platformProperties.id!!
-        var account: String? = null
-        var accountName: String? = null
-        try {
-            account = SSOUtil.getCurAccount()!!
-            accountName = SSOUtil.getCurUserInfo()!!.username
-        } catch (e: Throwable) {
-        }
-        val logDB = LogDB().apply {
-            this.platformId = platformId
-            this.operatorAccount = account
-            this.operatorName = accountName
-            this.operatorTime = Date()
-        }
-        // 设定sql
-        logDB.sql = boundSql.sql
+        // 消息构造
+        val type: Int
+        val sql = boundSql.sql
 
-        val statement = CCJSqlParserUtil.parse(logDB.sql)
+
+        val statement = CCJSqlParserUtil.parse(sql)
 
         var dbName: String? = null
         var tableName: String? = null
@@ -87,19 +67,19 @@ open class LogDBInterceptor : Interceptor {
             SqlCommandType.SELECT -> {
                 val plainSelect = (statement as Select).selectBody as PlainSelect
                 table = (plainSelect.fromItem as Table)
-                logDB.type = LogConstants.DB_TYPE_SELECT
+                type = LogConstants.DB_TYPE_SELECT
             }
             SqlCommandType.DELETE -> {
                 table = (statement as Delete).table
-                logDB.type = LogConstants.DB_TYPE_DELETE
+                type = LogConstants.DB_TYPE_DELETE
             }
             SqlCommandType.INSERT -> {
                 table = (statement as Insert).table
-                logDB.type = LogConstants.DB_TYPE_INSERT
+                type = LogConstants.DB_TYPE_INSERT
             }
             SqlCommandType.UPDATE -> {
                 table = (statement as Update).tables[0]
-                logDB.type = LogConstants.DB_TYPE_UPDATE
+                type = LogConstants.DB_TYPE_UPDATE
             }
             else -> {
                 // 直接跳过
@@ -116,16 +96,12 @@ open class LogDBInterceptor : Interceptor {
                 tableName = tableArr[1]
             }
         }
-
-        // tableId & tableName
-        val connection = invocation.args[0] as Connection
-        logDB.tableId = tableName
-        logDB.tableName = getTableNameCN(tableName, connection, dbName)
+        // 执行
+        val result = invocation.proceed()
 
         // 发消息
-        MQLogUtil.logDB(logDB)
-        logger.debug("操作数据库日志记录结束,耗时: ${System.currentTimeMillis() - startTime} ms")
-        return invocation.proceed()
+        MQLogUtil.logDB(type, sql, tableName, getTableNameCN(tableName, invocation.args[0] as Connection, dbName), startTime)
+        return result
     }
 
     override fun plugin(target: Any): Any {

+ 14 - 23
zen-api/src/main/kotlin/com/gxzc/zen/logging/aop/LogRequestAspect.kt

@@ -1,11 +1,9 @@
 package com.gxzc.zen.logging.aop
 
 import com.fasterxml.jackson.databind.ObjectMapper
-import com.gxzc.zen.common.properties.PlatformProperties
 import com.gxzc.zen.logging.annotation.LogAnnotation
 import com.gxzc.zen.logging.model.LogRequest
 import com.gxzc.zen.logging.util.MQLogUtil
-import com.gxzc.zen.umps.util.SSOUtil
 import org.aspectj.lang.ProceedingJoinPoint
 import org.aspectj.lang.annotation.Around
 import org.aspectj.lang.annotation.Aspect
@@ -35,9 +33,6 @@ class LogRequestAspect {
         private val logger = LoggerFactory.getLogger(LogRequestAspect::class.java)
     }
 
-    @Autowired
-    private lateinit var platformProperties: PlatformProperties
-
     @Autowired
     private lateinit var mapper: ObjectMapper
 
@@ -82,17 +77,7 @@ class LogRequestAspect {
         val requestMethod = request.method
         val requestParam = request.queryString
 
-        val platformId = platformProperties.id!!
-        var account: String? = null
-        var accountName: String? = null
-        try {
-            account = SSOUtil.getCurAccount()!!
-            accountName = SSOUtil.getCurUserInfo()!!.username
-        } catch (e: Throwable) {
-        }
-
         val data = LogRequest().apply {
-            this.platformId = platformId
             this.requestUri = requestUri
             this.requestMethod = requestMethod
             this.requestParam = requestParam
@@ -100,25 +85,27 @@ class LogRequestAspect {
             //            this.responseBody = mapper.writeValueAsString(result)
             this.remoteHost = remoteHost
             this.method = fullMethodName
-            this.operatorAccount = account
-            this.operatorName = accountName
-            this.operatorTime = Date()
             //            this.exMsg = exMsg
             this.remark = remark
         }
+        val startTime = Date()
         return try {
-            val result = joinPoint.proceed()
 
-            data.responseBody = mapper.writeValueAsString(result)
+            val result = joinPoint.proceed()
 
+            data.apply {
+                this.responseBody = mapper.writeValueAsString(result)
+                this.operatorStartTime = startTime
+                this.operatorEndTime = Date()
+            }
             MQLogUtil.logRequest(data)
             result
         } catch (e: Throwable) {
-            // 运行时异常
+            // 运行时异常(保留5最近异常栈)
             var exMsg = e.javaClass.name + " : " + e.message + "\r\n"
             run breaking@{
                 e.stackTrace.forEachIndexed { index, it ->
-                    if (index > 9) {
+                    if (index > 4) {
                         return@breaking
                     }
                     exMsg += it
@@ -127,7 +114,11 @@ class LogRequestAspect {
             }
             exMsg += "......"
 
-            data.exMsg = exMsg
+            data.apply {
+                this.exMsg = exMsg
+                this.operatorStartTime = startTime
+                this.operatorEndTime = Date()
+            }
 
             MQLogUtil.logRequest(data)
             throw e

+ 44 - 3
zen-api/src/main/kotlin/com/gxzc/zen/logging/util/MQLogUtil.kt

@@ -1,15 +1,18 @@
 package com.gxzc.zen.logging.util
 
+import com.gxzc.zen.common.util.PlatformUtil
 import com.gxzc.zen.logging.model.LogAuth
 import com.gxzc.zen.logging.model.LogBiz
 import com.gxzc.zen.logging.model.LogDB
 import com.gxzc.zen.logging.model.LogRequest
 import com.gxzc.zen.msg.mq.MQProducerUtil
 import com.gxzc.zen.msg.mq.constants.MQConstants
+import com.gxzc.zen.umps.util.SSOUtil
 import com.maihaoche.starter.mq.base.MessageBuilder
 import org.apache.rocketmq.client.producer.SendCallback
 import org.apache.rocketmq.client.producer.SendResult
 import org.slf4j.LoggerFactory
+import java.util.*
 
 /**
  * 基于消息队列MQ的日志工具类
@@ -22,7 +25,7 @@ object MQLogUtil {
     private val mqProducer = MQProducerUtil.producer!!
 
     /**
-     * 发送 登陆日志 消息
+     * 发送登陆日志消息
      */
     fun logAuth(logAuth: LogAuth) {
         mqProducer.asyncSend(MessageBuilder.of(logAuth).topic(MQConstants.TOPIC_LOGS).tag(MQConstants.TAGS_LOGS_AUTH).build(),
@@ -37,7 +40,15 @@ object MQLogUtil {
                 })
     }
 
+    /**
+     * 发送请求日志消息
+     */
     fun logRequest(logRequest: LogRequest) {
+        logRequest.apply {
+            this.platformId = PlatformUtil.getPlatformId()
+            this.operatorAccount = SSOUtil.getCurAccount()
+            this.operatorName = SSOUtil.getCurUserName()
+        }
         mqProducer.asyncSend(MessageBuilder.of(logRequest).topic(MQConstants.TOPIC_LOGS).tag(MQConstants.TAGS_LOGS_REQUEST).build(),
                 object : SendCallback {
                     override fun onException(e: Throwable) {
@@ -50,7 +61,21 @@ object MQLogUtil {
                 })
     }
 
-    fun logDB(logDB: LogDB) {
+    /**
+     * 发送DB日志消息
+     */
+    fun logDB(type: Int, sql: String?, tableId: String?, tableName: String?, startTime: Date, endTime: Date = Date()) {
+        val logDB = LogDB().apply {
+            this.platformId = PlatformUtil.getPlatformId()
+            this.operatorStartTime = startTime
+            this.operatorEndTime = endTime
+            this.operatorAccount = SSOUtil.getCurAccount()
+            this.operatorName = SSOUtil.getCurUserName()
+            this.type = type
+            this.sql = sql
+            this.tableId = tableId
+            this.tableName = tableName
+        }
         mqProducer.asyncSend(MessageBuilder.of(logDB).topic(MQConstants.TOPIC_LOGS).tag(MQConstants.TAGS_LOGS_DB).build(),
                 object : SendCallback {
                     override fun onException(e: Throwable) {
@@ -63,7 +88,23 @@ object MQLogUtil {
                 })
     }
 
-    fun logBiz(logBiz: LogBiz) {
+    /**
+     * 发送业务日志消息
+     */
+    fun logBiz(bizCode: String, bizContent: String, remark: String, startTime: Date, endTime: Date = Date()) {
+        MQLogUtil.logBizInner(LogBiz().apply {
+            this.bizCode = bizCode
+            this.bizContent = bizContent
+            this.platformId = PlatformUtil.getPlatformId()
+            this.operatorAccount = SSOUtil.getCurAccount()
+            this.operatorName = SSOUtil.getCurUserName()
+            this.operatorStartTime = startTime
+            this.operatorEndTime = endTime
+            this.remark = remark
+        })
+    }
+
+    private fun logBizInner(logBiz: LogBiz) {
         mqProducer.asyncSend(MessageBuilder.of(logBiz).topic(MQConstants.TOPIC_LOGS).tag(MQConstants.TAGS_LOGS_BIZ).build(),
                 object : SendCallback {
                     override fun onException(e: Throwable) {