SpringBoot项目中日志写入数据库,最主要的核心类就是DBAppender。
我使用的MySQL数据库,创建auge_log数据库,执行以下内容建表。
BEGIN;
DROP TABLE IF EXISTS logging_event_property;
DROP TABLE IF EXISTS logging_event_exception;
DROP TABLE IF EXISTS logging_event;
COMMIT;
BEGIN;
CREATE TABLE logging_event
(
timestmp BIGINT NOT NULL,
formatted_message TEXT NOT NULL,
logger_name VARCHAR(254) NOT NULL,
level_string VARCHAR(254) NOT NULL,
thread_name VARCHAR(254),
reference_flag SMALLINT,
arg0 VARCHAR(254),
arg1 VARCHAR(254),
arg2 VARCHAR(254),
arg3 VARCHAR(254),
caller_filename VARCHAR(254) NOT NULL,
caller_class VARCHAR(254) NOT NULL,
caller_method VARCHAR(254) NOT NULL,
caller_line CHAR(4) NOT NULL,
event_id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
COMMIT;
BEGIN;
CREATE TABLE logging_event_property
(
event_id BIGINT NOT NULL,
mapped_key VARCHAR(254) NOT NULL,
mapped_value TEXT,
PRIMARY KEY(event_id, mapped_key),
FOREIGN KEY (event_id) REFERENCES logging_event(event_id)
);
COMMIT;
BEGIN;
CREATE TABLE logging_event_exception
(
event_id BIGINT NOT NULL,
i SMALLINT NOT NULL,
trace_line VARCHAR(254) NOT NULL,
PRIMARY KEY(event_id, i),
FOREIGN KEY (event_id) REFERENCES logging_event(event_id)
);
COMMIT;
然后在pom中添加的dbcp的依赖
commons-dbcp
commons-dbcp
之后在logback.xml中添加写入数据库的配置信息(这里设置了写入数据库的日志级别为error,root日志级别为INFO)
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/auge_log?characterEncoding=UTF-8
root
123456
error
ACCEPT
DENY
示例:
Logger logger = LoggerFactory.getLogger(UserController.class);
@RequestMapping("/login")
@LogApi(info = "用户登陆")
public String login(String loginName, String password, Model model){
User user = userService.getUserByLogin(loginName,password);
if(user==null){
//在此试验是否写入数据库
logger.error("用户名或密码错误,请重新登录");
model.addAttribute("emg","用户名或密码错误,请重新登录");
return "login";
}
logger.info("测试info级别是否也能写入数据库");
session.setAttribute("user",user);
return "index";
}
查看数据库记录如下:
说明配置成功了(只有error才会写入数据库)