java - 在 Swing 应用程序中使用 java.util.logging 包

标签 java swing logging java.util.logging

这个问题与Implementing logging in a Java application有关,但由于那里的示例代码使问题变得非常长,我决定根据目前所学的内容开始一个新问题。

为了说明我正在尝试做的事情,我有以下扩展 JFrame 的示例类:

package swingloggingsscce;

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class SwingLoggingSSCCE extends javax.swing.JFrame {

    public SwingLoggingSSCCE() {
        initComponents();
    }

    private void initComponents() {

        logButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Swing Logging SSCCE");

        logButton.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        logButton.setText("Do Log");
        logButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(147, 147, 147)
                .addComponent(logButton)
                .addContainerGap(146, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(120, 120, 120)
                .addComponent(logButton)
                .addContainerGap(143, Short.MAX_VALUE))
        );

        pack();
    }

    private void logButtonActionPerformed(java.awt.event.ActionEvent evt) {
        Logger.getLogger(SwingLoggingSSCCE.class.getName()).log(Level.INFO, "SwingLoggingFrame.logButtonActionPerformed()");
    }

    public static void main(String args[]) throws IOException {
        SwingLoggingSSCCE.initLogger();
        new SwingLoggingSSCCE().setVisible(true);
    }

    private static void initLogger() throws IOException {
        SwingLoggingSSCCE.HANDLER = new FileHandler(SwingLoggingSSCCE.LOG_FILE_NAME);
        SwingLoggingSSCCE.HANDLER.setFormatter(new SimpleFormatter());

        Logger logger = Logger.getLogger("");
        logger.setLevel(Level.INFO);
        logger.addHandler(SwingLoggingSSCCE.HANDLER);
    }

    private javax.swing.JButton logButton;

    private static final String LOG_FILE_NAME = "swingloggingsscce.log";
    private static FileHandler HANDLER = null;
}

这完全符合预期并生成以下“swingloggingsscce.log”文件:

Sep 09, 2012 8:37:43 PM swingloggingsscce.SwingLoggingSSCCE logButtonActionPerformed
INFO: SwingLoggingFrame.logButtonActionPerformed()

现在我正试图让同样的事情在我的主应用程序中工作。这是带有 main() 的类:

/*
 * This file is part of BBCT.
 *
 * Copyright 2012 codeguru <codeguru@users.sourceforge.net>
 *
 * BBCT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * BBCT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package bbct;

import bbct.data.BaseballCardIO;
import bbct.data.BaseballCardJDBCIO;
import bbct.exceptions.BBCTIOException;
import bbct.gui.BBCTFrame;
import bbct.gui.GUIResources;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.swing.JOptionPane;

/**
 * This is the driver class for the Baseball Card Tracker program.
 *
 * @author codeguru <codeguru@users.sourceforge.net>
 */
public class Baseball {

    private static final String LOG_FILE_NAME = "log/bbct.log";

    /**
     * Starts the Baseball Card Tracker by creating and showing the initial
     * window.
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            Baseball.initLogger();

            // ****************** Added this line ******************
            Logger.getLogger(Baseball.class.getName()).log(Level.INFO, "Fixing to create a BaseballCardIO object.");
            BaseballCardIO bcio = new BaseballCardJDBCIO(GUIResources.DB_URL);

            Logger.getLogger(Baseball.class.getName()).log(Level.INFO, "Fixing to show a new frame.");

            new BBCTFrame(bcio).setVisible(true);
        } catch (BBCTIOException | IOException ex) {
            Logger.getLogger(Baseball.class.getName()).log(Level.SEVERE, "Unable to initialize storage.", ex);
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Initialization Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private static void initLogger() throws IOException {
        boolean append = true;
        Handler handler = new FileHandler(Baseball.LOG_FILE_NAME, append);
        handler.setFormatter(new SimpleFormatter());

        Logger logger = Logger.getLogger("");
        logger.setLevel(Level.INFO);
        logger.addHandler(handler);
    }

    private static final String LOG_FILE_NAME = "log/bbct.log";
}

我不会包含其余代码,因为完整的应用程序有 24 个类。问题是我的 BBCT 应用程序创建了一个“log/bbct.log”文件,但在运行该应用程序后,该文件是空的!我没有看到我的 Baseball 类代码与 SwingLoggingSSCCE 有何不同。但是,显然有些不同,否则它会起作用。我只是需要一些新鲜的眼光来审视我的代码,我想。与此同时,我会尝试自己弄清楚。

预先感谢您的帮助。

编辑:

我忘了说 SwingLoggingSSCCE 也会在控制台上显示日志信息,但是 bbct.Baseball 不会。

更新: 好的,我已经缩小了问题的范围。在创建 BaseballCardIO 对象之前,我添加了对 Logger.log() 的调用。这会出现在日志文件中,但不会出现在 bcio 创建之后。我想我只需要从那里继续我的调查。

** 另一个更新:**

以下构造函数似乎是我的日志记录问题的根源:

public BaseballCardJDBCIO(String url) throws BBCTIOException {
    try {
        Logger logger = Logger.getLogger(BaseballCardJDBCIO.class.getName());
        logger.log(Level.INFO, "Creating BaseballCardJDBCIO object");
        logger.log(Level.INFO, "Getting database connection.");
        this.conn = DriverManager.getConnection(url);

        logger.log(Level.INFO, "Creating table");
        this.createTable();
    } catch (SQLException ex) {
        // TODO: Need a more user-friendly error message.
        throw new BBCTIOException(ex);
    }
}

调用 DriverManager.getConnection(url); 后,所有日志记录都会停止。一些进一步的研究表明 JDBC 使用 java.util.logging。我可能不想要所有的 JDBC 日志记录数据。但是,JDBC 似乎干扰了我需要添加到我的应用程序中的日志记录。这是 JDBC 的“特性”吗?

最佳答案

我发现了问题并发布了一个新的问答以(希望)更简洁地解释并给出我的解决方案:Using java.util.logging with JDBC drivers for the HyperSQL Database Engine

关于java - 在 Swing 应用程序中使用 java.util.logging 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12344824/

相关文章:

postgresql - postgres 索引包含 "unexpected zero page at block"异常

java - 为什么 JTable 滚动占用这么多内存?

java - 部署期间出现 NoSuchMethodException

java - 在 Swing 中动态更改文本

java - 为什么我的 JTextArea 附加不起作用

python - 如何获取python脚本失败消息

java - Swing 卡布局

java - 可绘制位图

java - 如何获取 JTextPane 中所选文本的样式?

git - 使用 Bitbucket 去除 GIT 存储库上的提交