Cómo imprimir en la consola en GWT


Estoy depurando una aplicación GWT y necesito imprimir algunas cosas en la consola para fines de prueba. System.out.println y GWT.log no funcionan. ¿Alguien tiene alguna idea?

 84
gwt
Author: andrewsi, 2012-02-12

10 answers

Citando la documentación:

Agregar el registro de GWT es realmente bastante simple, tan simple como el siguiente ejemplo de código. Sin embargo-entender cómo funciona el registro, y cómo configurarlo correctamente es importante, así que por favor tómese el tiempo para leer el resto de este documento.

Http://code.google.com/webtoolkit/doc/latest/DevGuideLogging.html

La forma más sencilla de habilitar el registro es:

# In your .gwt.xml file
<inherits name="com.google.gwt.logging.Logging"/>

# In your .java file
Logger logger = java.util.logging.Logger.getLogger("NameOfYourLogger");
logger.log(Level.SEVERE, "this message should get logged");
 68
Author: Strelok,
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
2018-02-15 09:19:43

Necesitaba hacer esto en el contexto de una aplicación GWT que se desplegó en un dispositivo/emulador Android a través de PhoneGap (y gwt-phonegap). Ninguno de los dos Sistemas.fuera.println () ni el registro GWT como el anterior (con la declaración del módulo) apareció en el logcat de Android, así que recurrí a un simple contenedor JSNI para la consola.log:

  public void onModuleLoad()
  {
    Logger logger = Logger.getLogger("Test1.java");
    logger.log(Level.INFO, "ash: starting onModuleLoad (1)"); // not in logcat
    System.out.println( "ash: starting onModuleLoad (2)" ); // not in logcat
    consoleLog( "ash: starting onModuleLoad (3)" ); // This shows up
    ...
  }

  native void consoleLog( String message) /*-{
      console.log( "me:" + message );
  }-*/;
 43
Author: mreppy,
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
2014-07-07 15:37:22

En GWT versión 2.6.0, método GWT.el registro escribe mensajes en la consola del navegador, no es necesario escribir métodos nativos.

 24
Author: zergood,
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
2014-02-12 08:44:57

Para iniciar sesión en la consola de navegadores puedes hacerlo usando nativo, de una manera muy sencilla. Muy útil en la depuración.

Si agrega un método nativo como el que se muestra a continuación, puede enviarle una cadena desde donde desee y la registrará en la consola de navegadores.

public static native void console(String text)
/*-{
    console.log(text);
}-*/;

Para obtener más información sobre el uso de nativo en GWT: http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html

 21
Author: erkinyldz,
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
2014-07-07 15:37:07

Simplemente resumiendo las diferentes posibilidades mostradas en las respuestas de mreppy y Strelok en un fragmento. También agregué una posible solución para las excepciones de IE como se describe aquí: ¿Por qué JavaScript solo funciona después de abrir las herramientas de desarrollo en IE una vez?

    java.util.logging.Logger logger = Logger.getLogger(this.getClass().getSimpleName());

    native void jsConsoleLog(String message) /*-{
        try {
            console.log(message);
        } catch (e) {
        }
    }-*/;

    private void log(final String message) {
        // Logs to Dev mode console only
        GWT.log(message);
        // Logs to Dev mode and JavaScript console (requires configuration)
        this.logger.log(Level.FINEST, message);
        // Logs to JavaScript console only
        jsConsoleLog(message);
 6
Author: schnatterer,
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 11:33:16

Otra variación usando la consola nativa...

Añadir esta clase:

package XXX.XXX.XXX.XXX;

public class Debug {
    private static boolean isEnabled_ = false;
    public static void enable() { isEnabled_ = true; }
    public static void setEnabled( final boolean isEnabled ) 
    { isEnabled_ = isEnabled; }

    public static void log( final String s ) 
    { if( isEnabled_ ) nativeConsoleLog( s ); }

    private static native void nativeConsoleLog( String s ) 
    /*-{ console.log( s ); }-*/;
}

Luego, habilite la depuración con él en algún momento, como al iniciar la aplicación:

public class XXXXXX implements EntryPoint {
    @Override
    public void onModuleLoad() {
        Debug.enable();
        ...
    }
}

Entonces úsalo así:

Debug.log("Hello World!");
 5
Author: BuvinJ,
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
2015-10-14 14:15:32

Yo también tuve este problema. El registro de GWT funciona, pero debido a que todo está convertido a javascript, se imprime en la salida del cliente, por lo que solo tiene que ver la consola de su navegador y estarán allí. En Google Chrome, haga clic en el botón Personalizar de triple línea en la parte superior derecha, haga clic en Herramientas> > Herramientas de desarrollador y aparecerá la consola. Sus declaraciones buscadas estarán allí. Además, Ctrl+Shift+I es el atajo que lo muestra. Si desea imprimir en el servidor, creo que los controladores de registro y tales son en orden?

 0
Author: Glenninator,
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-07-03 19:12:49

La url de la documentación en la primera respuesta ya da la opción de configuración diferente para iniciar sesión en diferentes lugares. Este marco que escribí le ofrece una API útil y le permite elegir su implementación de registro del lado del servidor. Echa un vistazo : https://code.google.com/p/gwt-usefull-logging /

 0
Author: François Wauquier,
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-07-08 12:55:44

Le sugiero que utilice GWT Developer mode Añade un poco de sobrecarga causa la compilación automática y la asignación de código en el servidor de código, pero es bastante claro cuando surgen algunas excepciones en el lado del cliente de su aplicación. Quiero decir, algunas veces chrome console (o firebug o cualquier herramienta incorporada de depuración del navegador) no dice demasiado en esas situaciones, confía en mí, encontrar un NullPointerException es un dolor en el cuello cuando intentas averiguar lo que está sucediendo al alertar a su codificar.

 0
Author: ,
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-13 19:13:48

Para imprimir en la consola del navegador estoy usando algo como esto:

EventLogger.java

public class EventLogger {
    public static void logEvent(String subsys, String grp, String type) {
        logEvent(GWT.getModuleName(), subsys, grp,
                Duration.currentTimeMillis(), type);
    }

    public static native void logEvent(String module, String subsys,
                                       String grp, double millis, String type)
/*-{
    if ($wnd.__gwtStatsEvent) {
        $wnd.__gwtStatsEvent({
            'moduleName':module,
            'subSystem':subsys,
            'evtGroup':grp,
            'millis':millis,
            'type':type
        });
    }
}-*/;
}
 0
Author: Eugene,
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
2014-07-07 15:37:28