How to print to the console in GWT - gwt

I am debugging a GWT application and I need to print some stuff to the console for testing purposes. System.out.println and GWT.log don't work. Does anyone have any ideas?

Quoting the documentation:
Adding GWT logging is really quite simple, as simple as the following code example. However — understanding how logging works, and
how to correctly configure it is important, so please do take the time
to read the rest of this document.
http://code.google.com/webtoolkit/doc/latest/DevGuideLogging.html
The simplest way to enable logging is:
# 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");

I needed to do this in the context of a GWT application that was deployed to an Android device/emulator via PhoneGap (and gwt-phonegap). Neither System.out.println() nor GWT logging as above (with module declaration) showed up in Android's logcat, so I resorted to a simple JSNI wrapper to console.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 );
}-*/;

To log to browsers console you can do it using native, in a very simple way. Very helpful in debugging.
If you add a native method like in below, you can send a string to it from where you want and it will log it in the browsers console.
public static native void console(String text)
/*-{
console.log(text);
}-*/;
For more information about using native in GWT:
http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJSNI.html

In GWT version 2.6.0, method GWT.log writes message to browser console, you don't need to write native methods.

Just summing up the different possibilities shown in the answer's of mreppy and Strelok in one snippet. I also added one possible workaround for IE exceptions as described here: Why does JavaScript only work after opening developer tools in IE once?
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);

Yet another variation using the native console...
Add this class:
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 ); }-*/;
}
Then, enable debugging with it at some point, like upon starting the app:
public class XXXXXX implements EntryPoint {
#Override
public void onModuleLoad() {
Debug.enable();
...
}
}
Then just use it like so:
Debug.log("Hello World!");

I had this problem as well. The GWT log works but because it's all converted to javascript, it prints to the client output, so just view your browser's console and they will be there. In Google Chrome click the triple-line Customize button in the top right, click Tools-->Developer tools and the console will pop up. Your sought-after statements will be there. Also, Ctrl+Shift+I is the shortcut that brings it up. If you want to print to the server, I believe logger handlers and such are in order?

The documentation url in the first answer already gives the different configuration option to log to different places.
This framework i wrote offers you a usefull api and allows you to choose your server-side logging implementation.
Have a look :
https://code.google.com/p/gwt-usefull-logging/

I suggest you use GWT Developer mode It adds a little overhead cause the automatic compilation and code-allocating on the code server, but it's pretty clear when some exceptions arises in client side of your application. I mean, some times chrome console (or firebug or whatever browser debugging built-in tool) doesn't say too much in those situations, trust me, finding a NullPointerException is a pain in the neck when you try to figure out what is happening by alerting your code.

For printing to the browser console I am using something like this:
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
});
}
}-*/;
}

You can put alaert.Alert(""); in your gwt code compile it and run it you will get pop up on browser when you make request or at the action where you have placed that alert

Related

GWT Framework Enable console logs

Im new to the GWT framework which my project is using now. I wanted to trace the code flow and hence thought I could put System.out logs or debug logs. But nothing worked. Then I came accross this page and saw its tottaly differnet for logging. I added,
Debug.Java
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 ); }-*/;
}
and called inside my class
Frame.java
public void onModuleLoad() {
logSC("#### onModuleLoad");
Debug.enable();
Debug.log("&&&&&&&INSIDE BICC******DEBUG LOGGERRRRRRRRR**************************");
}
But I didnt get the debug logs. Could you please advise me what should i do to enable logs and get printed in my console window.
Regards,
Saranya Chandrasekaran
The console.log call in your JSNI needs a $wnd. prefix so that it runs on the correct window (gwt defaults to sandboxing its code in an iframe).
private static native void nativeConsoleLog( String s ) /*-{
$wnd.console.log( s );
}-*/;
Note that using JsInterop will not have this issue - add elemental2-core to your project, and call DomGlobal.console.log() and it will already work in the main window.
That is not the right way to do logging in GWT, GWT already enables you to use the java logging on the browser, so to enable java logging you need to follow these steps :
1- inherits the java logging module by adding<inherits name="com.google.gwt.logging.Logging"/> to your XXX.gwt.xml file, this will enable logging.
2- enable the console logger by adding:
<set-property name="gwt.logging.logLevel" value="INFO"/>
<set-property name="gwt.logging.enabled" value="TRUE"/>
<set-property name="gwt.logging.consoleHandler" value="ENABLED"/>
-this is the default.
then you can define normal java logger like this
public static final Logger LOGGER = Logger.getLogger(MyClass.getName());
//use the logger
LOGGER.log(Level.info, "my log message");
this kind of logging will work even in the production mode and result in a larger javascript file after compilation. any log statements that does not match the log level defined in the XXX.gwt.xml will be removed from the compilation final result.
another way to do logging for development mode or Super dev mode is to use GWT.log this type of logging will only work for development modes but will be removed in production compilation.
for more readings about this topic you can refer to the gwtproject web site
you can also ask in the gwt-users google group
or you can ask in gwt gitter channel for a live interactive chat
See here a solution for using the gwt log framework:
gwt logging not working
It uses java.util.log
You need to add the in gwt.xml to enable it
< set-prop name="gwt.logging.logLevel" value="ALL" />
<set-property name="gwt.logging.enabled" value="TRUE" />

