1. 程式人生 > >log4j遠端日誌管理

log4j遠端日誌管理

利用JPPF進行平行計算,計算任務執行在遠端節點上,那麼如何收集執行在遠端的任務日誌,用於跟蹤和分析呢?

JPPF框架對此也有封裝,主要的實現思路是,通過自定義實現一個log4j的appender,對外提供JMX服務。客戶端(監控端)實現一個監聽器,監聽遠端日誌,這樣即可把遠端日誌採集到本地進行統一的管理。這對於我們收集和管理平行計算實時日誌是非常有用的。具體看一下:

在沒個執行任務的Node節點,修改log4j的配置,啟用jppf提供的JmxAppender:
log4j-node.properties

log4j.appender.JMX=org.jppf.logging.log4j.JmxAppender
log4j.appender.JMX.layout=org.apache.log4j.PatternLayout log4j.appender.JMX.layout.ConversionPattern=%d [%-5p][%c.%M(%L)]: %m\n ### set log levels - for more verbose logging change 'info' to 'debug' ### #log4j.rootLogger=DEBUG, JPPF log4j.rootLogger=INFO, JPPF, JMX

客戶端程式碼如下:

/**
* @author lihzh
* @alia OneCoder
* @blog http://www.coderli.com
* @date 2013年7月17日 上午10:34:44
*/
public class RemoteLog {
     public static void main(String args[]) throws Exception {
            // get a JMX connection to the node MBean server
           JMXNodeConnectionWrapper jmxNode
= new JMXNodeConnectionWrapper("localhost" , 12001); jmxNode.connectAndWait(500000L); // get a proxy to the MBean JmxLogger nodeProxy = jmxNode.getProxy(JmxLogger.DEFAULT_MBEAN_NAME , JmxLogger. class); // use a handback object so we know where the log messages come from String source = "node " + jmxNode.getHost() + ":" + jmxNode.getPort(); // subbscribe to all notifications from the MBean NotificationListener listener = new MyLoggingHandler(); nodeProxy.addNotificationListener(listener, null, source); String source167 = "node " + jmxNode167.getHost() + ":" + jmxNode167.getPort(); } } public class MyLoggingHandler implements NotificationListener { // handle the logging notifications public void handleNotification(Notification notification, Object handback) { String message = notification.getMessage(); String toDisplay = handback.toString() + ": " + message; System. out.println(toDisplay); } }

簡單介紹下,就是通過ip和埠與需要監聽的node節點建立jmx連結,然後講自己事先的監聽處理類MyLoggingHandler例項,註冊到nodeProxy上。這樣如果node端有日誌出現,就會通知到監聽端,可以進行自己的分類處理。試驗一下,啟動JPPF環境和啟動監聽,執行之前介紹的JPPF任務,可以看到在本地成功打印出任務日誌資訊,這樣,平行計算任務分節點的日誌收集處理也就很容易實現了。