如何在groovyConsole中显示HTTPBuilder日志

时间:2013-12-13 17:48:03

标签: logging groovy httpbuilder groovy-2

问题

我收到groovyx.net.http.HttpResponseException: Not Found并希望查看来自HTTPBuilder的日志。我正在使用 Groovy 2.1.9 groovyConsole

我尝试了什么

因此,我检查了this blog post关于将log4j.xml添加到groovy.home/conf/的问题。我这样做了,这是我的档案:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p  %c{1} - %m%n" />
        </layout>
    </appender>

    <category name="groovyx.net.http">
        <priority value="DEBUG" />
    </category>

    <!-- Use DEBUG to see basic request/response info;  
         Use TRACE to see headers for HttpURLClient. -->
    <category name="groovyx.net.http.HttpURLClient">
        <priority value="INFO" />
    </category>

    <category name="org.apache.http">
        <priority value="DEBUG" />
    </category>
    <category name="org.apache.http.headers">
        <priority value="DEBUG" />
    </category>
    <category name="org.apache.http.wire">
        <priority value="DEBUG" />
    </category>

    <root>
        <priority value="INFO" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>

这是我在控制台中运行的脚本:

import groovyx.net.http.*
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager
import javax.net.ssl.SSLContext
import java.security.cert.X509Certificate
import javax.net.ssl.TrustManager
import java.security.SecureRandom
import org.apache.http.conn.ssl.SSLSocketFactory
import org.apache.http.conn.scheme.Scheme
import org.apache.http.conn.scheme.SchemeRegistry

import groovy.util.logging.*

@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6')
@Grab( 'log4j:log4j:1.2.16' )
@Log4j
class WebserviceTest {
  static void main (String[] args) {

    def http = new HTTPBuilder('https://localhost:8443/project/service/')
    log.debug "http is instanceof ${http.getClass()}" //this is printed

    //=== SSL UNSECURE CERTIFICATE ===
   def sslContext = SSLContext.getInstance("SSL")              
   sslContext.init(null, [ new X509TrustManager() {
     public X509Certificate[] getAcceptedIssuers() {null}
     public void checkClientTrusted(X509Certificate[] certs, String authType) { }
     public void checkServerTrusted(X509Certificate[] certs, String authType) { }
   } ] as TrustManager[], new SecureRandom())
   def sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
   def httpsScheme = new Scheme("https", sf, 4483)
   http.client.connectionManager.schemeRegistry.register( httpsScheme )
   //================================

    //the next line throws the exeption...
    http.post(path: '/method', contentType: ContentType.JSON, query: [param: '1000']) { resp, reader ->
        println "resp is instanceof ${resp.getClass()}"
        println "and reader is instanceof ${reder.getClass()}"

        println "response status: ${resp.statusLine}"
        println 'Headers: -----------'
        resp.headers.each { h ->
          println " ${h.name} : ${h.value}"
        }
        println 'Response data: -----'
        System.out << reader
        println '\n--------------------'

    }
  } 
}

编辑:我的HttpResponseException已解决,我在请求中没有/,但仍然没有出现构建器日志。

2 个答案:

答案 0 :(得分:2)

HTTPBuilder使用commons-logging,因此您必须将commons-logging的输出桥接到log4j。不幸的是,log4j 1.2并不支持开箱即用。所以我简化了你的例子,并切换到SLF4J,这是一个简单的Java日志记录门面&#39;。在引擎盖下,以下配置仍然使用log4j,因此您仍然需要log4j.xmlgroovy.home/conf/)。有关详细说明,请参阅Bridging legacy APIs

@Grapes([
    @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.6'),
    // This brings in slf4j, log4j12 (as dependancies) and the bridge to log4j
    @Grab(group='org.slf4j', module='slf4j-log4j12', version='1.7.7'),
    // This brings in the bridge to commons-logging
    @Grab(group='org.slf4j', module='jcl-over-slf4j', version='1.7.7')
])

import org.slf4j.LoggerFactory
import groovyx.net.http.*

// get a logger for the script
def log = LoggerFactory.getLogger('script')

def http = new HTTPBuilder('http://www.google.com')
log.info "http is instanceof ${http.getClass()}" //this is printed

http.get( path : '/search', contentType : ContentType.TEXT, query : [q:'Groovy'] ) { resp, reader ->
    log.debug "response status: ${resp.statusLine}"
    println 'Done'
}

答案 1 :(得分:0)

试试这个 导入此

import ch.qos.logback.classic.Level
import ch.qos.logback.classic.Logger

并设置

Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)
rootLogger.setLevel(mLevel)

您可以在调用HTTP构建器之前设置此项