在 log4j 中重新连接到数据库

发布于 2024-09-26 19:28:18 字数 75 浏览 0 评论 0原文

如果我配置了 JDBCAppender 将日志消息发送到 MySQL 并且,当我的系统启动时,我重新启动数据库,它会重新连接到数据库吗?

If I have a JDBCAppender configured to throw log messages to MySQL
and, while my system is up I restart the database is it reconnect to DB?

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

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

发布评论

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

评论(2

表情可笑 2024-10-03 19:28:18

我在上周末就遇到过这个用例。我的数据库由亚马逊AWS托管。它翻转了我的日志数据库,并且通过 Log4j JDBC Appender 记录到该数据库的所有实例都停止了记录。我退回了其中一个应用程序,它恢复了日志记录。

因此,根据经验,这个问题的答案似乎是

如果数据库出现故障并重新联机,则 JDBC 附加程序不会自动重新连接。

编辑

JDBCAppender getConnection 可能会被重写来修复。

I have had this use case occur over this past weekend. My database is hosted by Amazon AWS. It rolled over my log database and all of the instances logging to that database via the Log4j JDBC Appender stopped logging. I bounced one of the apps and it resumed logging.

So the answer to this question, through experience, appears to be No.

If the database goes down and comes back online, the JDBC appender does not reconnect automatically.

edit

JDBCAppender getConnection might be overridden to fix.

泪眸﹌ 2024-10-03 19:28:18

log4j 1.2.15 中的 JDBCAppender 具有以下代码

protected Connection getConnection() throws SQLException {
      if (!DriverManager.getDrivers().hasMoreElements())
         setDriver("sun.jdbc.odbc.JdbcOdbcDriver");

      if (connection == null) {
        connection = DriverManager.getConnection(databaseURL, databaseUser,
                    databasePassword);
      }

      return connection;
  }

,因此如果连接不为空,但已损坏(需要重新连接),log4j 会将损坏的连接返回到其逻辑,并且执行记录到数据库的语句将失败。

不是解决方法,但正确的解决方案是将 log4j 替换为 logback:请参阅相关答案: 使用 log4j 登录到数据库

JDBCAppender in log4j 1.2.15 has following code

protected Connection getConnection() throws SQLException {
      if (!DriverManager.getDrivers().hasMoreElements())
         setDriver("sun.jdbc.odbc.JdbcOdbcDriver");

      if (connection == null) {
        connection = DriverManager.getConnection(databaseURL, databaseUser,
                    databasePassword);
      }

      return connection;
  }

so if connection is not null, but is broken (needs reconnect) log4j will return broken connection to its logic, and executing statement which does logging to db will fail.

Not a workaround, but a proper solution is to replace log4j with logback: see related answer: Log to a database using log4j

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