log4j2官方例子在spring boot中报错而且还是用的是org.apache.commons.dbcp包

我给改了一下使用org.apache.commons.dbcp2包

1.log4j2.xml如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <Configuration status="error">
  3. <Appenders>
  4. <Console name="Console" target="SYSTEM_OUT">
  5. <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
  6. </Console>
  7. <JDBC name="DBLogger" tableName="MicroServiceLogHandle">
  8. <ConnectionFactory class="com.malls.common.tool.LogConnectionFactory"
  9. method="getDatabaseConnection" />
  10. <Column name="RequestKey" pattern="${sd:RequestKey}" />
  11. <Column name="LogType" pattern="${sd:LogType}" />
  12. <Column name="RequestUrl" pattern="${sd:RequestUrl}" />
  13. <Column name="UserName" pattern="${sd:UserName}" />
  14. <Column name="OrderNo" pattern="${sd:OrderNo}" />
  15. <Column name="Content" pattern="${sd:Content}" />
  16. <Column name="Keyword" pattern="${sd:Keyword}" />
  17. <Column name="ClientIP" pattern="${sd:ClientIP}" />
  18. <Column name="TimeLong" pattern="${sd:TimeLong}" />
  19. <Column name="LogTime" pattern="${sd:LogTime}" />
  20. <Column name="DBCreateTime" literal="now()" />
  21. <Column name="ServerDesc" pattern="${sd:ServerDesc}" />
  22. <Column name="LogLevel" pattern="${sd:LogLevel}" />
  23. <Column name="RequestServerIP" pattern="${sd:RequestServerIP}" />
  24. <Column name="ServerIP" pattern="${sd:ServerIP}" />
  25. <Column name="CurrentApiRequestKey" pattern="${sd:CurrentApiRequestKey}" />
  26. </JDBC>
  27. </Appenders>
  28. <Loggers>
  29. <AsyncLogger name="AsyncDBLogger" level="debug"
  30. includeLocation="true">
  31. <AppenderRef ref="DBLogger" />
  32. </AsyncLogger>
  33. <Root level="info">
  34. <AppenderRef ref="Console" />
  35. </Root>
  36. </Loggers>
  37. </Configuration>
  1. AsyncLogger 表示是异步插入.需要在pom.xml中插入disruptor引用
  1. <dependency>
  2. <groupId>com.lmax</groupId>
  3. <artifactId>disruptor</artifactId><!-- log4j异步插入用到 -->
  4. <version>3.4.1</version>
  5. </dependency>

2.创建LogConnectionFactory类:

  1. package com.malls.common.tool;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.SQLException;
  6. import java.util.concurrent.locks.Lock;
  7. import java.util.concurrent.locks.ReentrantLock;
  8.  
  9. import javax.sql.DataSource;
  10.  
  11. import org.apache.commons.dbcp2.ConnectionFactory;
  12. import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
  13. import org.apache.commons.dbcp2.PoolableConnection;
  14. import org.apache.commons.dbcp2.PoolableConnectionFactory;
  15. import org.apache.commons.dbcp2.PoolingDataSource;
  16. import org.apache.commons.pool2.ObjectPool;
  17. import org.apache.commons.pool2.impl.GenericObjectPool;
  18.  
  19. import com.malls.common.model.DBConfig;
  20.  
  21. public class LogConnectionFactory {
  22.  
  23. private static interface Singleton {
  24. final LogConnectionFactory INSTANCE = new LogConnectionFactory();
  25. }
  26.  
  27. private DataSource dataSource;
  28.  
  29. private LogConnectionFactory() {
  30.  
  31. }
  32.  
  33. private void initDataSource() {
  34.  
  35. try {
  36. //
  37. // First, we'll create a ConnectionFactory that the
  38. // pool will use to create Connections.
  39. // We'll use the DriverManagerConnectionFactory,
  40. // using the connect string passed in the command line
  41. // arguments.
  42. DBConfig dbConfig = ApplicationConfig.GetDbConfig("dblog");
  43. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(dbConfig.getUrl(),
  44. dbConfig.getUserName(), dbConfig.getPassword());
  45.  
  46. //
  47. // Next we'll create the PoolableConnectionFactory, which wraps
  48. // the "real" Connections created by the ConnectionFactory with
  49. // the classes that implement the pooling functionality.
  50. //
  51. PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
  52. null);
  53.  
  54. //
  55. // Now we'll need a ObjectPool that serves as the
  56. // actual pool of connections.
  57. //
  58. // We'll use a GenericObjectPool instance, although
  59. // any ObjectPool implementation will suffice.
  60. //
  61. ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
  62.  
  63. // Set the factory's pool property to the owning pool
  64. poolableConnectionFactory.setPool(connectionPool);
  65.  
  66. //
  67. // Finally, we create the PoolingDriver itself,
  68. // passing in the object pool we created.
  69. //
  70. dataSource = new PoolingDataSource<>(connectionPool);
  71. } catch (Exception e) {
  72. // TODO 自动生成的 catch 块
  73. e.printStackTrace();
  74. dataSource = null;
  75. }
  76.  
  77. }
  78.  
  79. int i = 0;
  80. private static Lock lock = new ReentrantLock();
  81.  
  82. public static Connection getDatabaseConnection() throws SQLException {
  83. if (Singleton.INSTANCE.i == 0) {
  84. //这儿如果第一次直接返回连接池的话会报错
  85. //因为PoolableConnectionFactory也使用了log4j记录日志
  86. //这儿是重点
  87. Singleton.INSTANCE.i++;
  88. DBConfig dbConfig = ApplicationConfig.GetDbConfig("dblog");
  89. return DriverManager.getConnection(dbConfig.getUrl(), dbConfig.getUserName(), dbConfig.getPassword());
  90. }
  91. if (Singleton.INSTANCE.dataSource == null) {
  92. lock.lock();
  93. try {
  94. if (Singleton.INSTANCE.dataSource == null) {
  95. Singleton.INSTANCE.initDataSource();
  96. }
  97. } finally {
  98. lock.unlock();
  99. }
  100. }
  101. return Singleton.INSTANCE.dataSource.getConnection();
  102. }
  103. }

