Frage

How do I print the entire stack trace using java.util.Logger? (without annoying Netbeans).

The question should've originally specified staying within Java SE. Omitting that requirment was an error on my part.

-do-compile:
    [mkdir] Created dir: /home/thufir/NetBeansProjects/rainmaker/build/empty
    [mkdir] Created dir: /home/thufir/NetBeansProjects/rainmaker/build/generated-sources/ap-source-output
    [javac] Compiling 13 source files to /home/thufir/NetBeansProjects/rainmaker/build/classes
    [javac] /home/thufir/NetBeansProjects/rainmaker/src/model/TelnetEventProcessor.java:44: error: 'void' type not allowed here
    [javac]                 log.severe(npe.printStackTrace(System.out));
    [javac]                                               ^
    [javac] 1 error

BUILD FAILED

code with the error:

package model;

import java.util.Observable;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TelnetEventProcessor extends Observable {

    private static Logger log = Logger.getLogger(TelnetEventProcessor.class.getName());
    private String string = null;

    public TelnetEventProcessor() {
    }

    private void stripAnsiColors() {
        Pattern regex = Pattern.compile("\\e\\[[0-9;]*m");
        Matcher regexMatcher = regex.matcher(string);
        string = regexMatcher.replaceAll(""); // *3 ??
    }

    public void parse(String string) {
        this.string = string;
        ifs();
    }

    //       [\w]+(?=\.) 
    private void ifs() {
        log.fine("checking..");
        if (string.contains("confusing the hell out of")) {
            Pattern pattern = Pattern.compile("[\\w]+(?=\\.)");  //(\w+)\.
            Matcher matcher = pattern.matcher(string);
            String enemy = null;
            GameData data = null;
            while (matcher.find()) {
                enemy = matcher.group();
            }
            try {
                data = new GameData.Builder().enemy(enemy).build();
                log.fine("new data object\t\t" + data.getEnemy());
                setChanged();
                notifyObservers(data);
            } catch (NullPointerException npe) {
                log.severe(npe.printStackTrace(System.out));
            }

        } else if (string.contains("Enter 3-letter city code:")) {
            log.fine("found enter city code");
        } else {
        }
    }
}

see also:

https://stackoverflow.com/a/7100975/262852

War es hilfreich?

Lösung

The severe method is only used to log severe messages without associated throwable information. If you need to log throwable information then you should use the log method instead:

try {
     data = new GameData.Builder().enemy(enemy).build();
     log.fine("new data object\t\t" + data.getEnemy());
     setChanged();
     notifyObservers(data);
} catch (NullPointerException npe) {
     log.log(Level.SEVERE, npe.getMessage(), npe);
}

Andere Tipps

Why don't you put the exception in the logger?

You can use this method :

logger.log(Level level, String msg, Throwable thrown) 

Maybe a duplicated question? Java - Need a logging package that will log the stacktrace

Below the explanation from the given url

Using log4j this is done with:

logger.error("An error occurred", exception);

The first argument is a message to be displayed, the second is the exception (throwable) whose stacktrace is logged.

Another option is commons-logging, where it's the same:

log.error("Message", exception);

With java.util.logging this can be done via:

logger.log(Level.SEVERE, "Message", exception);

You don't explicitly print the stack trace; Throwables have stack traces attached to them, and you can pass a Throwable to the log methods:

log(Level level, String msg, Throwable thrown)

You could use Apache ExceptionUtils. In your case

try {
     data = new GameData.Builder().enemy(enemy).build();
     log.fine("new data object\t\t" + data.getEnemy());
     setChanged();
     notifyObservers(data);
 } catch (NullPointerException npe) {
     logger.info(**ExceptionUtils.getFullStackTrace(npe)**);
 }

You should redirect the System.err to the logger, the process is not too simple but you can use this code:

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LogOutputStream extends ByteArrayOutputStream {//java.io.OutputStream {

    private String  lineSeparator;
    private Logger  logger;
    private Level   level;

    public LogOutputStream(Logger logger, Level level) {
        super();
        this.logger = logger;
        this.level = level;
        this.lineSeparator = System.getProperty("line.separator");
    }

    @Override
    public void flush() throws IOException {

        String record;
        synchronized (this) {
            super.flush();
            record = this.toString();
            super.reset();

            if ((record.length() == 0) || record.equals(this.lineSeparator)) {
                // avoid empty records 
                return;
            }

            this.logger.logp(this.level, "", "", record);
        }
    }
}

And The code to set this (that should called the when you first create the logger

Logger logger = Logger.getLogger("Exception");
LogOutputStream los = new LogOutputStream(logger, Level.SEVERE);
System.setErr(new PrintStream(los, true));

This will redirect the System.err stream to the logger.

You can also try to use ExceptionUtils from apache commons

The exception is due to the printstacktrace method being void, meaning it doesn't return anything. You are trying to do:

log.severe(npe.printStackTrace(System.out));

My guess is that the severe method needs a String and not void.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top