log4j 记录到数据库(在集群中)

发布于 2024-08-10 22:01:19 字数 465 浏览 6 评论 0原文

我有一个 Java 应用程序,它在集群中的两台机器上运行,它们都记录到一个 MySQL 数据库。一切正常,但我希望数据库中有一个附加字段,它表示请求来自的 IP。
我通过使用两个不同的 log4j.properties 文件解决了这个问题,但我想有更好的方法来做到这一点?

这是 log4j.properties 文件中的行,该行在机器上有所不同:

log4j.appender.DB.sql=INSERT INTO log4j (date, category, priority, server, message) VALUES ('%d{dd MMM yyyy HH:mm:ss,SSS}','%c','%p','10.20.30.40','%m')

Is there those for MySQL like connection_ip?或者 log4j 中的占位符,以便我可以将 Java 应用程序的 IP 存储在其中?

I have a Java application which runs on two machines in a cluster and they both log to one MySQL database. Everything works fine, but I would like to have an additional field in the database which represents the IP where the requests is coming from.
I solved this by having two different log4j.properties files, but I guess there is a nicer way to do that?

This is the line in the log4j.properties file that is different on the machines:

log4j.appender.DB.sql=INSERT INTO log4j (date, category, priority, server, message) VALUES ('%d{dd MMM yyyy HH:mm:ss,SSS}','%c','%p','10.20.30.40','%m')

Is there something for MySQL like connection_ip? Or a placeholder in log4j, so that I could store the IP in there from the Java application?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谈情不如逗狗 2024-08-17 22:01:19

我通过使用 log4j 的映射诊断上下文解决了这个问题。
当我启动 Java 应用程序时,我使用此命令存储 IP。

MDC.put("serverIP", InetAddress.getLocalHost().getHostAddress());

现在我可以在 log4j.properties 文件中使用 %X{serverIP} 作为占位符。

log4j.appender.DB.sql=INSERT INTO log4j (date, category, priority, server, sessionID, message) VALUES ('%d{dd/MM/yyyy HH:mm:ss,SSS}','%c','%p','%X{serverIP}','%X{sessionID}','%m')

这是一篇关于 log4j 的优秀文章,其中有一些很好的示例
http://onjava.com/pub/ a/onjava/2002/08/07/log4j.html?page=3

I solved this by using the Mapped Diagnostic Context of log4j.
When I start the Java application I store the IP with this command.

MDC.put("serverIP", InetAddress.getLocalHost().getHostAddress());

And now I can use the %X{serverIP} as a placeholder in my log4j.properties file.

log4j.appender.DB.sql=INSERT INTO log4j (date, category, priority, server, sessionID, message) VALUES ('%d{dd/MM/yyyy HH:mm:ss,SSS}','%c','%p','%X{serverIP}','%X{sessionID}','%m')

Here is a excellent post about log4j with a few good examples
http://onjava.com/pub/a/onjava/2002/08/07/log4j.html?page=3

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文