查看: 628|回复: 0

[Java语言] 自定义日志操作功能的实现

发表于 2018-2-4 10:15:40
  1. @Service("logService")
  2. public class LogServiceImpl implements LogService {
  3. private Log logger = LogFactory.getLog(this.getClass());
  4. @Autowired
  5. private LogDao logMapper;
  6. @SuppressWarnings("rawtypes")
  7. @Override
  8. public void log(Class clz, String method, String logInfo, String logType, String errorCode) {
  9. LogPojo logDto = new LogPojo(this.getClassName(clz), errorCode, logType, method, exInfoSubstring(logInfo));
  10. this.log(logDto);
  11. }
  12. @Override
  13. @Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=false)
  14. public void log(LogPojo logDto) {
  15. if (null == logDto) {
  16. return;
  17. }
  18. try {
  19. if (LogType.ERROR == logDto.getLogType()) {
  20. logMapper.insertErrorLog(logDto);
  21. } else {
  22. logMapper.insertTracerLog(logDto);
  23. }
  24. } catch (Exception e) {
  25. // TODO Auto-generated catch block
  26. logger.error("保存日志出错 - LogPojo:"+ JSON.toJSONString(logDto) + " ErrorInfo:" + e.getMessage());
  27. }
  28. }
  29. @SuppressWarnings("rawtypes")
  30. @Override
  31. @Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=false)
  32. public void error(Class clz, String errorCode, String errorMethod, String logInfo) {
  33. // TODO Auto-generated method stub
  34. LogPojo logDto = new LogPojo(this.getClassName(clz), errorCode, LogType.ERROR, errorMethod, exInfoSubstring(logInfo));
  35. try {
  36. logMapper.insertErrorLog(logDto);
  37. } catch (Exception e) {
  38. // TODO Auto-generated catch block
  39. logger.error("保存错误日志出错 - LogPojo:"+ JSON.toJSONString(logDto) + " ErrorInfo:" + e.getMessage());
  40. }
  41. }
  42. @Override
  43. @Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=false)
  44. public void error(Exception ex) {
  45. LogPojo logDto = null;
  46. StringWriter sw = new StringWriter();
  47. PrintWriter pw = new PrintWriter(sw, true);
  48. try {
  49. StackTraceElement[] st = ex.getStackTrace();
  50. StackTraceElement stackTraceElement = null;
  51. String exclass = "";
  52. String method = "";
  53. String message = "";
  54. //保存系统类出现的异常
  55. for (int i = 0; i < st.length; i++) {
  56. stackTraceElement = st[i];
  57. exclass = stackTraceElement.getClassName();
  58. method = stackTraceElement.getMethodName();
  59. if(exclass.startsWith("com.pingan.imsp")) {
  60. message = new Date() + ":" + "[类:" + exclass + "]调用" + method + "时在第" + stackTraceElement.getLineNumber() + "行代码处发生异常!异常类型:" + ex.getClass().getName();
  61. logDto = new LogPojo(exclass, "" , LogType.ERROR, method, exInfoSubstring(message));
  62. logMapper.insertErrorLog(logDto);
  63. }
  64. }
  65. ex.printStackTrace(pw);
  66. pw.flush();
  67. sw.flush();
  68. logDto = new LogPojo(exclass, "" , LogType.ERROR, method, exInfoSubstring(sw.toString()));
  69. logMapper.insertErrorLog(logDto);
  70. //保存最后一个
  71. if(st.length>1){
  72. stackTraceElement = st[st.length-1];
  73. exclass = stackTraceElement.getClassName();
  74. method = stackTraceElement.getMethodName();
  75. message = new Date() + ":" + "[类:" + exclass + "]调用" + method + "时在第" + stackTraceElement.getLineNumber() + "行代码处发生异常!异常类型:" + ex.getClass().getName();
  76. logDto = new LogPojo(exclass, "" , LogType.ERROR, method, exInfoSubstring(message));
  77. logMapper.insertErrorLog(logDto);
  78. }
  79. } catch (Exception e) {
  80. logger.error("保存错误日志出错 - LogPojo:"+ JSON.toJSONString(logDto) + " ErrorInfo:" + e.getMessage());
  81. } finally{
  82. pw.close();
  83. try {
  84. sw.close();
  85. } catch (IOException e) {
  86. e.printStackTrace();
  87. }
  88. }
  89. }
  90. @SuppressWarnings("rawtypes")
  91. private String getClassName(Class clz) {
  92. return null == clz ? "" : clz.getName();
  93. }
  94. private String exInfoSubstring(String exInfo) {
  95. int ex_length = 3999;
  96. if(exInfo == null || exInfo.equals("")) {
  97. return "";
  98. }
  99. int byteLength = 0;
  100. for (int i = 0; i < exInfo.length(); i++) {
  101. char c = exInfo.charAt(i);
  102. if (c > 256) {
  103. byteLength+=3;
  104. }else{
  105. byteLength++;
  106. }
  107. }
  108. if(byteLength <= ex_length) {
  109. return exInfo;
  110. } else {
  111. int zhongwenLength = 0;
  112. for (int i = 0; i < exInfo.length(); i++) {
  113. char c = exInfo.charAt(i);
  114. if (c > 256) {
  115. zhongwenLength++;
  116. }
  117. }
  118. return exInfo.substring(0, ex_length-2*zhongwenLength);
  119. }
  120. }
  121. /**
  122. * 定时任务备份日志表30天之前的数据到备份表
  123. * @throws Exception
  124. */
  125. @Override
  126. public void backupLogData() throws Exception {
  127. try{
  128. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  129. Calendar cal = Calendar.getInstance();
  130. cal.add(Calendar.DATE, -30);
  131. Date date = cal.getTime();
  132. //将30天前的执行日志数据插入到备份表中
  133. logMapper.insertTracerLogBackUp(sdf.format(date));
  134. //将30天前的错误日志数据插入到备份表中
  135. logMapper.insertErrorLogBackUp(sdf.format(date));
  136. //删除30天前的执行日志数据
  137. logMapper.deleteTracerLog(sdf.format(date));
  138. //删除30天前的错误日志数据
  139. logMapper.deleteErrorLog(sdf.format(date));
  140. logger.info("日志表数据备份成功!");
  141. }catch(Exception e){
  142. e.printStackTrace();
  143. logger.info("备份日志表数据失败!");
  144. throw new Exception(e);
  145. }
  146. }
  147. }
