views:

147

answers:

3

Need: Output a Java application's log into a GUI component, such as a JTextArea.

Concern: Need to log things from any class, in a static manner. However, the GUI logger component must not be static (obviously) as it's the member of a parent component.

What should I do?

+1  A: 

Databinding comes to my mind. You need a model that represents your log and this model is bound to a GUI component. A common databinding framework for SWT is JFace Databinding, I'm sure something similiar exists for SWING.

How would it work - the logger adds messages to the model, maybe just an Arraylist of Strings (logentries). The databinding classes listen to the model and update the GUI everytime the model has changed. It would work the other way round too (edits on the GUI could be send to the model) but you'll just need one direction.

Andreas_D
+1  A: 

Create a singelton log provider and add the "textfield" as a listener to it.

Example of the logger singelton:

interface Listener {
    void log(String log);
}

enum Logger {

    instance;

    private List<Listener> listeners = new LinkedList<Listener>();

    public void addListener(Listener l) {
    synchronized(listeners) {
        listeners.add(l);
     }
    }

    public void log(String log) {
        synchronized(listeners) {
            for(Listener l : listeners)
                l.log(log);
        }
    }
}

Add your listener (which you will need to implement yourself) like this:

Logger.instance.addListener(myTextField);

And use it (from any class) like this:

Logger.instance.log("Hello World!");

Or you can use a package like log4j.

dacwe
Don't write yet another logging framework, just don't do it. Use log4j (or slf4j, it seems to be all the rage)
Justin
+2  A: 

Log to a file, have the component follow the tail of the file. You probably want to use log4j's XML logging if you want to put the output into a grid.

Update: You could alternatively implement an in-memory circular logger.

Justin
good call -- this decouples the timing/priority requirements. Logging should be high-priority, displaying the log should not.
Jason S