开发者

Accessing a logger in a Java application

I have a question regarding logging in a Java application. I want to log the main user actions and possible errors with user friendly messages. Therefore, I have two appenders for the logger: one shows errors (level = error) in dialogs and the other writes the logs of the current user session into an html-file so that the user could send this file back if something goes wrong.

To avoid having the logger creation in every class (private Logger logger = …) I have a static reference of the configured logger in a class App which has also the methods for accessing the logger:

public class App {
    private static Logger logger = Logger.getLogger("logger name");
    …
    public static void logError(String message, Throwable cause) {
    …
    }
    public static void logInfo(String messa开发者_如何学JAVAge) {
    …
    }
}

The logging is mainly done in the UI classes:

class UIWidget extends UIFrameworkWidget {

    void aMethod() {
        try {
            someBusinessLogic();
        } catch (Exception e) {
            App.logError(“log message”, e);
        }
    }
} 

Is this a good practice? (Note that the widgets are created by the framework.)

Thanks in advance for answers, comments, or hints on this


Better would be to use a single static Logger instance but allow each class to create a private instance which is initialized with the name of the class (and maybe other info). This private instance then uses the static instance to actually perform its logging but can be omitted if necessary and reduces references to external classes.

This is how slf4j does it, which is a logging framework you should consider using - however you could roll your own in the same manner.

Note, however I don't know how to get your error messages to be displayed within a dialog box - that may need to be explicitly added.


It seems you're just one step away of subclassing the JDK Logger. Having only one static instance prevents you from targeting specific classes at runtime. If you subclass the Logger, then you can still have has many loggers as logged classes and yet keep your appender's peculiarities.

You can also craft your own layout (and, in log4j at least, even add placeholders - geronimo has an example of this).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