Question

I am currently working on a Java project where I am using the standard Java logger (i.e. java.util.logging.Logger). I'm finding that when I hit unexpected exceptions that are not handled in my code, my program closes but the logger doesn't release the lock on the text file.

Is there some way to adjust my code so that any unexpected exception in my code gets logged to the output file, closes the output file and quits?

Some code in case it's relevant

I have a CustomLogging class:

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 CustomLogging 
{
    static private FileHandler txtFileHandle;
    static private SimpleFormatter formatterTxt;

    static public void initalise() throws IOException 
    {
        //Global logger configuration
        Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);

        logger.setLevel(Level.INFO);
        txtFileHandle = new FileHandler("Logging.txt");

        formatterTxt = new SimpleFormatter();
        txtFileHandle.setFormatter(formatterTxt);
        logger.addHandler(txtFileHandle);
    }

    static public void shutdown() throws IOException
    {
        txtFileHandle.close();
    }
}

The initialise method for the CustomLogger class is called at program start-up in the constructor of my first Java Swing GUI:

public StartMenu() 
{
    try
    {
        CustomLogging.initalise();
    }
    catch (Exception e)
    {
        //Placeholder, will fix this up
    }
    //Other code....
}

All other classes get access via:

private final static Logger logger = Logger.getLogger(MyClassNameHere.class.getName());

Thank you.

Was it helpful?

Solution

Invoke the shutdown() method of your custom logger in finally{} block of your code

Logger.getLogger(MyClassNameHere.class.getName()); 

This will not return your CustomLogging instance. Your initialize() should return logger which your Code must use for logging.

Example:

public class CustomLogging 
{
static private FileHandler txtFileHandle;
static private SimpleFormatter formatterTxt;

static public Logger getLogger(Class loggerClass) throws IOException 
{
    //Global logger configuration
    Logger logger = Logger.getLogger(loggerClass);

    logger.setLevel(Level.INFO);
    txtFileHandle = new FileHandler("Logging.txt");

    formatterTxt = new SimpleFormatter();
    txtFileHandle.setFormatter(formatterTxt);
    logger.addHandler(txtFileHandle);

    return logger;
}

 static public void shutdown() throws IOException
 {
    txtFileHandle.close();
 }
}

Use it like this:

CustomLogging logger = CustomLogging.getLogger(MyClassNameHere.class);

try{
   logger.info("print in log");
}finally{
   logger.shutdown();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top