本文介绍了使用log4j将日志发送到Java中的Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对网络服务世界相当陌生但知道 log4j



我需要实施一种功能,它将使用 Web服务appender 将日志消息发送到Web服务而不是文件。



我通过搜索 Google WebServiceAppender log4j 类之一,但我无法验证这一点。

  log4j.appender.CONSOLE = main.WSAppender 
log4j.appender.CONSOLE.endpoint = http:// localhost :8080 / Logging / services / logging?w sdl
log4j.appender.CONSOLE.layout = org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern =%p [%t ]%c {2}(%M:%L)::%m%n
WSAppender.java扩展AppenderSkeleton,无法解析端点,append()中的主机名

if( endpoint == null){
System.out.println(没有端点设置。检查配置文件);
System.out.println([+ hostname +]+ this.layout.format(event));
返回;
}


解决方案

扩展课程时 AppenderSkeleton 我认为你应该在你应该覆盖的 public void activateOptions()方法中初始化你的webservice类。我已经编写了DatabaseAppender和JmsAppender log4j记录器,我总是发现我必须初始化db连接或jms连接,或者在你的情况下, public void activateOptions()方法。



然后像往常一样在追加(LoggingEvent)方法中调用web服务。



我可能会建议实现一个BlockingQueue来存储所有LoggingEvent对象,这样如果你收到大量日志消息,它们就会排队并异步发送到web服务。 / p>

更新以包含模板Log4j类



尝试使用以下模板。我在重要部分添加了评论。基本上在activateOptions和processEvent方法中,您可以初始化连接并发送事件对象。可以是DB,JMS,WebService等等。

  package mypackage; 

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

公共类WebServiceAppender扩展AppenderSkeleton {

私有静态最终BlockingQueue< LoggingEvent> loggingEventQueue = new LinkedBlockingQueue< LoggingEvent>();
私有静态WebServiceAppender实例;
private static Thread thread = null;

//您的Web服务的自定义属性

private String property1;
private String property2;
private String property3;

static {
thread = new Thread(new Runnable(){
public void run(){
processQueue();
}
});

thread.setDaemon(true);
thread.start();
}

private static void processQueue(){
while(true){
try {
LoggingEvent event = loggingEventQueue.poll(1L,TimeUnit。秒);
if(event!= null){
instance.processEvent(event);
}
}
catch(InterruptedException e){
//无操作。
}
}
}

private final void processEvent(LoggingEvent loggingEvent){
if(loggingEvent!= null){
//发送loggingEvent对象,或者你可以
//从中获取数据并将其打包到另一个
// java类中并将其发送到您的Web服务。

//这里调用Web服务
}
}

public synchronized void close(){
//同步修改器避免并发追加和平仓操作

if(this.closed){
return;
}

closeWS();
thread.interrupt();

LogLog.debug(Closing appender [+ name +]。);
this.closed = true;
}

private void closeWS(){
try {
//关闭webservice连接
//或此处的任何内容。
}
catch(Exception ex){
LogLog.error(关闭WebServiceAppender [+ name +]时出错。,ex);
}
}

public boolean requiresLayout(){
//不需要布局,因为
//我们正在发送序列化事件
//到外部源
返回false;
}

@Override
public void activateOptions(){
instance = this;
try {
LogLog.debug(获取网络服务属性。);

if(property1!= null){
//对你的财产做一些事情
}

if(property2!= null){
//用您的房产做一些事情
}

if(property3!= null){
//用您的房产做一些事情
}

//在这里初始化您的Web服务连接和对象
LogLog.debug(Web Service created。);
}
catch(exception ex){
LogLog.error(激活WebServiceAppender [+ name +]的选项时出错。,ex);
}
}

/ *
*这些方法是从log4j属性文件设置的,如:
* log4j.appender.WS = mypackage.WebServiceAppender
* log4j.appender.WS.property1 = bla
* log4j.appender.WS.property2 = ble
* log4j.appender.WS.property3 = blo
* /

public final String getProperty1(){
return property1;
}

public final String getProperty2(){
return property2;
}

public final String getProperty3(){
return property3;
}

public final void setProperty1(String property1){
this.property1 = property1;
}

public final void setProperty2(String property2){
this.property2 = property2;
}

public final void setProperty3(String property3){
this.property3 = property3;
}

@Override
protected void append(LoggingEvent event){
loggingEventQueue.add(event);
}

@Override
public void finalize(){
close();
super.finalize();
}
}


I am fairly new to the web services world but have knowledge of log4j.

I need to implement a functionality which will send the log messages to a web service rather than to a file using web service appender.

I read by searching on Google that WebServiceAppender is one of the log4j class, but I couldn't verify this.

