问题描述
我正在创建一个使用 http://hc.apache 的模块.org/httpcomponents-client-4.2.x/index.html 向外部服务发出 HTTP 请求.该模块将由应用程序使用.应用程序通过基于 XML 的配置文件配置模块的不同方面.我想在该 XML 文件中指定用于 http 通信的日志记录级别.该模块将读取该配置文件,并使用该日志级别配置 apache HTTP 客户端.我找不到任何方式以编程方式配置 apache http 库,该库具有应用程序所需的正确日志记录级别.有什么办法吗?
I am creating a module that uses http://hc.apache.org/httpcomponents-client-4.2.x/index.html to make HTTP requests to external services. This module is going to be used by application. The application configures different aspect of the module by XML based config file. and I want to specify the logging level to be used for http communication in that XML file. The module will read that config file, and configure apache HTTP client with that logging level. I could not find any way how programmatically i can configure apache http library with the right logging level the app wants. Is there any way?
推荐答案
httpclient 使用公共日志记录,如下所述:http://hc.apache.org/httpcomponents-client-4.2.x/logging.html
httpclient uses commons logging, as explained here: http://hc.apache.org/httpcomponents-client-4.2.x/logging.html
因此它将日志记录委托给您的日志记录框架.要配置 http 请求的日志记录,您需要使用日志记录框架的 API.例如,如果使用 JDK 日志记录,这样的事情应该可以工作:
So it delegates logging to your logging framework. To configure logging of http requests, you need to use the API of the logging framework.For instance, if using JDK logging, something like this should work:
java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(Level.ALL)
每个日志框架都有自己的 API.
Each logging framework will have its own API.
要使用与 commons-logging 一起打包的内置 SimpleLog 实现,您可以执行以下操作:
To use the built-in SimpleLog implementation that is packaged with commons-logging, you could do something like this:
System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.defaultlog","trace");
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.google.com");
client.execute(request);
运行此代码应该会向控制台 (syserr) 打印大量日志输出.
Running this code should print a lot of log outputs to the console (syserr).
请注意,对于生产日志记录框架来说,simplelog 并不是一个真正的好选择.你真的应该使用类似 log4j 的东西.
Note that simplelog is not really a good choice for a production logging framework. You should really use something like log4j.
这篇关于动态配置Apache Http客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!