复制代码
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="com.core.common.log.dao.LogDao">
  5. <!-- 插入错误日志 -->
  6. <insert id="insertErrorLog" parameterType="com.paic.core.common.log.LogPojo">
  7. insert into avs_error_log
  8. (
  9. ID_ERROR_LOG,
  10. CLASS_NAME,
  11. ERROR_CODE,
  12. ERROR_METHOD,
  13. ERROR_INFO,
  14. CREATED_BY,
  15. CREATED_DATE,
  16. UPDATED_BY,
  17. UPDATED_DATE
  18. )values
  19. (
  20. sys_guid(),
  21. #{className, jdbcType=VARCHAR},
  22. #{errorCode, jdbcType=VARCHAR},
  23. #{method, jdbcType=VARCHAR},
  24. #{logInfo, jdbcType=VARCHAR},
  25. 'system',
  26. sysdate,
  27. 'system',
  28. sysdate
  29. )
  30. </insert>
  31. <!-- 插入Tracer 日志 -->
  32. <insert id="insertTracerLog" parameterType="com.paic.core.common.log.LogPojo">
  33. insert into avs_tracer_log
  34. (
  35. ID_TRACER_LOG,
  36. CLASS_NAME,
  37. METHOD,
  38. LOG_TYPE,
  39. LOG_INFO,
  40. CREATED_BY,
  41. CREATED_DATE,
  42. UPDATED_BY,
  43. UPDATED_DATE
  44. )values
  45. (
  46. sys_guid(),
  47. #{className, jdbcType=VARCHAR},
  48. #{method, jdbcType=VARCHAR},
  49. #{logType, jdbcType=VARCHAR},
  50. #{logInfo, jdbcType=VARCHAR},
  51. 'system',
  52. sysdate,
  53. 'system',
  54. sysdate
  55. )
  56. </insert>
  57. <!-- 备份30天前Tracer日志 -->
  58. <insert id="insertTracerLogBackUp" parameterType="java.lang.String">
  59. insert into avs_tracer_log_bak
  60. (ID_TRACER_LOG,
  61. CLASS_NAME,
  62. METHOD,
  63. LOG_TYPE,
  64. LOG_INFO,
  65. CREATED_BY,
  66. CREATED_DATE,
  67. UPDATED_BY,
  68. UPDATED_DATE)
  69. select sys_guid(),
  70. CLASS_NAME,
  71. METHOD,
  72. LOG_TYPE,
  73. LOG_INFO,
  74. 'system',
  75. SYSDATE,
  76. 'system',
  77. SYSDATE
  78. from avs_tracer_log
  79. where TRUNC(CREATED_DATE) <= to_date(#{date,jdbcType=VARCHAR},'YYYY-MM-DD')
  80. </insert>
  81. <!-- 备份30天前Error日志 -->
  82. <insert id="insertErrorLogBackUp" parameterType="java.lang.String">
  83. insert into avs_error_log_bak
  84. (ID_ERROR_LOG,
  85. CLASS_NAME,
  86. ERROR_CODE,
  87. ERROR_METHOD,
  88. ERROR_INFO,
  89. CREATED_BY,
  90. CREATED_DATE,
  91. UPDATED_BY,
  92. UPDATED_DATE)
  93. select sys_guid(),
  94. CLASS_NAME,
  95. ERROR_CODE,
  96. ERROR_METHOD,
  97. ERROR_INFO,
  98. 'system',
  99. SYSDATE,
  100. 'system',
  101. SYSDATE
  102. from avs_error_log
  103. where TRUNC(CREATED_DATE) <= to_date(#{date,jdbcType=VARCHAR},'YYYY-MM-DD')
  104. </insert>
  105. <!-- 删除 30天前Tracer日志-->
  106. <delete id="deleteTracerLog" parameterType="java.lang.String">
  107. delete from avs_tracer_log where TRUNC(CREATED_DATE) <= to_date(#{date,jdbcType=VARCHAR},'YYYY-MM-DD')
  108. </delete>
  109. <!-- 删除 30天前Error日志-->
  110. <delete id="deleteErrorLog" parameterType="java.lang.String">
  111. delete from avs_error_log where TRUNC(CREATED_DATE) <= to_date(#{date,jdbcType=VARCHAR},'YYYY-MM-DD')
  112. </delete>
  113. </mapper>
复制代码


回复

使用道具 举报