printStackTrace a java.útil.tala.Registrador


¿Cómo puedo imprimir todo el seguimiento de la pila usando java?útil.¿Leñador? (sin molestos Netbeans).

La pregunta debería haber especificado originalmente permanecer dentro de Java SE. Omitir ese requerimiento fue un error de mi parte.

-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

Código con el 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 {
        }
    }
}

Véase también:

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

Author: Community, 2013-09-19

8 answers

El método severe solo se usa para registrar mensajes severos sin información lanzable asociada. Si necesita registrar información lanzable, debe usar el método log en su lugar:

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);
}
 48
Author: mabbas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-19 14:38:28

¿Por qué no pones la excepción en el registrador?

Puedes usar este método:

logger.log(Level level, String msg, Throwable thrown) 
 9
Author: Michael Laffargue,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-19 08:43:37

¿Quizás una pregunta duplicada? Java-Necesita un paquete de registro que registre la stacktrace

Debajo de la explicación de la url dada

Usando log4j esto se hace con:

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

El primer argumento es un mensaje a mostrar, el segundo es el excepción (lanzable) cuyo stacktrace está registrado.

Otra opción es commons-logging, donde es lo mismo:

log.error("Message", exception);

Con java.util.logging esto se puede hacer via:

logger.log(Level.SEVERE, "Message", exception);
 8
Author: Emanuele,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:09:35

No se imprime explícitamente el seguimiento de pila; Throwablelos trazos de pila están adjuntos a ellos, y se puede pasar un Throwable a los métodos de registro:

log(Level level, String msg, Throwable thrown)
 7
Author: chrylis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-19 08:43:47

Podría usar Apache ExceptionUtils. En su caso

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)**);
 }
 4
Author: RIP_SunMicroSys,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-13 18:16:59

Debe redirigir el Sistema.err para el registrador, el proceso no es demasiado simple, pero se puede utilizar este código:

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

Y El código para establecer esto (que se debe llamar el cuando se crea por primera vez el registrador

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

Esto redirigirá el Sistema.errar corriente al registrador.

 3
Author: Gianmarco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-19 08:54:50

También puedes intentar usar ExceptionUtils de apache commons

 3
Author: KrzyH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-15 10:07:13

La excepción se debe a la printstacktrace el método es void, lo que significa que no devuelve nada. Usted está tratando de hacer:

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

Mi conjetura es que el método severe necesita un String y no void.

 1
Author: Sajan Chandran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-27 15:57:33