printStackTrace 到 java.util.logging.Logger

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18889941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:58:19  来源:igfitidea点击:

printStackTrace to java.util.logging.Logger

javanullpointerexceptionjava.util.loggingthrowableprintstacktrace

提问by Thufir

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

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

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

该问题最初应该指定留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

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

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

采纳答案by M. Abbas

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

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

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);
}

回答by Michael Laffargue

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

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

You can use this method :

您可以使用此方法:

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

回答by chrylis -cautiouslyoptimistic-

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

您没有明确打印堆栈跟踪;Throwables 附加了堆栈跟踪,您可以将 a 传递Throwable给日志方法:

log(Level level, String msg, Throwable thrown)

回答by Sajan Chandran

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

异常是由于printstacktrace方法是void,这意味着它不返回任何内容。您正在尝试执行以下操作:

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

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

My guess is that the severemethod needs a Stringand not void.

我的猜测是该severe方法需要 aString而不是void

回答by Gianmarco

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

您应该将 System.err 重定向到记录器,该过程不是太简单,但您可以使用以下代码:

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.

这会将 System.err 流重定向到记录器。

回答by Emanuele

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

也许是重复的问题?Java - 需要一个记录堆栈跟踪的日志包

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.loggingthis can be done via:

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

使用 log4j,这是通过以下方式完成的:

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

第一个参数是要显示的消息,第二个参数是记录堆栈跟踪的异常(可抛出)。

另一种选择是 commons-logging,它是相同的:

log.error("Message", exception);

有了java.util.logging这可以通过这样做:

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

回答by KrzyH

You can also try to use ExceptionUtils from apache commons

您也可以尝试使用apache commons 中的 ExceptionUtils

回答by RIP_SunMicroSys

You could use Apache ExceptionUtils. In your case

您可以使用 Apache ExceptionUtils。在你的情况下

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)**);
 }