Using the java.util.logging package in a Swing application

This question is related to Implementing logging in a Java application, but since the example code there has made the question incredibly long, I decided to start a new question based on what I have learned so far.

To illustrate what I am trying to do, I have the following example class which extends 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;
}

This works exactly as expected and produces the following "swingloggingsscce.log" file:

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

Now I am trying to get the same thing to work in my main application. This is the class with 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";
}

I won't include the rest of the code as there are 24 classes for the complete application. The problem is that my BBCT application creates a "log/bbct.log" file, but after running the application, the file is empty! I don't see how my code for the Baseball class differs from SwingLoggingSSCCE. Obviously something is different, though, or else it would work. I just need some fresh eyes to look at my code, I think. In the mean time, I'll try to figure it out on my own.

Thanks in advance for your help.

Edit:

I forgot to mention that SwingLoggingSSCCE also displays the logging information on the console, but bbct.Baseball does not.

Update: Okay, I have narrowed down the problem a little bit. I added a call to Logger.log() before creating the BaseballCardIO object. This appears in the log file, but not the one after bcio is created. I guess I just need to continue my investigation from there.

** Another Update:**

The following constructor seems to be the source of my logging issues:

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);
    }
}

All logging stops after the call to DriverManager.getConnection(url);. Some further research shows that JDBC uses java.util.logging. I probably don't want all of the JDBC logging data. However, JDBC seems to be interfering with the logging I need to add to my application. Is this a "feature" of JDBC?

Answers


I found the problem and posted a new Q&A to (hopefully) explain more concisely and give my solution: Using java.util.logging with JDBC drivers for the HyperSQL Database Engine


Need Your Help

C# progress bar and EdtFTPnet Bytestransferred event

c# progress-bar byte

Hello peeps at Stack Overflow, I have a problem that I've been trying to solve since a couple of days. I have a problem in which I want to display via a progress bar, the bytes transferred from the...

Use LINQ to get comma separated list from different table

c# mysql asp.net sql linq

I'm using ASP.NET and have a GridView that I want to populate with data from 2 tables. Right now, I have the following query:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.