Hystrix getting access to the current execution state within fallback

I successfully configured spring-cloud (via spring-cloud-starter-hystrix) to wrap a call to a service.
This all works fine and looks like the following:
#Component
public class MyService {
#HystrixCommand(fallbackMethod = "fallback")
public void longRunning() {
// this could fail
}
public void fallback() {
// fallback code
}
}
My question now is, I would like to log some statistics about the execution error in longRunning()
Trying to access HystrixRequestLog.getCurrentRequest() within the fallback method throws
java.lang.IllegalStateException: HystrixRequestContext.initializeContext() must be called at the beginning of each request before RequestVariable functionality can be used.
I am looking for a simple way to log the exception of longRunning if the fallback is called.
testing with v1.0.0.RC2
To see a stack trace you can just enable DEBUG logging in com.netflix.hystrix.
As far as I can tell, to use the HystrixRequestContext the caller of MyService has to call HystrixRequestContext.initializeContext() before using the service. That sucks, so if anyone has a better idea, I'm interested.
Starting from Javanica v1.4.21, it allows fallback method to have an argument of Throwable type for accessing the command execution exception like so:
public void fallback(Throwable e) {
// fallback code
LOGGER.error(e.getMessage());
}
To get this feature, your build config needs to override the older version of Javanica pulled in by Spring Cloud.

Send localized email in GWT [duplicate]

I have an interface that extends the com.google.gwt.i18n.client.Messages class, which I use for retrieving i18n messages in my GWT application. It looks like this:
public interface MyMessages extends com.google.gwt.i18n.client.Messages {
#DefaultMessage("Hello world")
#Key("message1")
String message1();
#DefaultMessage("Hello again")
#Key("message2")
String message2();
//...
}
Normally, I create an instance of it using GWT.create() like so:
private MyMessages messages = GWT.create(MyMessages.class);
However, this does not work with server-side code, only client-side code (it throws an error saying that GWT.create() is only usable in client-side code).
The answer to a similar question points to a separate library that you can download which will let you access the i18n messages on the server, but I don't want to download any extra libraries (this seems like a simple problem, there must be a simple solution).
In summary: How can I access my i18n messages in server-side code? Thanks.
On the server side you can use the standard Java localization tools like ResourceBundle.
Look here for a tutorial how to use it.
// Create a ResourceBundle out of your property files
ResourceBundle labels =
ResourceBundle.getBundle("LabelsBundle", currentLocale);
// Get localized value
String value = labels.getString(key);
The GWT specific way of creating an interface out of your property files and providing implementations via deferred binding can not be used on sever side Java.
If you are fearless and willing to spend the time, you can implement a code generation step to read your property files and generate implementation classes for your message interface. That's exactly what the Google GWT compiler does behind the scene.
I agree with Michael.. I was having this problem of trying to "localize" messages generated on the server.... but I decided to instead just throw an Exception on the server (because it is an error message which should only happen exceptionally) which contains the message code, which the client code can then look up and show the correct localized message to the user.
There's a great library for GWT internationalization gwt-dmesg. It allows you to 'share' .properties files between clent and server. However, project looks to be abandoned by author and you must recompile it manually for use with GWT versio >= 2.1.0.
GWT.create() can only be used in client-side code.
The good thing to do is that you provide your own I18NProvider class/interface, from which then you can extend to server side I18N factory and client side I18N factory read the same resource bundle.
After that you can simply use it all over your system, unify your code.
Hope that helps.
Following vanje's answer, and considering the encoding used for the properties files (which can be troublesome as ResourceBundle uses by default "ISO-8859-1", here is the solution I came up with:
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.ResourceBundle;
public class MyResourceBundle {
// feature variables
private ResourceBundle bundle;
private String fileEncoding;
public MyResourceBundle(Locale locale, String fileEncoding){
this.bundle = ResourceBundle.getBundle("com.app.Bundle", locale);
this.fileEncoding = fileEncoding;
}
public MyResourceBundle(Locale locale){
this(locale, "UTF-8");
}
public String getString(String key){
String value = bundle.getString(key);
try {
return new String(value.getBytes("ISO-8859-1"), fileEncoding);
} catch (UnsupportedEncodingException e) {
return value;
}
}
}
The way to use this would be very similar than the regular ResourceBundle usage:
private MyResourceBundle labels = new MyResourceBundle("es", "UTF-8");
String label = labels.getString(key)
Or you can use the alternate constructor which uses UTF-8 by default:
private MyResourceBundle labels = new MyResourceBundle("es");

