自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用Log4j、ActiveMQ和Spring實現(xiàn)異步日志

開發(fā) 前端
我的團隊和我正在創(chuàng)建一個由一組RESTful JSON服務組成的服務平臺,該平臺中的每個服務在平臺中的作用就是分別提供一些獨特的功能和/或數(shù)據(jù)。由于平臺中產生的日志四散各處,所以我們想,要是能將這些日志集中化處理一下,并提供一個能夠讓我們查看、過濾、排序和搜索我們所有的日志的基本型的日常查看工具就好了。

我的團隊和我正在創(chuàng)建一個由一組RESTful JSON服務組成的服務平臺,該平臺中的每個服務在平臺中的作用就是分別提供一些獨特的功能和/或數(shù)據(jù)。由于平臺中產生的日志四散各處,所以我們想,要是能將這些日志集中化處理一下,并提供一個能夠讓我們查看、過濾、排序和搜索我們所有的日志的基本型的日常查看工具就好了。我們還想讓我們的日志是異步式的,因為我們可不想在寫日志的時候(比方說,可能會將日志直接寫入數(shù)據(jù)庫),讓我們提供的服務因為寫日志而暫時被阻擋住。

 

實現(xiàn)這個目標的策略非常簡單明了。

  1. 安裝ActiveMQ
  2. 創(chuàng)建一個log4j的日志追加器,將日志寫入隊列(log4j自帶了一個這樣的追加器,不過現(xiàn)在讓我們自己來寫一個吧。) 
  3. 寫一個消息偵聽器,從MQ服務器上所設置的JMS隊列中讀取日志并將日志持久化

下面讓我們分步來看這個策略是如何得以實現(xiàn)的。

安裝ActiveMQ

安裝一個外部的ActiveMQ服務器簡單極了。這個鏈接http://servicebus.blogspot.com/2011/02/installing-apache-active-mq-on-ubuntu.html是在Ubuntu上安裝ActiveMQ的一個非常棒的指南。你還可以選擇在你的應用中嵌入一個消息代理,采用Spring就可以非常輕松實現(xiàn)。 我們將在后文中詳談具體的實現(xiàn)方法。

創(chuàng)建一個Lo4j的JMS日志追加器

首先,我們來創(chuàng)建一個log4j的JMS日志追加器。log4j自帶了一個這樣的追加器(該追加器沒有將日志寫入一個隊列,而是寫給了一個話題)

  1. import javax.jms.DeliveryMode;  
  2. import javax.jms.Destination;  
  3. import javax.jms.MessageProducer;  
  4. import javax.jms.ObjectMessage;  
  5. import javax.jms.Session;  
  6.  
  7. import org.apache.activemq.ActiveMQConnectionFactory;  
  8. import org.apache.log4j.Appender;  
  9. import org.apache.log4j.AppenderSkeleton;  
  10. import org.apache.log4j.Logger;  
  11. import org.apache.log4j.PatternLayout;  
  12. import org.apache.log4j.spi.LoggingEvent;  
  13.  
  14. /**  
  15.  * JMSQueue appender is a log4j appender that writes LoggingEvent to a queue.  
  16.  * @author faheem  
  17.  *  
  18.  */ 
  19. public class JMSQueueAppender extends AppenderSkeleton implements Appender{  
  20.  
  21. private static Logger logger = Logger.getLogger("JMSQueueAppender");  
  22.  
  23. private String brokerUri;  
  24. private String queueName;  
  25.  
  26. @Override 
  27. public void close() {  
  28.  
  29. }  
  30.  
  31. @Override 
  32. public boolean requiresLayout() {  
  33.     return false;  
  34. }  
  35.  
  36. @Override 
  37. protected synchronized void append(LoggingEvent event) {  
  38.  
  39.    try {  
  40.  
  41.      ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(  
  42.                     this.brokerUri);  
  43.  
  44.      // Create a Connection  
  45.      javax.jms.Connection connection = connectionFactory.createConnection();  
  46.      connection.start();np  
  47.  
  48.      // Create a Session  
  49.      Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);  
  50.  
  51.      // Create the destination (Topic or Queue)  
  52.      Destination destination = session.createQueue(this.queueName);  
  53.  
  54.      // Create a MessageProducer from the Session to the Topic or Queue  
  55.      MessageProducer producer = session.createProducer(destination);  
  56.      producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);  
  57.  
  58.      ObjectMessage message = session.createObjectMessage(new LoggingEventWrapper(event));  
  59.  
  60.      // Tell the producer to send the message  
  61.      producer.send(message);  
  62.  
  63.      // Clean up  
  64.      session.close();  
  65.      connection.close();  
  66.   } catch (Exception e) {  
  67.      e.printStackTrace();  
  68.   }  
  69. }  
  70.  
  71. public void setBrokerUri(String brokerUri) {  
  72.     this.brokerUri = brokerUri;  
  73. }  
  74.  
  75. public String getBrokerUri() {  
  76.     return brokerUri;  
  77. }  
  78.  
  79. public void setQueueName(String queueName) {  
  80.     this.queueName = queueName;  
  81. }  
  82.  
  83. public String getQueueName() {  
  84.     return queueName;  
  85. }  

