日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

log4j2 mysql_spring boot使用log4j2将日志写入mysql数据库

發布時間:2025/3/12 数据库 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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数据库的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。