我正在尝试使用
log4j2
将我的事件记录在我的数据库中。具体来说,我在属性配置文件中使用 log4j2
jdbc appender
来实现此目的。
这是我的 log4j2 属性文件中的附加程序:
# Custom log levels
customLevels = D
customLevels.D.name = ACTIVITY
customLevel.ACTIVITY = 50
# JDBC appender
appender.db.type = Jdbc
appender.db.name = databaseAppender
appender.db.tableName = db_name.test
appender.db.cf.type = ConnectionFactory
appender.db.cf.class = com.myproject.FactoryConnection
appender.db.cf.method = getConnection
appender.db.col1.type = Column
appender.db.col1.name = id
appender.db.col1.pattern = ${id}
appender.db.col2.type = Column
appender.db.col2.name = message
appender.db.col2.pattern = ${message}
appender.db.filter.threshold.type = ThresholdFilter
appender.db.filter.threshold.level = activity
appender.db.filter.threshold.onMatch = Accept
appender.db.filter.threshold.onMismatch = Deny
我将字符串 id 和消息放在 Map 中并将它们传递到我的日志:
Map<String, String> map = new HashMap<>();
map.put("id", "12");
map.put("message", "this is test");
LOG.log(Level.getLevel("ACTIVITY"), new StringMapMessage(map));
它成功地将其记录到我的数据库中。
现在我的问题是我已将数据库中的 id 数据类型设置为 VARCHAR,以便可以从这里发送字符串。但我的数据库中的 id 需要是
INT(11)
类型。当我设置时,我无法像上面那样设置日志记录,因为 StringMapMessage 只接受字符串值。
现在我不能这样做:
Map<String, Object> map = new HashMap<>();
map.put("id", 12345); //<<<send integer value
map.put("message", "this is test");
LOG.log(Level.getLevel("ACTIVITY"), new StringMapMessage(map));
我已经尝试使用 objectmessage 等几个小时了。我该如何解决这个问题?谢谢。
你不需要把它放在整数上。您可以在写入数据库时传递字符串中的数值,它会自动转换为整数。但是,如果您将非数字值放入 int 数据库字段中,您将收到类似“Caused by: java.sql.BatchUpdateException: Inquate value: 'non-numeric(maybe a)' for columns 'column_name'”的错误。因此,在将字符串值传递给整数数据库字段时要小心。
Map<String, String> map = new HashMap<>();
map.put("id", "12345"); //make it String log4j2 automatically configures to int in db
map.put("message", "this is test");
LOG.log(Level.getLevel("ACTIVITY"), new StringMapMessage(map));
如果您仍然遇到错误,则上面的示例是正确的解决方案,这可能是由于其他方面的问题造成的。谢谢。
设置log4j.xml
<ColumnMapping name="job_id" pattern="%X{job.id}" type="java.lang.Long"/>