第37行: log4j將一個LoggingEvent對象作為參數(shù)append方法進行調用,這個LoggingEvent對象表示了對logger的一次調用,它封裝了每一個日志項的所有信息。

第41和42行:將指向JMS的uri作為參數(shù),創(chuàng)建一個連接工廠對象,在我們的情況下,該uri指向的是我們的ActiveMQ服務器。

第45, 46和49行: 我們同JMS服務器建立一個連接和會話。會話有多種打開模式。在Auto_Acknowledge模式的會話中,消息的應答會自動發(fā)生。Client_Acknowledge 模式下,客戶端需要對消息的接收和/或處理進行顯式地應答。另外還有兩種其它的模式。有關細節(jié),請參考文檔http://download.oracle.com/javaee/1.4/api/javax/jms/Session.html

第52行: 創(chuàng)建一個隊列。將隊列的名字作為參數(shù)發(fā)送給連接

下面讓我們看看這里面發(fā)生了什么事情。

第19行:We我們實現(xiàn)了的Log4J日志追加器接口,該接口要求我們實現(xiàn)三個方法:requiresLayout, closeappend。我們將暫時簡化處理過程,實現(xiàn)所需的append方法。在對logger進行調用時這個方法就會被調用。

第56行: 我們將發(fā)送模式設置為Non_Persistent。另一個可選的模式是Persistent ,在這種模式下,消息會持久化到一個持久性存儲系統(tǒng)中。持久化模式會降低系統(tǒng)速度,但能增加了消息傳遞的可靠性。

第58行: 這行我們做了很多事。首先我將一個LoggingEvent對象封裝到了一個LoggingEventWrapper對象之中。這么做是因為LoggingEvent對象有一些屬性不支持序列化,另外還有一個原因是我想記錄一些額外的信息,比如IP地址和主機名。接下來,使用JMS的會話對象,我們把一個對象(LoggingEventWrapper對象)做好了發(fā)送前的準備。

第61行: 我將該對象發(fā)送到了隊列中。

