要解决使用Log4j2记录Http Client日志的问题,可以按照以下步骤进行:
org.apache.logging.log4j
log4j-api
2.14.1
org.apache.logging.log4j
log4j-core
2.14.1
此配置文件将打印Http Client相关的日志到控制台。
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class HttpClientExample {
private static final Logger logger = LogManager.getLogger(HttpClientExample.class);
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com");
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
logger.info("Response: " + result);
} catch (Exception e) {
logger.error("Error occurred during HTTP request.", e);
} finally {
try {
httpClient.close();
} catch (Exception e) {
logger.error("Error occurred while closing HTTP client.", e);
}
}
}
}
在上述示例代码中,我们创建了一个CloseableHttpClient对象,发送了一个HttpGet请求,并将返回结果记录到日志中。
使用以上步骤,你可以成功地使用Log4j2记录Http Client的日志。