Spring log4j mq实现日志记录

Spring log4j mq实现日志记录,对于一般系统还是很实用的,简单方便。记得之前做过一个项目是解析的log日志文件,今天突发奇想log4j能不能将信息推送到mq于是百度查阅资料写了这个例子。

1、导入对应jar



    log4j
    log4j
    1.2.17




    org.slf4j
    slf4j-log4j12
    1.7.13




    org.springframework
    spring-jms
    4.0.0.RELEASE




    org.apache.activemq
    activemq-core
    5.7.0

2、配置log4j

## Be sure that ActiveMQ messages are not logged to 'jms' appender
log4j.logger.org.apache.activemq=INFO, stdout
log4j.rootLogger=INFO, stdout, jms
## Configure 'jms' appender. You'll also need jndi.properties file in order to make it work
log4j.appender.jms=org.apache.log4j.net.JMSAppender
log4j.appender.jms.InitialContextFactoryName=org.apache.activemq.jndi.ActiveMQInitialContextFactory
log4j.appender.jms.ProviderURL=tcp://localhost:61616
log4j.appender.jms.TopicBindingName=logTopic
log4j.appender.jms.TopicConnectionFactoryBindingName=ConnectionFactory

3、添加jndi配置

topic.logTopic=logTopic

4、编写接收代码

package com.anzy.frame.jms;

import java.io.Serializable;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.log4j.EnhancedPatternLayout;
import org.apache.log4j.spi.LoggingEvent;
/**
 * Created by anzy on 2018/4/12.
 */
public class LoggingEventWrapper implements Serializable{

    private static final String ENHANCED_PATTERN_LAYOUT = "%throwable";
    private static final long serialVersionUID = 3281981073249085474L;
    private LoggingEvent loggingEvent;

    private Long timeStamp;
    private String level;
    private String logger;
    private String message;
    private String detail;
    private String ipAddress;
    private String hostName;

    public LoggingEventWrapper(LoggingEvent loggingEvent){
        this.loggingEvent = loggingEvent;

        //Format event and set detail field
        EnhancedPatternLayout layout = new EnhancedPatternLayout();
        layout.setConversionPattern(ENHANCED_PATTERN_LAYOUT);
        this.detail = layout.format(this.loggingEvent);
    }

    public Long getTimeStamp() {
        return this.loggingEvent.timeStamp;
    }

    public String getLevel() {
        return this.loggingEvent.getLevel().toString();
    }

    public String getLogger() {
        return this.loggingEvent.getLoggerName();
    }

    public String getMessage() {
        return this.loggingEvent.getRenderedMessage();
    }

    public String getDetail() {
        return this.detail;
    }

    public LoggingEvent getLoggingEvent() {
        return loggingEvent;
    }

    public String getIpAddress() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            return "Could not determine IP";
        }
    }

    public String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "Could not determine Host Name";
        }
    }
}
package com.anzy.frame.jms;

import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
/**
 * Created by anzy on 2018/4/12.
 */
@Component
public class LogQueueListener implements MessageListener
{
    public static Logger logger = Logger.getLogger(LogQueueListener.class);


    public void onMessage( final Message message )
    {
        if ( message instanceof ObjectMessage )
        {
            try{
                final LoggingEvent loggingEvent = (LoggingEvent)((ObjectMessage) message).getObject();
                LoggingEventWrapper loggingEventWrapper = new LoggingEventWrapper(loggingEvent);
                loggingEvent.getMDC("user");
                System.out.println("===========================" + loggingEventWrapper.getLevel());
                System.out.println("===========================" + loggingEventWrapper.getTimeStamp());
                System.out.println("===========================" + loggingEvent.getMDC("user"));
            }
            catch (final JMSException e)
            {
                logger.error(e.getMessage(), e);
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
    }
}

因为做的是demo因此我单独写在了一个服务上了,实际项目中可以单独拿出来做日志系统。

Spring log4j mq实现日志记录_第1张图片

以上思路提供给大家参考。

咱们放在MDC中的数据同样也可以拿到    loggingEvent.getMDC("user");

====================================================

我在编写的时候第一次一直没成功,因为

log4j.rootLogger=INFO, stdout, jms
没加jms,希望大家注意。







你可能感兴趣的:(语言-Java核心技术,架构进阶,进阶-LOG)