log4j.appender.CONSOLE=main.WSAppender 
log4j.appender.CONSOLE.endpoint=http://localhost:8080/Logging/services/logging?w‌​sdl 
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout 
log4j.appender.CONSOLE.layout.ConversionPattern=%p [%t] %c{2} (%M:%L) :: %m%n 
WSAppender.java extends AppenderSkeleton, can't resolve endpoint, hostname in append()    

if (endpoint == null) { 
    System.out.println("no endpoint set. Check configuration file"); 
    System.out.println("[" + hostname + "] " + this.layout.format(event)); 
    return; 
}
解决方案

when you extend the class AppenderSkeleton I would assume that you should initialize your webservice class in the public void activateOptions() method which you should override. I've written DatabaseAppender and JmsAppender log4j loggers and I've always found that I have to initialize the db connection or jms connection or in your case the webservice properties in the public void activateOptions() method.

Then as usual in the append(LoggingEvent) method you would just invoke the webservice.

Might I suggest to implement a BlockingQueue to store all the LoggingEvent objects so that if you are getting an influx of log messages they are queued and sent to the webservice asynchronously.

Updated to include a Template Log4j Class

Try to use the below template. I added comments in important sections. Basically in the activateOptions and processEvent method is where you would initialize your "connection" and send your event objects. Can be DB, JMS, WebService ...etc.

package mypackage;

      import java.util.concurrent.BlockingQueue;
      import java.util.concurrent.LinkedBlockingQueue;
      import java.util.concurrent.TimeUnit;
      import org.apache.log4j.AppenderSkeleton;
      import org.apache.log4j.helpers.LogLog;
      import org.apache.log4j.spi.LoggingEvent;

      public class WebServiceAppender extends AppenderSkeleton {

            private static final BlockingQueue<LoggingEvent> loggingEventQueue = new LinkedBlockingQueue<LoggingEvent>();
            private static WebServiceAppender instance;
            private static Thread thread = null;

            //Your custom properties for your web service

            private String property1;
            private String property2;
            private String property3;

            static {
                thread = new Thread(new Runnable() {
                    public void run() {
                        processQueue();
                    }
                });

                thread.setDaemon(true);
                thread.start();
            }

            private static void processQueue() {
                while(true) {
                    try {
                        LoggingEvent event = loggingEventQueue.poll(1L, TimeUnit.SECONDS);
                        if (event != null) {
                            instance.processEvent(event);
                        }
                    }
                    catch(InterruptedException e) {
                        // No operations.
                    }
                }
            }

            private final void processEvent(LoggingEvent loggingEvent) {
                if(loggingEvent != null) {
                    //Send the loggingEvent object or you can
                    //get data out of it and package it in another
                    //java class and send that, to your web service.

                    //Web Service is invoked here
                }
            }

            public synchronized void close() {
                // The synchronized modifier avoids concurrent append and close operations

                    if(this.closed) {
                      return;
                }

                closeWS();
                thread.interrupt();

                LogLog.debug("Closing appender [" + name + "].");
                this.closed = true;
            }

            private void closeWS() {
                try {
                    //Close the webservice connection 
                    //or whatever here.
                }
                catch(Exception ex) {
                    LogLog.error("Error while closing WebServiceAppender [" + name + "].", ex);
                }
            }

            public boolean requiresLayout() {
                //Does not need a layout because
                //we are sending serialized events
                //to an external source
                return false;
            }

            @Override
            public void activateOptions() {
                instance = this;
                try {
                    LogLog.debug("Getting web service properties.");

                    if(property1 != null) {
                        //Do something with your property
                    }

                    if(property2 != null) {
                        //Do something with your property
                    }

                    if(property3 != null) {
                        //Do something with your property
                    }

                    //Initialize your web-service connection and objects here
                    LogLog.debug("Web Service created.");
                }
                catch(Exception ex) {
                    LogLog.error("Error while activating options for WebServiceAppender [" + name + "].", ex);
                }
            }

            /*
             * These methods are set from the log4j properties file like:
             * log4j.appender.WS=mypackage.WebServiceAppender
             * log4j.appender.WS.property1=bla
             * log4j.appender.WS.property2=ble
             * log4j.appender.WS.property3=blo
             */

            public final String getProperty1() {
                return property1;
            }

            public final String getProperty2() {
                return property2;
            }

            public final String getProperty3() {
                return property3;
            }

            public final void setProperty1(String property1) {
                this.property1 = property1;
            }

            public final void setProperty2(String property2) {
                this.property2 = property2;
            }

            public final void setProperty3(String property3) {
                this.property3 = property3;
            }

            @Override
            protected void append(LoggingEvent event) {
                loggingEventQueue.add(event);
            }

            @Override
            public void finalize() {
                close();
                super.finalize();
            }
      }

这篇关于使用log4j将日志发送到Java中的Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 12:44