JavaBranch

воскресенье, 2 мая 2010 г.

Eclipse Logging Framework

Если Вы пишите плагин для Eclipse RCP и Вам понадобился логгер, то лучше всего для этих целей использовать возможности самой платформы. Класс Plugin, по средствам метода getLog(), предоставляет необходимый API для логирования (org.eclipse.core.runtime.ILog).

   Plugin plugin = MyPlugin.getDefault();
   ILog logger = plugin.getLog();
   IStatus event = new Status(IStatus.INFO, 
         plugin.getBundle().getSymbolicName(), 
         "Какое нибудь сообщение");
   logger.log(event);
Это сообщение попадет в "${workspace}/.metadata/.log".

Также можно отслеживать и перенаправлять все сообщения. В данном примере все сообщения перенаправляются в log4j.

public class MyPlugin extends AbstractUIPlugin {

   public static final String PLUGIN_ID = "myplugin";

   private static MyPlugin plugin;

   private ILogListener logListener;

   public MyPlugin() {
   }

   public void start(BundleContext context) throws Exception {
      super.start(context);
      plugin = this;

      logListener = new ILogListener() {

         private Logger logger = Logger.getLogger(PLUGIN_ID);

            @Override
            public void logging(IStatus status, String pluginName) {
               if (status == null) { 
                          return;
                   }

                      int severity = status.getSeverity();
                      Level level = Level.DEBUG;  
                      if (severity == Status.ERROR) {
                          level = Level.ERROR;
                      } else if (severity == Status.WARNING) {
                          level = Level.WARN;
                      } else if (severity == Status.INFO) {
                          level = Level.INFO;
                      } else if (severity == Status.CANCEL) {
                             level = Level.FATAL;
                      }

                      pluginName = formatText(pluginName);
                      String statusPlugin = formatText(status.getPlugin());
                      String statusMessage = formatText(status.getMessage());
                      StringBuffer message = new StringBuffer();
                      if (pluginName != null) {
                  message.append(pluginName);
                         message.append(" - ");
                      }
                      if (statusPlugin != null 
                     && (pluginName == null 
                           || !statusPlugin.equals(pluginName))) {

                         message.append(statusPlugin);
                         message.append(" - ");
                      } 
                      message.append(status.getCode());
                      if (statusMessage != null) {
                        message.append(" - ");
                         message.append(statusMessage);
                      }

                      logger.log(level, message.toString(), status.getException());
            }

               private String formatText(String text) {
                      if (text != null) {
                         text = text.trim();
                         if (text.length() == 0) {
                            return null;
                         }
               } 

                      return text;
            }

      };
 
      plugin.getLog().addLogListener(logListener);
   }
 
   public void stop(BundleContext context) throws Exception {
      plugin = null;
        plugin.getLog().removeLogListener(logListener);

        super.stop(context);
    }

    ...

}

Всего написанного должно хватить, что бы начать использовать штатный логгер Eclipse RCP.

Комментариев нет:

Отправить комментарий