要注意注释的地方,第二次才返回连接池

3.创建DBLog类:

  1. package com.malls.common.tool;
  2.  
  3. import java.time.Duration;
  4. import java.time.LocalDateTime;
  5. import java.util.UUID;
  6.  
  7. import org.apache.logging.log4j.LogManager;
  8. import org.apache.logging.log4j.Logger;
  9. import org.apache.logging.log4j.message.StructuredDataMessage;
  10. import org.springframework.web.context.request.RequestAttributes;
  11. import org.springframework.web.context.request.RequestContextHolder;
  12.  
  13. import com.malls.common.model.RequestModel;
  14.  
  15. public class DBLog {
  16. private static final Logger LOGGER = LogManager.getLogger("AsyncDBLogger");
  17.  
  18. public static void process(String logType, String content) {
  19. process(logType, content, "");
  20. }
  21.  
  22. public static void process(String logType, String content, String keyWord) {
  23. StructuredDataMessage msg = getataMessage(logType, content, keyWord);
  24. addMsg(msg, "logLevel", "Process");
  25. LOGGER.info(msg);
  26. }
  27.  
  28. public static void error(String logType, String content) {
  29. error(logType, content, "");
  30. }
  31.  
  32. public static void error(String logType, String content, String keyWord) {
  33. StructuredDataMessage msg = getataMessage(logType, content, keyWord);
  34. addMsg(msg, "logLevel", "Error");
  35. LOGGER.error(msg);
  36. }
  37.  
  38. public static void handle(String logType, String content) {
  39. handle(logType, content, "");
  40. }
  41.  
  42. public static void handle(String logType, String content, String keyWord) {
  43. StructuredDataMessage msg = getataMessage(logType, content, keyWord);
  44. addMsg(msg, "LogLevel", "Handle");
  45. LOGGER.info(msg);
  46. }
  47.  
  48. private static StructuredDataMessage getataMessage(String logType, String content, String keyWord) {
  49. String confirm = UUID.randomUUID().toString().replace("-", "");
  50. StructuredDataMessage msg = new StructuredDataMessage(confirm, "", "transfer");
  51. RequestAttributes req = RequestContextHolder.currentRequestAttributes();
  52. RequestModel requestModel = null;
  53. if (req != null) {
  54. requestModel = (RequestModel) req.getAttribute("RequestModel", RequestAttributes.SCOPE_REQUEST);
  55. }
  56. if (requestModel == null) {
  57. requestModel = new RequestModel();
  58. }
  59. addMsg(msg, "RequestKey", requestModel.getRequestKey());
  60. addMsg(msg, "RequestUrl", requestModel.getRequestUrl());
  61. addMsg(msg, "UserName", String.valueOf(requestModel.getCurrentUserId()));
  62. addMsg(msg, "OrderNo", requestModel.getOrderNo());
  63. addMsg(msg, "LogType", logType);
  64. addMsg(msg, "Content", content);
  65. addMsg(msg, "Keyword", keyWord);
  66. addMsg(msg, "ClientIP", requestModel.getClientIP());
  67. long timeLong = Duration.between(requestModel.getBeginRequestTime(), LocalDateTime.now()).toMillis();
  68. addMsg(msg, "TimeLong", String.valueOf(timeLong));
  69. addMsg(msg, "ServerDesc", "777");
  70. addMsg(msg, "RequestServerIP", requestModel.getRequestServerIP());
  71. addMsg(msg, "ServerIP", requestModel.getServerIP());
  72. addMsg(msg, "CurrentApiRequestKey", requestModel.getCurrentApiRequestKey());
  73. addMsg(msg, "LogTime", LocalDateTime.now().toString());
  74. return msg;
  75. }
  76.  
  77. private static void addMsg(StructuredDataMessage msg, String key, String val) {
  78. if (val == null) {
  79. msg.put(key, "");
  80. } else {
  81. msg.put(key, val);
  82. }
  83. }
  84. }

