0

Merge branch 'dev/logger' into rc/1.13

# Conflicts:
#	build.gradle
This commit is contained in:
2021-10-08 14:44:27 +03:00
11 changed files with 690 additions and 2 deletions

View File

@@ -1,5 +1,6 @@
plugins {
id 'java'
id 'jacoco'
}
project.group = 'ghast'
@@ -20,12 +21,13 @@ repositories {
def lombokVersion = '1.18.20'
def junitVersion = '5.8.1'
def bukkitVersion = '1.12.2-R0.1-SNAPSHOT'
dependencies {
annotationProcessor("org.projectlombok:lombok:$lombokVersion")
compileOnly("org.projectlombok:lombok:$lombokVersion")
compileOnly('org.bukkit:bukkit:1.12.2-R0.1-SNAPSHOT') {
compileOnly("org.bukkit:bukkit:$bukkitVersion") {
exclude(module: 'gson')
exclude(module: 'json-simple')
exclude(module: 'commons-lang')
@@ -37,7 +39,7 @@ dependencies {
testImplementation("org.junit.jupiter:junit-jupiter-api:$junitVersion")
testImplementation("org.junit.jupiter:junit-jupiter-engine:$junitVersion")
testImplementation('org.mockito:mockito-core:3.12.4')
testImplementation('org.bukkit:bukkit:1.12.2-R0.1-SNAPSHOT') {
testImplementation("org.bukkit:bukkit:$bukkitVersion") {
exclude(module: 'gson')
exclude(module: 'json-simple')
exclude(module: 'commons-lang')
@@ -49,3 +51,11 @@ dependencies {
test {
useJUnitPlatform()
}
jacoco {
toolVersion = '0.8.5'
}
jacocoTestReport {
dependsOn test
}

View File

@@ -6,8 +6,12 @@ import java.util.logging.Level;
import static java.text.MessageFormat.format;
/**
* @deprecated use {@link ghast.logger.BukkitLogger}
*/
@UtilityClass
@SuppressWarnings("unused")
@Deprecated
public class XLog {
//region Debug

View File

@@ -0,0 +1,42 @@
package ghast.logger;
import lombok.RequiredArgsConstructor;
import java.util.logging.Level;
import java.util.logging.Logger;
@RequiredArgsConstructor
public class BukkitLogger extends LoggerAdapter {
private final Logger originallLogger;
@Override
public void debug(String message) {
originallLogger.log(Level.CONFIG, message);
}
@Override
public void debug(String message, Throwable throwable) {
originallLogger.log(Level.CONFIG, message, throwable);
}
@Override
public void info(String message) {
originallLogger.log(Level.INFO, message);
}
@Override
public void warn(String message) {
originallLogger.log(Level.WARNING, message);
}
@Override
public void error(String message) {
originallLogger.log(Level.SEVERE, message);
}
@Override
public void error(String message, Throwable throwable) {
originallLogger.log(Level.SEVERE, message, throwable);
}
}

View File

@@ -0,0 +1,17 @@
package ghast.logger;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Getter
public class FormattingPair {
private final String message;
private final Throwable throwable;
public FormattingPair(String message) {
this.message = message;
this.throwable = null;
}
}

View File

@@ -0,0 +1,37 @@
package ghast.logger;
public abstract class LoggerAdapter {
public abstract void debug(String message);
public abstract void debug(String message, Throwable throwable);
public abstract void info(String message);
public abstract void warn(String message);
public abstract void error(String message);
public abstract void error(String message, Throwable throwable);
public void debug(String pattern, Object... objects) {
FormattingPair formattingPair = LoggerFormatter.arrayFormat(pattern, objects);
if (formattingPair.getThrowable() != null) {
debug(formattingPair.getMessage(), formattingPair.getThrowable());
} else {
debug(formattingPair.getMessage());
}
}
public void info(String pattern, Object... objects) {
info(StringFormatter.arrayFormat(pattern, objects));
}
public void warn(String pattern, Object... objects) {
warn(StringFormatter.arrayFormat(pattern, objects));
}
public void error(String pattern, Object... objects) {
FormattingPair formattingPair = LoggerFormatter.arrayFormat(pattern, objects);
if (formattingPair.getThrowable() != null) {
error(formattingPair.getMessage(), formattingPair.getThrowable());
} else {
error(formattingPair.getMessage());
}
}
}

View File

@@ -0,0 +1,55 @@
package ghast.logger;
/**
* Copy-Paste from org.slf4j.helpers.MessageFormatter
*/
public final class LoggerFormatter {
public static FormattingPair arrayFormat(String messagePattern, Object[] argArray) {
Object[] args;
Throwable throwableCandidate = getThrowableCandidate(argArray);
if (throwableCandidate != null) {
args = trimmedCopy(argArray);
} else {
args = argArray;
}
return arrayFormat(messagePattern, args, throwableCandidate);
}
public static FormattingPair arrayFormat(String messagePattern, Object[] argArray, Throwable throwable) {
if (messagePattern == null) {
return new FormattingPair(null, throwable);
}
if (argArray == null) {
return new FormattingPair(messagePattern);
}
return new FormattingPair(StringFormatter.arrayFormat(messagePattern, argArray), throwable);
}
private static Throwable getThrowableCandidate(Object[] argArray) {
if (argArray == null || argArray.length == 0) {
return null;
}
Object lastEntry = argArray[argArray.length - 1];
if (lastEntry instanceof Throwable) {
return (Throwable) lastEntry;
}
return null;
}
private static Object[] trimmedCopy(final Object[] argArray) {
int trimmedLen = argArray.length - 1;
Object[] trimmed = new Object[trimmedLen];
if (trimmedLen > 0) {
System.arraycopy(argArray, 0, trimmed, 0, trimmedLen);
}
return trimmed;
}
}

View File

@@ -0,0 +1,240 @@
package ghast.logger;
import java.util.HashMap;
import java.util.Map;
/**
* Copy-Paste from org.slf4j.helpers.MessageFormatter
*/
public final class StringFormatter {
private static final String EMPTY = "";
private static final char DELIM_START = '{';
private static final String DELIM_STR = "{}";
private static final char ESCAPE_CHAR = '\\';
public static String arrayFormat(String messagePattern, Object[] argArray) {
if (messagePattern == null || messagePattern.equals(EMPTY)) {
return EMPTY;
} else if (argArray == null) {
return messagePattern;
}
StringBuilder sb = new StringBuilder(messagePattern.length() + 50);
int k = 0;
for (int i = 0; i < argArray.length; i++) {
int idx = messagePattern.indexOf(DELIM_STR, k);
if (idx == -1) {
// no more variables
if (k == 0) { // this is a simple string
return messagePattern;
} else { // add the tail string which contains no variables and return
// the result.
sb.append(messagePattern, k, messagePattern.length());
return sb.toString();
}
} else {
if (isEscapedDelimeter(messagePattern, idx)) {
if (!isDoubleEscaped(messagePattern, idx)) {
i--; // DELIM_START was escaped, thus should not be incremented
sb.append(messagePattern, k, idx - 1);
sb.append(DELIM_START);
k = idx + 1;
} else {
// The escape character preceding the delimiter start is
// itself escaped: "abc x:\\{}"
// we have to consume one backward slash
sb.append(messagePattern, k, idx - 1);
deeplyAppendParameter(sb, argArray[i], new HashMap<>());
k = idx + 2;
}
} else {
sb.append(messagePattern, k, idx);
deeplyAppendParameter(sb, argArray[i], new HashMap<>());
k = idx + 2;
}
}
}
// append the characters following the last {} pair.
sb.append(messagePattern, k, messagePattern.length());
return sb.toString();
}
private static boolean isEscapedDelimeter(String messagePattern, int delimeterStartIndex) {
if (delimeterStartIndex == 0) {
return false;
}
char potentialEscape = messagePattern.charAt(delimeterStartIndex - 1);
return potentialEscape == ESCAPE_CHAR;
}
private static boolean isDoubleEscaped(String messagePattern, int delimeterStartIndex) {
return delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR;
}
// special treatment of array values was suggested by 'lizongbo'
private static void deeplyAppendParameter(StringBuilder sbuf, Object o, Map<Object[], Object> seenMap) {
if (o == null) {
sbuf.append("null");
return;
}
if (!o.getClass().isArray()) {
safeObjectAppend(sbuf, o);
} else {
// check for primitive array types because they
// unfortunately cannot be cast to Object[]
if (o instanceof boolean[]) {
booleanArrayAppend(sbuf, (boolean[]) o);
} else if (o instanceof byte[]) {
byteArrayAppend(sbuf, (byte[]) o);
} else if (o instanceof char[]) {
charArrayAppend(sbuf, (char[]) o);
} else if (o instanceof short[]) {
shortArrayAppend(sbuf, (short[]) o);
} else if (o instanceof int[]) {
intArrayAppend(sbuf, (int[]) o);
} else if (o instanceof long[]) {
longArrayAppend(sbuf, (long[]) o);
} else if (o instanceof float[]) {
floatArrayAppend(sbuf, (float[]) o);
} else if (o instanceof double[]) {
doubleArrayAppend(sbuf, (double[]) o);
} else {
objectArrayAppend(sbuf, (Object[]) o, seenMap);
}
}
}
private static void safeObjectAppend(StringBuilder sbuf, Object o) {
try {
String oAsString = o.toString();
sbuf.append(oAsString);
} catch (Throwable t) {
throw new RuntimeException("Failed toString() invocation on an object of type [" + o.getClass().getName() + "]", t);
}
}
@SuppressWarnings("DuplicatedCode")
private static void booleanArrayAppend(StringBuilder sbuf, boolean[] a) {
sbuf.append('[');
int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
@SuppressWarnings("DuplicatedCode")
private static void byteArrayAppend(StringBuilder sbuf, byte[] a) {
sbuf.append('[');
int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
@SuppressWarnings("DuplicatedCode")
private static void charArrayAppend(StringBuilder sbuf, char[] a) {
sbuf.append('[');
int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
@SuppressWarnings("DuplicatedCode")
private static void shortArrayAppend(StringBuilder sbuf, short[] a) {
sbuf.append('[');
int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
@SuppressWarnings("DuplicatedCode")
private static void intArrayAppend(StringBuilder sbuf, int[] a) {
sbuf.append('[');
int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
@SuppressWarnings("DuplicatedCode")
private static void longArrayAppend(StringBuilder sbuf, long[] a) {
sbuf.append('[');
int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
@SuppressWarnings("DuplicatedCode")
private static void floatArrayAppend(StringBuilder sbuf, float[] a) {
sbuf.append('[');
int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
@SuppressWarnings("DuplicatedCode")
private static void doubleArrayAppend(StringBuilder sbuf, double[] a) {
sbuf.append('[');
int len = a.length;
for (int i = 0; i < len; i++) {
sbuf.append(a[i]);
if (i != len - 1) {
sbuf.append(", ");
}
}
sbuf.append(']');
}
private static void objectArrayAppend(StringBuilder sbuf, Object[] a, Map<Object[], Object> seenMap) {
sbuf.append('[');
if (!seenMap.containsKey(a)) {
seenMap.put(a, null);
int len = a.length;
for (int i = 0; i < len; i++) {
deeplyAppendParameter(sbuf, a[i], seenMap);
if (i != len - 1) {
sbuf.append(", ");
}
}
// allow repeats in siblings
seenMap.remove(a);
} else {
sbuf.append("...");
}
sbuf.append(']');
}
}

View File

@@ -0,0 +1,54 @@
package ghast.logger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class BukkitLoggerTest {
Logger logger;
BukkitLogger bukkitLogger;
@BeforeEach
void before() {
logger = mock(Logger.class);
bukkitLogger = new BukkitLogger(logger);
}
@Test
void debug() {
bukkitLogger.debug("Some String");
verify(logger).log(Level.CONFIG, "Some String");
Exception exception = new Exception("oops!");
bukkitLogger.debug("Some String", exception);
verify(logger).log(Level.CONFIG, "Some String", exception);
}
@Test
void info() {
bukkitLogger.info("some message");
verify(logger).log(Level.INFO, "some message");
}
@Test
void warn() {
bukkitLogger.warn("some message");
verify(logger).log(Level.WARNING, "some message");
}
@Test
void error() {
bukkitLogger.error("some message");
verify(logger).log(Level.SEVERE, "some message");
Exception exception = new Exception("oops!");
bukkitLogger.error("Some String", exception);
verify(logger).log(Level.SEVERE, "Some String", exception);
}
}

View File

@@ -0,0 +1,50 @@
package ghast.logger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class LoggerAdapterTest {
LoggerAdapter loggerAdapter;
@BeforeEach
void before() {
loggerAdapter = mock(LoggerAdapter.class, CALLS_REAL_METHODS);
}
@Test
void debug() {
loggerAdapter.debug("some pattern {}", "item-1");
verify(loggerAdapter).debug("some pattern item-1");
Exception exception = new Exception("oops!");
loggerAdapter.debug("some pattern {}", "item-1", exception);
verify(loggerAdapter).debug("some pattern item-1", exception);
}
@Test
void info() {
loggerAdapter.info("some pattern {}", "item-1");
verify(loggerAdapter).info("some pattern item-1");
}
@Test
void warn() {
loggerAdapter.warn("some pattern {}", "item-1");
verify(loggerAdapter).warn("some pattern item-1");
}
@Test
void error() {
loggerAdapter.error("some pattern {}", "item-1");
verify(loggerAdapter).error("some pattern item-1");
Exception exception = new Exception("oops!");
loggerAdapter.error("some pattern {}", "item-1", exception);
verify(loggerAdapter).error("some pattern item-1", exception);
}
}

View File

@@ -0,0 +1,84 @@
package ghast.logger;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class LoggerFormatterTest {
@Test
void arrayFormatNullPattern() {
Exception exception = new Exception("oops!");
FormattingPair formattingPair = LoggerFormatter.arrayFormat(null, null, exception);
assertNotNull(formattingPair);
assertNull(formattingPair.getMessage());
assertNotNull(formattingPair.getThrowable());
assertEquals(exception, formattingPair.getThrowable());
formattingPair = LoggerFormatter.arrayFormat(null, null, null);
assertNotNull(formattingPair);
assertNull(formattingPair.getMessage());
assertNull(formattingPair.getThrowable());
}
@Test
void arrayFormatNullArgs() {
FormattingPair formattingPair = LoggerFormatter.arrayFormat("some pattern", null, null);
assertNotNull(formattingPair);
assertNotNull(formattingPair.getMessage());
assertEquals("some pattern", formattingPair.getMessage());
assertNull(formattingPair.getThrowable());
formattingPair = LoggerFormatter.arrayFormat("some pattern {}", null, null);
assertNotNull(formattingPair);
assertNotNull(formattingPair.getMessage());
assertEquals("some pattern {}", formattingPair.getMessage());
assertNull(formattingPair.getThrowable());
}
@Test
void arrayFormat() {
Exception exception = new Exception("oops!");
FormattingPair formattingPair = LoggerFormatter.arrayFormat("some pattern {}", new Object[]{"item-1"}, exception);
assertNotNull(formattingPair);
assertNotNull(formattingPair.getMessage());
assertEquals("some pattern item-1", formattingPair.getMessage());
assertNotNull(formattingPair.getThrowable());
assertEquals(exception, formattingPair.getThrowable());
}
@Test
void arrayFormatWithoutThrowable() {
FormattingPair formattingPair = LoggerFormatter.arrayFormat("Arg1: {}", new Object[]{ "item-1" });
assertNotNull(formattingPair);
assertNotNull(formattingPair.getMessage());
assertEquals("Arg1: item-1", formattingPair.getMessage());
assertNull(formattingPair.getThrowable());
}
@Test
void arrayFormatWithoutThrowableNullArgs() {
FormattingPair formattingPair = LoggerFormatter.arrayFormat("Arg1: {}", null);
assertNotNull(formattingPair);
assertNotNull(formattingPair.getMessage());
assertEquals("Arg1: {}", formattingPair.getMessage());
assertNull(formattingPair.getThrowable());
}
@Test
void arrayFormatThrowableInArgs() {
Exception exception = new Exception("oops!");
FormattingPair formattingPair = LoggerFormatter.arrayFormat("Arg1: {}", new Object[]{ "item-1", exception });
assertNotNull(formattingPair);
assertNotNull(formattingPair.getMessage());
assertEquals("Arg1: item-1", formattingPair.getMessage());
assertNotNull(formattingPair.getThrowable());
assertEquals(exception, formattingPair.getThrowable());
}
}

View File

@@ -0,0 +1,95 @@
package ghast.logger;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class StringFormatterTest {
@Test
void emptyPattern() {
String actual = StringFormatter.arrayFormat(null, null);
assertEquals("", actual);
actual = StringFormatter.arrayFormat("", null);
assertEquals("", actual);
}
@Test
void nullArgArray() {
String pattern = "some pattern";
String actual = StringFormatter.arrayFormat(pattern, null);
assertEquals(pattern, actual);
pattern = "some pattern {}";
actual = StringFormatter.arrayFormat(pattern, null);
assertEquals(pattern, actual);
}
@Test
void dummyPattern() {
String actual = StringFormatter.arrayFormat("dummy pattern", new Object[]{"argument"});
assertEquals("dummy pattern", actual);
}
@Test
void escapePattern() {
String actual = StringFormatter.arrayFormat("Arg1: \\{}", new Object[]{"item1"});
assertEquals("Arg1: {}", actual);
actual = StringFormatter.arrayFormat("Arg1: {}, \\{}", new Object[]{"item1"});
assertEquals("Arg1: item1, \\{}", actual);
}
@Test
void simpleArg() {
String actual;
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{"item1"});
assertEquals("Arg1: item1", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{11});
assertEquals("Arg1: 11", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{11.5f});
assertEquals("Arg1: 11.5", actual);
}
@Test
void nullArg() {
String actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{null});
assertEquals("Arg1: null", actual);
}
@Test
void arrayArg() {
String actual;
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{new boolean[]{false, true}});
assertEquals("Arg1: [false, true]", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{new byte[]{0b00, 0b01}});
assertEquals("Arg1: [0, 1]", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{new char[]{'c', 'h'}});
assertEquals("Arg1: [c, h]", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{new short[]{11, 12}});
assertEquals("Arg1: [11, 12]", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{new int[]{11, 12}});
assertEquals("Arg1: [11, 12]", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{new long[]{11L, 12L}});
assertEquals("Arg1: [11, 12]", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{new float[]{11.2f, 12.3f}});
assertEquals("Arg1: [11.2, 12.3]", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{new double[]{11.2d, 12.3d}});
assertEquals("Arg1: [11.2, 12.3]", actual);
actual = StringFormatter.arrayFormat("Arg1: {}", new Object[]{new String[]{"str-arr-1", "str-arr-2"}});
assertEquals("Arg1: [str-arr-1, str-arr-2]", actual);
}
}