Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add http logging for Java #606

Merged
merged 7 commits into from
Dec 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,13 @@ Twilio.setEdge("sydney");

This will result in the `hostname` transforming from `api.twilio.com` to `api.sydney.au1.twilio.com`.

### Enable Debug Logging
In order to enable debug logging, create a configuration file named log4j2.xml that defines the logger at the root level to at least 'debug'. An example of the configuration file can be found [here](src/main/java/com/twilio/example/log4j2.xml). For more configuration options please see the log4j configuration [documentation](https://logging.apache.org/log4j/2.x/manual/configuration.html).
```java
Twilio.init(accountSid, authToken);
Twilio.setLoggerConfiguration("path/to/log4j2.xml");
```

### Environment Variables

`twilio-java` supports the credentials, region, and edge values stored in the following environment variables:
Expand Down Expand Up @@ -139,7 +146,7 @@ try {
new PhoneNumber("+15559994321"), // From number
"Hello world!" // SMS body
).create();

System.out.println(message.getSid());
} catch (final ApiException e) {
System.err.println(e);
Expand Down
12 changes: 11 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,16 @@
<version>3.4.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.14.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.0</version>
</dependency>
</dependencies>
<build>
<plugins>
Expand Down Expand Up @@ -382,4 +392,4 @@
<artifactId>oss-parent</artifactId>
<version>7</version>
</parent>
</project>
</project>
17 changes: 17 additions & 0 deletions src/main/java/com/twilio/Twilio.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.File;

import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.LogManager;

/**
* Singleton class to initialize Twilio environment.
Expand Down Expand Up @@ -150,6 +154,19 @@ public static synchronized void setEdge(final String edge) {
Twilio.edge = edge;
}

/**
* Set the logger configuration file path.
*
* @param filePath path to logging configuration file
* @param loggerContext defaults to false to get the appropriate logger context for the caller.
*/
public static synchronized void setLoggerConfiguration(final String filePath, final boolean... loggerContext) {
boolean logContext = (loggerContext.length >= 1) ? loggerContext[0] : false;
LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(logContext);
File file = new File(filePath);
context.setConfigLocation(file.toURI());
}

/**
* Returns (and initializes if not initialized) the Twilio Rest Client.
*
Expand Down
14 changes: 14 additions & 0 deletions src/main/java/com/twilio/example/log4j2.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--logging configuration file example-->
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d [%t] %-5p %c - %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="STDOUT"/>
</Root>
</Loggers>
</Configuration>
43 changes: 42 additions & 1 deletion src/main/java/com/twilio/http/TwilioRestClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.util.function.Predicate;
import java.util.Map;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;

public class TwilioRestClient {

Expand All @@ -19,6 +25,7 @@ public class TwilioRestClient {
private final String region;
private final String edge;
private final HttpClient httpClient;
private static final Logger logger = LogManager.getLogger();

private TwilioRestClient(Builder b) {
this.username = b.username;
Expand Down Expand Up @@ -50,7 +57,16 @@ public Response request(final Request request) {
if (edge != null)
request.setEdge(edge);

return httpClient.reliableRequest(request);
logRequest(request);
eshanholtz marked this conversation as resolved.
Show resolved Hide resolved
Response response = httpClient.reliableRequest(request);
logger.debug("status code: " + response.getStatusCode());
org.apache.http.Header[] responseHeaders = response.getHeaders();
logger.debug("response headers:");
for (int i = 0; i < responseHeaders.length; i++) {
logger.debug(responseHeaders[i]);
}

return response;
}

public String getAccountSid() {
Expand Down Expand Up @@ -126,4 +142,29 @@ public TwilioRestClient build() {
}
}

/**
* Logging debug information about HTTP request.
*/
public void logRequest(final Request request) {
logger.debug("-- BEGIN Twilio API Request --");
logger.debug("request method: " + request.getMethod());
logger.debug("request URL: " + request.getUrl());
final Map<String, List<String>> queryParams = request.getQueryParams();
final Map<String, List<String>> headerParams = request.getHeaderParams();

if (!queryParams.isEmpty()) {
logger.debug("query parameters: " + queryParams);
}

if (!headerParams.isEmpty()) {
logger.debug("header parameters: ");
for (String key : headerParams.keySet()) {
if (!key.toLowerCase().contains("authorization")) {
logger.debug(key + ": " + headerParams.get(key));
}
}
}
logger.debug("-- END Twilio API Request --");
}

}
59 changes: 59 additions & 0 deletions src/test/java/com/twilio/http/LoggingTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.twilio.http;

import com.twilio.Twilio;
import com.twilio.rest.Domains;
import com.twilio.rest.api.v2010.account.Message;
import org.junit.Before;
import org.junit.Test;
import org.junit.Assert;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class LoggingTest {
private ByteArrayOutputStream output;
private PrintStream originalStream;

@Before
public void setUp() throws Exception {
Twilio.init("AC123", "AUTH TOKEN");
}

public void logCapturingSetup() {
output = new ByteArrayOutputStream();
PrintStream outputStream = new PrintStream(output);
originalStream = System.out;
System.setOut(outputStream);
}

public void finishLogCapturingSetup(Request request) {
TwilioRestClient twilioRestClient = Twilio.getRestClient();
twilioRestClient.logRequest(request);
System.out.flush();
System.setOut(originalStream);
}

@Test
public void testDebugLogging() {
logCapturingSetup();
Twilio.setLoggerConfiguration("src/main/java/com/twilio/example/log4j2.xml");
final Request request = new Request(HttpMethod.GET, Domains.API.toString(),
"/2010-04-01/Accounts/AC123/Messages/MM123.json");
request.addHeaderParam("Authorization", "authorization value");
request.addHeaderParam("Test Header", "test value");
finishLogCapturingSetup(request);
Assert.assertTrue(output.toString().contains("GET"));
Assert.assertFalse(output.toString().contains("Authorization"));
}

@Test
public void testUsingDefaultConfigurationFileDebugLogging() {
logCapturingSetup();
final Request request = new Request(HttpMethod.GET, Domains.API.toString(),
"/2010-04-01/Accounts/AC123/Messages/MM123.json");
request.addHeaderParam("Authorization", "authorization value");
request.addHeaderParam("Test Header", "test value");
finishLogCapturingSetup(request);
Assert.assertTrue(output.toString().isEmpty());
}
JenniferMah marked this conversation as resolved.
Show resolved Hide resolved
}