log4j2 mysql_spring boot使用log4j2将日志写入mysql数据库
log4j2官方例子在spring boot中报错而且还是用的是org.apache.commons.dbcp包
我给改了一下使用org.apache.commons.dbcp2包
1.log4j2.xml如下:
method="getDatabaseConnection" />
includeLocation="true">
AsyncLogger 表示是异步插入.需要在pom.xml中插入disruptor引用
com.lmax
disruptor
3.4.1
2.创建LogConnectionFactory类:
package com.malls.common.tool;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.ConnectionFactory;
import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
import org.apache.commons.dbcp2.PoolableConnection;
import org.apache.commons.dbcp2.PoolableConnectionFactory;
import org.apache.commons.dbcp2.PoolingDataSource;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import com.malls.common.model.DBConfig;
public class LogConnectionFactory {
private static interface Singleton {
final LogConnectionFactory INSTANCE = new LogConnectionFactory();
}
private DataSource dataSource;
private LogConnectionFactory() {
}
private void initDataSource() {
try {
//
// First, we'll create a ConnectionFactory that the
// pool will use to create Connections.
// We'll use the DriverManagerConnectionFactory,
// using the connect string passed in the command line
// arguments.
DBConfig dbConfig = ApplicationConfig.GetDbConfig("dblog");
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(dbConfig.getUrl(),
dbConfig.getUserName(), dbConfig.getPassword());
//
// Next we'll create the PoolableConnectionFactory, which wraps
// the "real" Connections created by the ConnectionFactory with
// the classes that implement the pooling functionality.
//
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
null);
//
// Now we'll need a ObjectPool that serves as the
// actual pool of connections.
//
// We'll use a GenericObjectPool instance, although
// any ObjectPool implementation will suffice.
//
ObjectPool connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
// Set the factory's pool property to the owning pool
poolableConnectionFactory.setPool(connectionPool);
//
// Finally, we create the PoolingDriver itself,
// passing in the object pool we created.
//
dataSource = new PoolingDataSource<>(connectionPool);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
dataSource = null;
}
}
int i = 0;
private static Lock lock = new ReentrantLock();
public static Connection getDatabaseConnection() throws SQLException {
if (Singleton.INSTANCE.i == 0) {
//这儿如果第一次直接返回连接池的话会报错
//因为PoolableConnectionFactory也使用了log4j记录日志
//这儿是重点
Singleton.INSTANCE.i++;
DBConfig dbConfig = ApplicationConfig.GetDbConfig("dblog");
return DriverManager.getConnection(dbConfig.getUrl(), dbConfig.getUserName(), dbConfig.getPassword());
}
if (Singleton.INSTANCE.dataSource == null) {
lock.lock();
try {
if (Singleton.INSTANCE.dataSource == null) {
Singleton.INSTANCE.initDataSource();
}
} finally {
lock.unlock();
}
}
return Singleton.INSTANCE.dataSource.getConnection();
}
}
要注意注释的地方,第二次才返回连接池
3.创建DBLog类:
package com.malls.common.tool;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.StructuredDataMessage;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import com.malls.common.model.RequestModel;
public class DBLog {
private static final Logger LOGGER = LogManager.getLogger("AsyncDBLogger");
public static void process(String logType, String content) {
process(logType, content, "");
}
public static void process(String logType, String content, String keyWord) {
StructuredDataMessage msg = getataMessage(logType, content, keyWord);
addMsg(msg, "logLevel", "Process");
LOGGER.info(msg);
}
public static void error(String logType, String content) {
error(logType, content, "");
}
public static void error(String logType, String content, String keyWord) {
StructuredDataMessage msg = getataMessage(logType, content, keyWord);
addMsg(msg, "logLevel", "Error");
LOGGER.error(msg);
}
public static void handle(String logType, String content) {
handle(logType, content, "");
}
public static void handle(String logType, String content, String keyWord) {
StructuredDataMessage msg = getataMessage(logType, content, keyWord);
addMsg(msg, "LogLevel", "Handle");
LOGGER.info(msg);
}
private static StructuredDataMessage getataMessage(String logType, String content, String keyWord) {
String confirm = UUID.randomUUID().toString().replace("-", "");
StructuredDataMessage msg = new StructuredDataMessage(confirm, "", "transfer");
RequestAttributes req = RequestContextHolder.currentRequestAttributes();
RequestModel requestModel = null;
if (req != null) {
requestModel = (RequestModel) req.getAttribute("RequestModel", RequestAttributes.SCOPE_REQUEST);
}
if (requestModel == null) {
requestModel = new RequestModel();
}
addMsg(msg, "RequestKey", requestModel.getRequestKey());
addMsg(msg, "RequestUrl", requestModel.getRequestUrl());
addMsg(msg, "UserName", String.valueOf(requestModel.getCurrentUserId()));
addMsg(msg, "OrderNo", requestModel.getOrderNo());
addMsg(msg, "LogType", logType);
addMsg(msg, "Content", content);
addMsg(msg, "Keyword", keyWord);
addMsg(msg, "ClientIP", requestModel.getClientIP());
long timeLong = Duration.between(requestModel.getBeginRequestTime(), LocalDateTime.now()).toMillis();
addMsg(msg, "TimeLong", String.valueOf(timeLong));
addMsg(msg, "ServerDesc", "777");
addMsg(msg, "RequestServerIP", requestModel.getRequestServerIP());
addMsg(msg, "ServerIP", requestModel.getServerIP());
addMsg(msg, "CurrentApiRequestKey", requestModel.getCurrentApiRequestKey());
addMsg(msg, "LogTime", LocalDateTime.now().toString());
return msg;
}
private static void addMsg(StructuredDataMessage msg, String key, String val) {
if (val == null) {
msg.put(key, "");
} else {
msg.put(key, val);
}
}
}
这样就可以了.
log4j2 mysql_spring boot使用log4j2将日志写入mysql数据库相关推荐
- 关于log4net日志写入mysql数据库记录
网上关于log4net日志写入mysql数据库的博客感觉比较少,所以这边搞定之后先过来记录一下. 首先新建个项目,我命名是log4netDemo,然后需要引入两个dll,一个是mysql.dll,一个 ...
- 【python】通过loging模块将日志写入mysql数据库
建立新的py文件,用于写DB日志写入 文件名dblog.py # coding: utf-8 import logging import pymysqlclass DatabaseLogHandler ...
- springbooot mysql_Spring Boot入门(2)使用MySQL数据库
介绍 本文将介绍如何在Spring项目中连接.处理MySQL数据库. 该项目使用Spring Data JPA和Hibernate来连接.处理MySQL数据库,当然,这仅仅是其中一种方式,你也可以使用 ...
- Python将日志写入MySQL数据库
今天开发需求:把某个日志里面的内容写入数据库存储,方便调阅. 日志类型,每天会生成一个,里面有6个字段: 第一个字段是时间,但是只有时分秒(xx:xx:xx) 第二个字段和第三个字段还有第五个字段只是 ...
- springdata和mysql_Spring Boot使用Spring Data JPA访问MySQL数据库
它使用Spring Data JPA来访问数据库,但这只是众多可能选择中的一种(例如,您可以使用普通的Spring JDBC). mysql建立数据库,添加用户,并且授权 mysql> crea ...
- ELK之收集日志到mysql数据库
写入数据库的目的是持久化保存重要数据,比如状态码.客户端浏览器版本等,用于后期按月做数据统计等. 环境准备 linux-elk1:10.0.0.22,Kibana ES Logstash Nginx ...
- python 并发 数据库_python写入mysql数据库
scrapy爬虫成长日记之将抓取内容写入mysql数据库 前面小试了一下scrapy抓取博客园的博客(您可在此查看scrapy爬虫成长日记之创建工程-抽取数据-保存为json格式的数据),但是前面抓取 ...
- spring boot+kafka+canal实现监听MySQL数据库
spring boot+kafka+canal实现监听MySQL数据库 一.zookeeper安装 kafka依赖于zookeeper,安装kafka前先安装zookeeper 下载地址:Apache ...
- SparkStreaming读取Kafka数据源并写入Mysql数据库
SparkStreaming读取Kafka数据源并写入Mysql数据库 一.实验环境 本实验所用到的工具有 kafka_2.11-0.11.0.2: zookeeper-3.4.5: spark-2. ...
最新文章
- CMD 一条命令 执行 多条命令
- C++_member template成员模板
- 深度学习(计算机视觉)面试中问题(一)
- 切记:只有肯吃苦才能赚大钱!
- 重庆大学计算机组成,重庆大学计算机组成原理试题集(含部分答案)
- No.3 - CSS transition 和 CSS transform 配合制作动画
- Linux下查看CPU使用率 --- top命令的使用
- oracle数据库月份日期固定,oracle 日期函数介绍-数据库专栏,ORACLE
- simple_html_dom.php 使用 乱码处理作者:gaoming13
- Ubuntu系统上安装微信(legacy)
- Linux查看进程是否占用,Linux 下查看哪个进程占用swap空间
- 骑士CMS模版注入+文件包含getshell漏洞复现
- OBJ格式模型详细介绍
- 2022年电工(技师)考试题及电工(技师)模拟试题
- 原生js实现轮盘抽奖,控制中奖概率(完整示例)
- ArcGIS 实验理论基础十五 空间查询
- SAP UI5 应用开发教程之八十三 - SAP UI5 的自动化测试套件页面的开发步骤介绍试读版
- PostgreSQL对汉字按拼音排序
- AutoResetEvent 与 ManualResetEvent区别
- vue中新增弹出对话框操作
热门文章
- c++代码转为go_Go语言学习笔记六--string编码
- [转载] python基础入门二
- Java Double类hashCode()方法及示例
- python统计行号_利用Python进行数据分析(第三篇上)
- micropython 蜂鸣器_基于MicroPython的TPYBoard微信远程可燃气体报警器的设计与实现...
- python文件读写用到的库_Python使用pyshp库读取shapefile信息的方法
- Linux中常用的命令
- ug10许可证错误一8_面对排污许可证后监督检查,企业应做好哪些准备?
- 计算机毕业设计谢辞怎么写,毕业论文谢辞怎么写(通用8篇)
- android界面设计字体大小,Andoird用户界面设计上手指南:设置字体大小