36

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

0

8 Answers 8

52

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);
}
2
  • 2
    the only problem with this answer is that it's rather verbose -- but that's Java for you!
    – Thufir
    Sep 19, 2013 at 9:29
  • This is the first time that I see someone catching a NP exception!
    – hzitoun
    Apr 25, 2016 at 14:33
12

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

You can use this method :

logger.log(Level level, String msg, Throwable thrown) 
1
  • I think this is the simplest way to achieve the desired result. Will have to try it, of course.
    – Thufir
    Sep 19, 2013 at 9:26
9

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);
1
  • This is what I was looking for. Thanks.
    – Shashank
    Jan 3, 2017 at 6:12
7

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)
4

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)**);
 }
1
  • 1
    Your solution helped me. Another workaround: logger.severe(Arrays.toString(e.getStackTrace())); Dec 30, 2016 at 6:40
3

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.

3

You can also try to use ExceptionUtils from apache commons

1

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.