Overrided broadcast(Object message, GwtAtmosphereResource resource) method in Atmosphere with GWT not working

We are trying to handle a scenario that when a user in quitting a room ,we send a message using MetaBroadcaster to all room .We implemented this feature by override broadcast method of AtmosphereGwtHandler .
The feature is good when we testing in development mode, but when we test it in Jetty8 production mode, telling by log, the override method is void which never get called.
So anybody know what's wrong with it, or do we have a better solution to this feature.
here is our code snippet:
public class ChatHandler extends AtmosphereGwtHandler {
...
#Override
public void broadcast(Object message, GwtAtmosphereResource resource) {
MsgType msgtype=((ChatMessage)message).getMsgtype();
if(msgtype==MsgType.Broad){
MetaBroadcaster.getDefault().broadcastTo(((ChatMessage)message).getChanel(), message);
System.out.println("Doing to all room);
}else{
super.broadcast(message, resource);
System.out.println("Doing to myself);
}
}
}
Can't really give an answer on the info provided.
Where have you configured your handler?
web.xml or atmosphere.xml
What servlet are you using Meteor/Atmosphere?
What version of Atmosphere?

GWT detect browser refresh in CloseHandler

I have a GWT application and I want to run some code when the user leaves the application to force a logout and remove any data etc.
To do this I am using a CloseHandler and registering it using Window.addCloseHandler.
I have noticed that when the refresh button is clicked the onClose method is run but I have been unable to differentiate this event from a close where the user has closed the browser. If it is a refresh I do not want to do the logout etc, I only want to do this when the user closes the browser/tab or navigates away from the site.
Does anybody know how I can do this?
There is no way to differentiate the 'close' from 'refresh'. But, you can set a cookie that holds the last CloseHandler call time and check, when loading the module, if this time is old enough to clean the information before showing the page.
You can do that with the folowing utility class (BrowserCloseDetector). Here is an example using it on the onModuleLoad.
The test lines:
#Override
public void onModuleLoad() {
if (BrowserCloseDetector.get().wasClosed()) {
GWT.log("Browser was closed.");
}
else {
GWT.log("Refreshing or returning from another page.");
}
}
The utility class:
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;
public class BrowserCloseDetector {
private static final String COOKIE = "detector";
private static BrowserCloseDetector instance;
private BrowserCloseDetector() {
Window.addWindowClosingHandler(new Window.ClosingHandler() {
public void onWindowClosing(Window.ClosingEvent closingEvent) {
Cookies.setCookie(COOKIE, "");
}
});
}
public static BrowserCloseDetector get() {
return (instance == null) ? instance = new BrowserCloseDetector() : instance;
}
public boolean wasClosed() {
return Cookies.getCookie(COOKIE) == null;
}
}
Have you tried
<BODY onUnload = "scriptname">
in your gwt hosting/launching html file?
I am thinking that if you defined a map "hash" (i.e. a javascript pseudo hash) in the hosting file and then accessed the "hash" in GWT through Dictionary class, you could update values in that hash as the user progresses through the gwt app. Which means, your programming style would require you to log milestones on the user's progress onto this map.
When the user closes the browser page, the onunload script of the launching html page would be triggered. That script would access the map to figure out what needs to be updated to the server, or what other url to launch.
I am intereted too if someone got a solution (GWT/java side only).
Maybe we can do it with HistoryListerner ?
1-set a flag for your current viewing page.
2-when ClosingHandler event, launch a "timeout" on server-side (for example 10s)
3-if during this time your got a massage from HistoryListerner with the same last flag so it was just a refresh.
of disconnect if timer is over...
Is not a good solution but I think it is easy to do... If someone have a better one...