Dynamically configuring Apache Http client
Asked Answered
T

1

1

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?

Tatar answered 24/10, 2013 at 4:49 Comment(0)
M
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.

Mysterious answered 30/10, 2013 at 8:2 Comment(3)
Hi Barak, i am trying this System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.SimpleLog"); but could not get any log output (not even on console). System.setProperty("org.apache.commons.logging.simplelog.showdatetime","true"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http","DEBUG"); System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.wire","DEBUG"); java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(Level.ALL);Tatar
Where do you suggest I add the logging configuration in my code? I must be confused, or perhaps this is a terrible design? It doesn't seem to be very 'configurable' if it is hard-coded in my application.Indelible
Logging configuration goes in a file, which should usually be in the process working directory. Something like log4j.xml. The configuration file name is dependent on the logging library implementation you chose.Mysterious

© 2022 - 2024 — McMap. All rights reserved.