这样就可以了.

spring boot使用log4j2将日志写入mysql数据库的更多相关文章

  1. Spring Boot入门(2)使用MySQL数据库

    介绍   本文将介绍如何在Spring项目中连接.处理MySQL数据库.   该项目使用Spring Data JPA和Hibernate来连接.处理MySQL数据库,当然,这仅仅是其中一种方式,你也 ...

  2. Spring Boot项目中使用jdbctemplate 操作MYSQL数据库

    不废话,先来代码 pom文件: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http ...

  3. Spring Boot系列一:默认日志logback配置解析

    前言 今天来介绍下Spring Boot如何配置日志logback,我刚学习的时候,是带着下面几个问题来查资料的,你呢 如何引入日志? 日志输出格式以及输出方式如何配置? 代码中如何使用? 正文 Sp ...

  4. Spring Boot 学习摘要--关于日志框架

    date: 2020-01-05 16:20:00 updated: 2020-01-08 15:50:00 Spring Boot 学习摘要--关于日志框架 学习教程来自:B站 尚硅谷 1. 关于日 ...

  5. spring boot使用slf4j输出日志

    spring boot使用slf4j输出日志 https://blog.csdn.net/qq442270636/article/details/79406346 Spring Boot SLF4J日 ...

  6. Spring Boot Logback几种日志详解

    日志对于应用程序来说是非常重要的,Spring框架本身集成了不少其他工具,我们自身的应用也会使用到第三方库,所以我们推荐在Spring应用中使用SLF4J/Logback来记录日志. SLF4J与Lo ...

  7. Spring Boot中使用logback日志框架

    说明:Spring Boot在最新的版本中默认使用了logback框架.一般来说使用时只需在classpath下创建logback.xml即可,而官方推荐使用logback-spring.xml替代, ...

  8. Spring boot使用log4j打印日志

    先将maven中spring-boot-starter的日志spring-boot-starter-logging去掉 <dependency> <groupId>org.sp ...

  9. spring boot配置druid连接池连接mysql

    Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...

随机推荐

  1. HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth完全详细的说明

      HTML:scrollLeft,scrollWidth,clientWidth,offsetWidth具体指完全解释究竟哪里的距离scrollHeight: 获取对象的高度滚动. scrollLe ...

  2. nyoj 92 图片实用面积【bfs】

    图像实用区域 时间限制:3000 ms  |  内存限制:65535 KB 难度:4 描写叙述 "ACKing"同学曾经做一个图像处理的项目时.遇到了一个问题,他须要摘取出图片中某 ...

  3. Swift 中使用 SwiftyJSON 制作一个比特币价格 APP

    Swift 中处理 JSON 数据有很多种方式,可以使用原生的 NSJSONSerialization,也可以使用很多第三方库.原生的 NSJSONSerialization 方式这篇文章中介绍过.这 ...

  4. Angular升级流程

    执行命令 ng update @angular/cli --migrate-only --from=1.7.1 npm install --save-dev @angular/cli@latest 注 ...

  5. WPF4.0用tablet实现手写输入(更新XP SP3下也能手写输入方法)

    原文:WPF4.0用tablet实现手写输入(更新XP SP3下也能手写输入方法) 由于项目需求一个手写输入的控件,纠结了2天,终于搞定了. 主要是由于本人的英语不过关,一直和ocr混淆在一起,研究了 ...

  6. Redis进阶实践之十八 使用管道模式提高Redis查询的速度

    原文:Redis进阶实践之十八 使用管道模式提高Redis查询的速度 一.引言             学习redis 也有一段时间了,该接触的也差不多了.后来有一天,以为同事问我,如何向redis中 ...

  7. Win8 Metro(C#)数字图像处理--2.61哈哈镜效果

    原文:Win8 Metro(C#)数字图像处理--2.61哈哈镜效果  [函数名称] 哈哈镜效果函数  WriteableBitmap DistortingMirrorProcess(Writea ...

  8. ArcGIS中Python逆地理编码,根据坐标获取实际的地址

    import json import urllib import arcpy def getAddress(lng,lat): url= 'http://restapi.amap.com/v3/geo ...

  9. Windows实用小工具-问题步骤记录器

    今晚给大家介绍个实用的好工具,可以做简单的问题记录,再也不用截图加注释这么辛苦了····· 经测试,这东东在win7,2008 及2008R2里适用,也就是说,在win7以上的系统中才有.好了,下面直 ...

  10. Android零基础入门第43节:ListView优化和列表首尾使用

    原文:Android零基础入门第43节:ListView优化和列表首尾使用 前面连续几期都在学习ListView的各种使用方法,如果细心的同学可能会发现其运行效率是有待提高的,那么本期就来一起学习有哪 ...