问题
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?
回答1:
httpclient uses commons logging, as explained here: http://hc.apache.org/httpcomponents-client-4.2.x/logging.html
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)
Each logging framework will have its own API.
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);
Running this code should print a lot of log outputs to the console (syserr).
Note that simplelog is not really a good choice for a production logging framework. You should really use something like log4j.
来源:https://stackoverflow.com/questions/19557178/dynamically-configuring-apache-http-client