Skip to content
This repository has been archived by the owner on Jul 14, 2022. It is now read-only.

Commit

Permalink
Add Log4J logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Jesion authored and Maciej Billewicz committed May 18, 2017
1 parent 439f05a commit a19aa10
Show file tree
Hide file tree
Showing 14 changed files with 153 additions and 38 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -5,3 +5,4 @@ target/
*.iml
.idea
.vscode
.DS_Store
38 changes: 38 additions & 0 deletions README.md
Expand Up @@ -32,6 +32,43 @@ Determines the URL of the production platform.
## platformUrlSandbox
Determines the URL of the sandbox platform.

---
# Logging
Cleeng Java SDK depends on Log4J in order to provide logging capability. It is configured to log events to both the system console and cleeng.log file, which can be found in a folder containing the SDK build.
Log4J configuration for the SDK can be found in 'src/main/resources'. Feel free to remove ```<AppenderRef ref="File"/>``` elements in order to stop logging to a file.
```
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="filename">target/cleeng.log</Property>
</Properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="File" fileName="${filename}">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
<Root level="warn">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
```

---
# Example usage with synchronous/blocking method call
```
Expand Down Expand Up @@ -194,3 +231,4 @@ There are a few example Java programs in the jar file, that you can run as follo
```java -cp path/to/cleeng-java-sdk-{version}-jar-with-dependencies.jar com/cleeng/api/examples/CleengJavaAPIBatchExample```

```java -cp path/to/cleeng-java-sdk-{version}-jar-with-dependencies.jar com/cleeng/api/examples/CleengJavaAPIBatchExampleAsync```

10 changes: 10 additions & 0 deletions pom.xml
Expand Up @@ -108,6 +108,16 @@
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies>

<url>http://cleeng.com/open/</url>
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/com/cleeng/api/AsyncRequestCallback.java
Expand Up @@ -2,6 +2,8 @@

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.Response;

Expand All @@ -11,6 +13,8 @@

public class AsyncRequestCallback<T> extends CompletableFuture<Response> {

private static final Logger logger = LogManager.getLogger(AsyncRequestCallback.class);

protected Gson gson;

public AsyncRequestCallback(Class<T> responseClass) {
Expand Down Expand Up @@ -45,7 +49,7 @@ public T getResponse() {
@Override
public boolean complete(final Response response) {
final boolean out = super.complete(response);
System.out.println("Completed async request: " + response.getStatusCode() + " count: " + this._countdownLatch.getCount() + " response: " + this._responseClass.getCanonicalName());
logger.info("Completed async request: " + response.getStatusCode() + " count: " + this._countdownLatch.getCount() + " response: " + this._responseClass.getCanonicalName());
try {
this._response = response.getResponseBody();
} catch (Exception e) {
Expand All @@ -54,10 +58,10 @@ public boolean complete(final Response response) {
if (this.useNonBlockingMode == true) {
if (this._countdownLatch.getCount() == 0) {
try {
System.out.println("Closing connection...");
logger.info("Closing connection...");
this._client.close();
} catch (IOException e) {
System.out.println("Failed to close http connection...");
logger.error("Failed to close http connection...");
}
}
}
Expand All @@ -67,7 +71,7 @@ public boolean complete(final Response response) {

@Override
public boolean completeExceptionally(Throwable ex) {
System.out.println("Request completed with exception " + ex);
logger.error("Request completed with exception " + ex);
return super.completeExceptionally(ex);
}

Expand Down
10 changes: 7 additions & 3 deletions src/main/java/com/cleeng/api/BatchAsyncRequest.java
Expand Up @@ -5,6 +5,8 @@
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsonrpc.JSONRPCMessage;
import org.jsonrpc.JSONRPCRequest;

Expand All @@ -14,6 +16,8 @@

public class BatchAsyncRequest extends AsyncRequestCallback<BatchResponse> {

private static final Logger logger = LogManager.getLogger(BatchAsyncRequest.class);

private List<JSONRPCMessage> requests;

private ResponseMapper mapper = new ResponseMapper();
Expand Down Expand Up @@ -58,14 +62,14 @@ public BatchResponse getResponse() {
String responseTypeName = this.mapper.map(r.method);
if (responseTypeName != null) {
try {
System.out.println("Processing " + responseTypeName);
logger.info("Processing " + responseTypeName);
Serializable payload = (Serializable) this.gson.fromJson(res, Class.forName(responseTypeName));
batchResponse.responses.add(payload);
} catch (ClassNotFoundException e) {
System.out.println("Class not found " + e);
logger.error("Class not found " + e);
}
} else {
System.out.println("Mapper did not contain a response type for " + r.getClass().getTypeName());
logger.warn("Mapper did not contain a response type for " + r.getClass().getTypeName());
}
}
}
Expand Down
12 changes: 8 additions & 4 deletions src/main/java/com/cleeng/api/CleengImpl.java
Expand Up @@ -3,6 +3,8 @@
import com.cleeng.api.domain.*;
import com.cleeng.api.domain.async.*;
import com.google.gson.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsonrpc.JSONRPCRequest;

import java.io.FileInputStream;
Expand All @@ -14,6 +16,8 @@

public class CleengImpl implements Cleeng {

private static final Logger logger = LogManager.getLogger(CleengImpl.class);

private String publisherToken;
private String platformUrl;
private Gson gson;
Expand Down Expand Up @@ -625,14 +629,14 @@ public BatchResponse invokeBatch(BatchRequest batch) throws IOException {
String responseTypeName = mapper.map(r.method);
if (responseTypeName != null) {
try {
System.out.println("Processing " + responseTypeName);
logger.info("Processing " + responseTypeName);
Serializable payload = (Serializable) this.gson.fromJson(res, Class.forName(responseTypeName));
batchResponse.responses.add(payload);
} catch (ClassNotFoundException e) {
System.out.println("Class not found " + e);
logger.error("Class not found " + e);
}
} else {
System.out.println("Mapper did not contain a response type for " + r.getClass().getTypeName());
logger.warn("Mapper did not contain a response type for " + r.getClass().getTypeName());
}
}
}
Expand Down Expand Up @@ -671,7 +675,7 @@ private void initProps(String propertiesPath) {
this.config.platformUrl = properties.getProperty("platformUrl");
this.config.platformUrlSandbox = properties.getProperty("platformUrlSandbox");
} catch (IOException e) {
System.out.println("Config file not found or invalid.");
logger.error("Config file not found or invalid.");
} finally {
if (input != null) {
try {
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/com/cleeng/api/HttpClient.java
Expand Up @@ -18,6 +18,8 @@
import org.apache.http.impl.client.*;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.asynchttpclient.*;

import java.io.IOException;
Expand All @@ -28,6 +30,8 @@
@SuppressWarnings("unchecked")
public class HttpClient {

private static final Logger logger = LogManager.getLogger(HttpClient.class);

public Config config;

public synchronized String invokeBatch(BatchRequest request, String platformUrl) throws IOException {
Expand Down Expand Up @@ -69,7 +73,7 @@ public String handleResponse(HttpResponse httpResponse) throws IOException {
StatusLine statusLine = httpResponse.getStatusLine();
HttpEntity entity = httpResponse.getEntity();
if (statusLine.getStatusCode() >= 300) {
System.out.println(" Server returned response code: " + statusLine.getStatusCode() + " reason: " + statusLine.getReasonPhrase());
logger.error(" Server returned response code: " + statusLine.getStatusCode() + " reason: " + statusLine.getReasonPhrase());
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
if (entity == null) {
Expand Down
Expand Up @@ -3,11 +3,15 @@
import com.cleeng.api.Cleeng;
import com.cleeng.api.CleengFactory;
import com.cleeng.api.domain.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Arrays;

public class CleengJavaAPIBatchExample {

private static final Logger logger = LogManager.getLogger(CleengJavaAPIBatchExample.class);

public static void main(String args[]) throws Exception {

String publisherToken = "IEiuf3fJzAorVvxgBYiHiHXGk8oFPckTMSOn8hS1--lOti30";
Expand Down Expand Up @@ -36,6 +40,6 @@ public static void main(String args[]) throws Exception {

BatchResponse response = api.invokeBatch(batch);

System.out.println("Done. Number of responses available: " + response.responses.size());
logger.info("Done. Number of responses available: " + response.responses.size());
}
}
Expand Up @@ -5,12 +5,16 @@
import com.cleeng.api.CleengFactory;
import com.cleeng.api.domain.*;
import com.cleeng.api.domain.BatchResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

public class CleengJavaAPIBatchExampleAsync {

private static final Logger logger = LogManager.getLogger(CleengJavaAPIBatchExampleAsync.class);

public static void main(String args[]) throws Exception {

String publisherToken = "IEiuf3fJzAorVvxgBYiHiHXGk8oFPckTMSOn8hS1--lOti30";
Expand Down Expand Up @@ -43,7 +47,7 @@ public static void main(String args[]) throws Exception {

final BatchResponse response = batch.getResponse();

System.out.println("Done. Number of responses available: " + response.responses.size());
logger.info("Done. Number of responses available: " + response.responses.size());

System.exit(0);
}
Expand Down
Expand Up @@ -6,9 +6,13 @@
import com.cleeng.api.*;
import com.cleeng.api.domain.OfferResponse;
import com.cleeng.api.domain.SubscriptionOfferData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

class CleengJavaAPIExample {

private static final Logger logger = LogManager.getLogger(CleengJavaAPIExample.class);

public static void main(String args[]) throws Exception {

String publisherToken = "IEiuf3fJzAorVvxgBYiHiHXGk8oFPckTMSOn8hS1--lOti30";
Expand All @@ -29,6 +33,6 @@ public static void main(String args[]) throws Exception {
);
final OfferResponse response = api.createSubscriptionOffer(offerData);

System.out.println("Done. Created offer id: " + response.result.id);
logger.info("Done. Created offer id: " + response.result.id);
}
}
Expand Up @@ -6,13 +6,17 @@
import com.cleeng.api.CleengFactory;
import com.cleeng.api.domain.OfferResponse;
import com.cleeng.api.domain.SubscriptionOfferData;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class CleengJavaAPIExampleAsync {

private static final Logger logger = LogManager.getLogger(CleengJavaAPIExampleAsync.class);

public static void main(String args[]) throws Exception {

String publisherToken = "IEiuf3fJzAorVvxgBYiHiHXGk8oFPckTMSOn8hS1--lOti30";
Expand Down Expand Up @@ -40,7 +44,7 @@ public static void main(String args[]) throws Exception {

Thread.sleep(2000);

System.out.println("Done. Created offer id: " + callback.getResponse().result.id);
logger.info("Done. Created offer id: " + callback.getResponse().result.id);

System.exit(0);
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/resources/config.properties
@@ -1,6 +1,6 @@
socketTimeout=3000
connectTimeout=400
requestTimeout=3000
socketTimeout=9000
connectTimeout=600
requestTimeout=9000
retryCount=10
useNonBlockingMode=true
platformUrl=https://cleeng.com/api/3.0/json-rpc
Expand Down
30 changes: 30 additions & 0 deletions src/main/resources/log4j2.xml
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="filename">target/cleeng.log</Property>
</Properties>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="File" fileName="${filename}">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
<Root level="warn">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
<Root level="info">
<AppenderRef ref="Console"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>

0 comments on commit a19aa10

Please sign in to comment.