下面所示是LoggingEventWrapper的代碼。

  1. import java.io.Serializable;  
  2. import java.net.InetAddress;  
  3. import java.net.UnknownHostException;  
  4.  
  5. import org.apache.log4j.EnhancedPatternLayout;  
  6. import org.apache.log4j.spi.LoggingEvent;  
  7.  
  8. /**  
  9.  * Logging Event Wraps a log4j LoggingEvent object. Wrapping is required by some information is lost  
  10.  * when the LoggingEvent is serialized. The idea is to extract all information required from the LoggingEvent  
  11.  * object, place it in the wrapper and then serialize the LoggingEventWrapper. This way all required data remains  
  12.  * available to us.  
  13.  * @author faheem  
  14.  *  
  15.  */ 
  16.  
  17. public class LoggingEventWrapper implements Serializable{  
  18.  
  19.     private static final String ENHANCED_PATTERN_LAYOUT = "%throwable";  
  20.     private static final long serialVersionUID = 3281981073249085474L;  
  21.     private LoggingEvent loggingEvent;  
  22.  
  23.     private Long timeStamp;  
  24.     private String level;  
  25.     private String logger;  
  26.     private String message;  
  27.     private String detail;  
  28.     private String ipAddress;  
  29.     private String hostName;  
  30.  
  31.     public LoggingEventWrapper(LoggingEvent loggingEvent){  
  32.         this.loggingEvent = loggingEvent;  
  33.  
  34.         //Format event and set detail field  
  35.         EnhancedPatternLayout layout = new EnhancedPatternLayout();  
  36.         layout.setConversionPattern(ENHANCED_PATTERN_LAYOUT);  
  37.         this.detail = layout.format(this.loggingEvent);  
  38.     }  
  39.  
  40.     public Long getTimeStamp() {  
  41.         return this.loggingEvent.timeStamp;  
  42.     }  
  43.  
  44.     public String getLevel() {  
  45.         return this.loggingEvent.getLevel().toString();  
  46.     }  
  47.  
  48.     public String getLogger() {  
  49.         return this.loggingEvent.getLoggerName();  
  50.     }  
  51.  
  52.     public String getMessage() {  
  53.         return this.loggingEvent.getRenderedMessage();  
  54.     }  
  55.  
  56.     public String getDetail() {  
  57.         return this.detail;  
  58.     }  
  59.  
  60.     public LoggingEvent getLoggingEvent() {  
  61.         return loggingEvent;  
  62.     }  
  63.  
  64.     public String getIpAddress() {  
  65.         try {  
  66.             return InetAddress.getLocalHost().getHostAddress();  
  67.         } catch (UnknownHostException e) {  
  68.             return "Could not determine IP";  
  69.         }  
  70.     }  
  71.  
  72.     public String getHostName() {  
  73.         try {  
  74.             return InetAddress.getLocalHost().getHostName();  
  75.         } catch (UnknownHostException e) {  
  76.             return "Could not determine Host Name";  
  77.         }  
  78.     }  

#p#

消息偵聽器

消息偵聽器會對隊列(或話題)進行“偵聽”。一旦有新消息添加到了隊列中,onMessage 方法就會得到調用。

  1. import javax.jms.JMSException;  
  2. import javax.jms.Message;  
  3. import javax.jms.MessageListener;  
  4. import javax.jms.ObjectMessage;  
  5.  
  6. import org.apache.log4j.Logger;  
  7. import org.springframework.beans.factory.annotation.Autowired;  
  8. import org.springframework.stereotype.Component;  
  9.  
  10. @Component 
  11. public class LogQueueListener implements MessageListener  
  12. {  
  13.     public static Logger logger = Logger.getLogger(LogQueueListener.class);  
  14.  
  15.     @Autowired 
  16.     private ILoggingService loggingService;  
  17.  
  18.     public void onMessage( final Message message )  
  19.     {  
  20.         if ( message instanceof ObjectMessage )  
  21.         {  
  22.             try{  
  23.                 final LoggingEventWrapper loggingEventWrapper = (LoggingEventWrapper)((ObjectMessage) message).getObject();  
  24.                 loggingService.saveLog(loggingEventWrapper);  
  25.             }  
  26.             catch (final JMSException e)  
  27.             {  
  28.                 logger.error(e.getMessage(), e);  
  29.             } catch (Exception e) {  
  30.             logger.error(e.getMessage(),e);  
  31.         }  
  32.         }  
  33.     }  

第23行: 檢查從隊列中拿到的對象是否是ObjectMessage的實例

第26行: 從消息中提取出LoggingEventWrapper對象

第27行: 調用服務方法將日志持久化

Spring配置

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:jms="http://www.springframework.org/schema/jms" xmlns:amq="http://activemq.apache.org/schema/core" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core-5.5.0.xsd">  
  3. <!-- lets create an embedded ActiveMQ Broker -->  
  4. <!-- uncomment the tag below only if you need to create an embedded broker -->  
  5. <!-- amq:broker useJmx="false" persistent="false">  
  6.      <amq:transportConnectors>  
  7.      <amq:transportConnector uri="tcp://localhost:61616" />  
  8.      </amq:transportConnectors>  
  9. </amq:broker-->  
  10. <!-- ActiveMQ destinations to use -->  
  11. <amq:queue id="destination" physicalName="logQueue" />  
  12. <!-- JMS ConnectionFactory to use, configuring the embedded broker using XML -->  
  13. <amq:connectionFactory id="jmsFactory" brokerURL="tcp://localhost:61616" />  
  14. <bean id="connectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">  
  15.    <constructor-arg ref="jmsFactory" />  
  16.    <property name="exceptionListener" ref="JMSExceptionListener" />  
  17.    <property name="sessionCacheSize" value="100" />  
  18. </bean>  
  19. <!-- Spring JMS Template -->  
  20. <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">  
  21.    <constructor-arg ref="connectionFactory" />  
  22. </bean>  
  23. <!-- listener container definition using the jms namespace, concurrency  
  24. is the max number of concurrent listeners that can be started -->  
  25. <jms:listener-container concurrency="10">  
  26.    <jms:listener id="QueueListener" destination="logQueue" ref="logQueueListener" />  
  27. </jms:listener-container>  
  28. </beans> 

第5到9行: 使用代理標簽建立一個嵌入式消息代理。既然我用的是外部消息代理,所以我就不需要它了。

第12行: 給出你想要連接的隊列的名字

第14行: 代理服務器的URI

15到19行: 連接工廠的設置

26到28行: 消息偵聽器的設置,這里可以指定用于從隊列中讀取消息的并發(fā)現(xiàn)線程的個數(shù)

當然,上面的例子做不到讓你能夠拿來就用。你還需要包含所有的JMS依賴庫并實現(xiàn)完成日志持久化任務的服務。但是,我希望本文能夠為你提供一個相當不錯的思路。

英文原文:Asynchronous logging using Log4j, ActiveMQ and Spring

譯文鏈接:http://www.oschina.net/translate/asynchronous-logging-using-log4j-activemq-and-spring

責任編輯:林師授 來源: OSCHINA編譯
相關推薦

2009-07-08 14:33:46

Java日志框架Log4J

2020-01-07 10:06:26

Slf4jLog4JLogback

2022-03-30 11:29:53

漏洞補丁Spring

2009-06-12 17:03:51

JBoss和log4j

2022-02-15 17:51:38

Log4j漏洞網(wǎng)絡安全

2022-03-25 13:42:15

Log4j漏洞網(wǎng)絡安全

2022-02-13 16:18:57

JetBrainsIntelliJLog4j

2021-12-24 09:52:31

Traefik Log4J 漏洞

2021-06-03 10:58:16

logbacklog4jJava

2023-10-07 10:08:54

2021-12-14 23:44:26

漏洞Log4j項目

2025-01-14 01:00:00

日志接口Log4j

2016-10-21 13:10:18

javalog4jslf4j

2020-11-04 12:33:08

Log4j 2日志Logback

2022-01-21 14:22:58

漏洞Log4Shell網(wǎng)絡犯罪

2021-12-23 09:47:36

Log4jRCE漏洞DoS漏洞

2022-01-24 10:02:53

漏洞微軟網(wǎng)絡攻擊

2021-12-13 01:49:34

漏洞Log4j代碼

2021-12-23 11:03:25

Log4j 漏洞漏洞

2022-01-10 11:54:54

FTCLog4j聯(lián)邦貿易委員會
點贊
收藏

51CTO技術棧公眾號