Skip to content

Commit

Permalink
Formatted AccessLog
Browse files Browse the repository at this point in the history
  • Loading branch information
kingster committed Aug 5, 2024
1 parent 8fa71d4 commit 282e97e
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions core/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ dependencies {
implementation libraries.grpc_stub
implementation libraries.grpc_services
implementation libraries.lombok
implementation 'org.apache.commons:commons-text:1.12.0'


testImplementation libraries.junit4
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.flipkart.gjex.core.context;


import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.commons.text.StringSubstitutor;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@AllArgsConstructor
public class AccessLogContext {
String clientIp;
String resourcePath;
Integer contentLength;
Long responseTime;
Map<String,String> headers;

@SneakyThrows
Map<String,Object> getValueMap() {
Map<String, Object> params = new HashMap<>();
for (Field field : this.getClass().getDeclaredFields()) {
params.put(field.getName(), field.get(this));
}
for (Map.Entry<String, String> entry : headers.entrySet()) {
params.put("headers." + entry.getKey(), entry.getValue());
}
return params;
}

public String format(String templateFormat) {
return StringSubstitutor.replace(templateFormat, getValueMap(), "{", "}");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.flipkart.gjex.core.context;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.Map;

public class AccessLogContextTest {

@Before
public void setUp() {
}

private String template = "Formatted {clientIp} {resourcePath} {contentLength} {responseTime} {headers.x-header}";

@Test
public void testSimpleRender() {
AccessLogContext context = new AccessLogContext("127.0.0.1", "/path", 100, 1000L, Map.of("x-header", "value"));
String result = context.format(template);
Assert.assertEquals("Formatted 127.0.0.1 /path 100 1000 value", result);
}
}

0 comments on commit 282e97e

Please sign in to comment.