printStackTrace to java.util.logging.Logger

如何使用java.util.Logger打印整个堆栈跟踪?(没有烦人的Netbeans)。

这个问题最初应该指定留在 Java SE 。省略该要求对我来说是一个错误。

-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

代码,但出现错误:

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 {
        }
    }
}

另请参阅:

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


答案 1

该方法仅用于记录没有关联可抛出信息的严重消息。如果需要记录可抛出的信息,则应改用 log 方法:severe

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

为什么不将异常放在记录器中?

您可以使用此方法:

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

推荐