Daniel Pereira
Daniel Pereira

Reputation: 453

Java logger problem

I would like to record the logs of my Java application. I have created this class:

public class Log {

    final Logger logger = Logger.getLogger("DigiScope.log");

    public static void main(String[] args) {
    }

    public Log(String message) {
        try {
            // Create an appending file handler
            boolean append = true;
            FileHandler handler = new FileHandler("my.log", append);

            // Add to the desired logger
            Logger logger = Logger.getLogger("com.mycompany");
            logger.addHandler(handler);
            logger.info(message);

        } catch (IOException e) {
        }

    }
}

And for each button I have a code like that:

private void btnNewPatient ActionPerformed(java.awt.event.ActionEvent evt) {
Log a = new Log("New Patient created");
}

This code creates a log.txt, but records only the click on the first button, the others clicks on the others buttons are not record.

Can you help me?

Thank you.

Upvotes: 0

Views: 3452

Answers (3)

Ralph
Ralph

Reputation: 120761

Péter Török and StriplingWarrior are right with their suggestion to use the Logging framework in the right way:

logger.info("New Patient created");

instead of creating a new Logger for each statement.


But even with your construction, you should have a logfile with all logging information. For each invocation of the Log constructor, a new my.log.X file is created (X is a number). And from this point in time each log statement is logged in this file.

So if you invoke the constructor three times (with message: "first", "second", "third") then you should have the files: my.log, my.log.1. my.log.2

  • my.log: "first", "second", "third"
  • my.log.1: "second", "third"
  • my.log.2: "third"

Upvotes: 1

Péter Török
Péter Török

Reputation: 116246

It doesn't make much sense to create a proprietary logging wrapper in your app - java.util.logging is already such a wrapper, so I recommend using it directly. You should create logger objects in your classes, then log messages within handler methods something like this:

logger.info("New Patient created");

And you should use the same Logger instance throughout your class, instead of creating new instances all the time. The standard way is to create one static final instance per class.

It is also better to configure logging from a config file, not from code.

I recommend reading through the Java Logging Tutorial.

Upvotes: 2

StriplingWarrior
StriplingWarrior

Reputation: 156459

I'm guessing that it's probably logging each click, but you're reopening the file with each new log message, rather than appending to it.

Upvotes: 0

Related Questions