add pmd, add subproject logging-ext, add missing @Override

This commit is contained in:
Jörg Prante 2024-07-07 20:44:37 +02:00
parent b2ec110f85
commit 3bcfc1366c
137 changed files with 1790 additions and 1101 deletions

View file

@ -1,5 +1,6 @@
plugins {
id 'pmd'
id 'maven-publish'
id 'signing'
id "io.github.gradle-nexus.publish-plugin" version "2.0.0-rc-1"
@ -30,6 +31,7 @@ subprojects {
apply from: rootProject.file('gradle/compile/java.gradle')
apply from: rootProject.file('gradle/test/junit5.gradle')
apply from: rootProject.file('gradle/publish/maven.gradle')
apply from: rootProject.file('gradle/quality/pmd.gradle')
}
apply from: rootProject.file('gradle/publish/sonatype.gradle')
apply from: rootProject.file('gradle/publish/forgejo.gradle')

View file

@ -12,6 +12,6 @@ tasks.withType(Pmd) {
pmd {
ignoreFailures = true
consoleOutput = false
toolVersion = "6.51.0"
toolVersion = "7.3.0"
ruleSetFiles = rootProject.files('gradle/quality/pmd/category/java/bestpractices.xml')
}

File diff suppressed because it is too large Load diff

View file

@ -1,6 +1,7 @@
dependencies {
api project(':logging')
api libs.log4j.core
testImplementation project(':logging-ext')
}
def moduleName = 'org.xbib.logging.log4j.test'

View file

@ -1,8 +1,8 @@
module org.xbib.logging.log4j.test {
requires transitive java.logging;
requires transitive org.xbib.logging.ext;
requires org.apache.logging.log4j;
requires org.junit.jupiter.api;
requires transitive org.xbib.logging;
requires org.xbib.logging.adapter.log4j;
exports org.xbib.logging.log4j.test to org.junit.platform.commons;
opens org.xbib.logging.log4j.test to org.junit.platform.commons;
}

View file

@ -5,7 +5,7 @@ import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.xbib.logging.MDC;
import org.xbib.logging.NDC;
import org.xbib.logging.formatters.PatternFormatter;
import org.xbib.logging.ext.formatters.PatternFormatter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

View file

@ -23,6 +23,7 @@ import org.slf4j.Marker;
import org.slf4j.helpers.BasicMarkerFactory;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
@ -58,7 +59,7 @@ public class LoggerTest {
@Test
public void testLogger() {
final Logger logger = LoggerFactory.getLogger(LoggerTest.class);
assertTrue(logger instanceof Slf4jLogger, expectedTypeMessage(Slf4jLogger.class, logger.getClass()));
assertInstanceOf(Slf4jLogger.class, logger, expectedTypeMessage(Slf4jLogger.class, logger.getClass()));
// Ensure the logger logs something
final String testMsg = "This is a test message";

22
logging-ext/build.gradle Normal file
View file

@ -0,0 +1,22 @@
dependencies {
api project(':logging')
}
test {
systemProperty 'java.util.logging.manager', 'org.xbib.logging.LogManager'
systemProperty 'javax.net.ssl.keyStore', 'src/test/resources/org/xbib/logging/ext/test/server-keystore.jks'
systemProperty 'javax.net.ssl.keyStorePassword', 'testpassword'
systemProperty 'javax.net.ssl.trustStore', 'src/test/resources/org/xbib/logging/ext/test/client-keystore.jks'
systemProperty 'javax.net.ssl.trustStorePassword', 'testpassword'
}
def moduleName = 'org.xbib.logging.ext.test'
def patchArgs = ['--patch-module', "$moduleName=" + files(sourceSets.test.resources.srcDirs).asPath ]
tasks.named('compileTestJava') {
options.compilerArgs += patchArgs
}
tasks.named('test') {
jvmArgs += patchArgs
}

View file

@ -0,0 +1,10 @@
module org.xbib.logging.ext {
requires transitive org.xbib.logging;
requires transitive java.xml;
exports org.xbib.logging.ext;
exports org.xbib.logging.ext.formatters;
exports org.xbib.logging.ext.handlers;
exports org.xbib.logging.ext.io;
exports org.xbib.logging.ext.net;
exports org.xbib.logging.ext.util;
}

View file

@ -1,8 +1,10 @@
package org.xbib.logging;
package org.xbib.logging.ext;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextSelector;
import org.xbib.logging.util.CopyOnWriteMap;
import org.xbib.logging.util.StackWalkerUtil;

View file

@ -1,9 +1,11 @@
package org.xbib.logging;
package org.xbib.logging.ext;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextSelector;
import org.xbib.logging.util.CopyOnWriteMap;
import org.xbib.logging.util.StackWalkerUtil;
@ -84,6 +86,7 @@ public final class ClassLoaderLogContextSelector implements LogContextSelector {
* {@inheritDoc} This instance will consult the call stack to see if any calling classloader is associated
* with any log context.
*/
@Override
public LogContext getLogContext() {
final LogContext result = StackWalkerUtil.logContextFinder(logApiClassLoaders, logContextFinder);
if (result != null) {

View file

@ -1,6 +1,8 @@
package org.xbib.logging;
package org.xbib.logging.ext;
import java.util.concurrent.ConcurrentMap;
import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextSelector;
import org.xbib.logging.util.CopyOnWriteMap;
import static java.lang.Thread.currentThread;
@ -28,6 +30,7 @@ public final class ContextClassLoaderLogContextSelector implements LogContextSel
private final ConcurrentMap<ClassLoader, LogContext> contextMap = new CopyOnWriteMap<>();
@Override
public LogContext getLogContext() {
ClassLoader cl = currentThread().getContextClassLoader();
if (cl != null) {

View file

@ -1,4 +1,7 @@
package org.xbib.logging;
package org.xbib.logging.ext;
import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextSelector;
/**
* A log context selector which stores the chosen log context in a thread-local.

View file

@ -1,10 +1,13 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.formatters;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level;
import org.xbib.logging.handlers.ConsoleHandler;
import org.xbib.logging.ext.util.formatter.ColorPrintf;
import org.xbib.logging.ext.util.formatter.ColorUtil;
import org.xbib.logging.ext.util.formatter.Printf;
import static java.lang.Math.abs;
/**
@ -25,7 +28,7 @@ public class ColorPatternFormatter extends PatternFormatter {
public ColorPatternFormatter(int darken) {
this.darken = darken;
printf = new ColorPrintf(darken);
this.printf = new ColorPrintf(darken);
}
public ColorPatternFormatter(int darken, final String pattern) {
@ -42,58 +45,32 @@ public class ColorPatternFormatter extends PatternFormatter {
}
private FormatStep colorize(final FormatStep step) {
switch (step.getItemType()) {
case LEVEL:
return new LevelColorStep(step, darken);
case SOURCE_CLASS_NAME:
return new ColorStep(step, 0xff, 0xff, 0x44, darken);
case DATE:
return new ColorStep(step, 0xc0, 0xc0, 0xc0, darken);
case SOURCE_FILE_NAME:
return new ColorStep(step, 0xff, 0xff, 0x44, darken);
case HOST_NAME:
return new ColorStep(step, 0x44, 0xff, 0x44, darken);
case SOURCE_LINE_NUMBER:
return new ColorStep(step, 0xff, 0xff, 0x44, darken);
case LINE_SEPARATOR:
return step;
case CATEGORY:
return new ColorStep(step, 0x44, 0x88, 0xff, darken);
case MDC:
return new ColorStep(step, 0x44, 0xff, 0xaa, darken);
case MESSAGE:
return new ColorStep(step, 0xff, 0xff, 0xff, darken);
case EXCEPTION_TRACE:
return new ColorStep(step, 0xff, 0x44, 0x44, darken);
case SOURCE_METHOD_NAME:
return new ColorStep(step, 0xff, 0xff, 0x44, darken);
case SOURCE_MODULE_NAME:
return new ColorStep(step, 0x88, 0xff, 0x44, darken);
case SOURCE_MODULE_VERSION:
return new ColorStep(step, 0x44, 0xff, 0x44, darken);
case NDC:
return new ColorStep(step, 0x44, 0xff, 0xaa, darken);
case PROCESS_ID:
return new ColorStep(step, 0xdd, 0xbb, 0x77, darken);
case PROCESS_NAME:
return new ColorStep(step, 0xdd, 0xdd, 0x77, darken);
case RELATIVE_TIME:
return new ColorStep(step, 0xc0, 0xc0, 0xc0, darken);
case RESOURCE_KEY:
return new ColorStep(step, 0x44, 0xff, 0x44, darken);
case SYSTEM_PROPERTY:
return new ColorStep(step, 0x88, 0x88, 0x00, darken);
case TEXT:
return new ColorStep(step, 0xd0, 0xd0, 0xd0, darken);
case THREAD_ID:
return new ColorStep(step, 0x44, 0xaa, 0x44, darken);
case THREAD_NAME:
return new ColorStep(step, 0x44, 0xaa, 0x44, darken);
case COMPOUND:
case GENERIC:
default:
return new ColorStep(step, 0xb0, 0xd0, 0xb0, darken);
}
return switch (step.getItemType()) {
case LEVEL -> new LevelColorStep(step, darken);
case SOURCE_CLASS_NAME -> new ColorStep(step, 0xff, 0xff, 0x44, darken);
case DATE -> new ColorStep(step, 0xc0, 0xc0, 0xc0, darken);
case SOURCE_FILE_NAME -> new ColorStep(step, 0xff, 0xff, 0x44, darken);
case HOST_NAME -> new ColorStep(step, 0x44, 0xff, 0x44, darken);
case SOURCE_LINE_NUMBER -> new ColorStep(step, 0xff, 0xff, 0x44, darken);
case LINE_SEPARATOR -> step;
case CATEGORY -> new ColorStep(step, 0x44, 0x88, 0xff, darken);
case MDC -> new ColorStep(step, 0x44, 0xff, 0xaa, darken);
case MESSAGE -> new ColorStep(step, 0xff, 0xff, 0xff, darken);
case EXCEPTION_TRACE -> new ColorStep(step, 0xff, 0x44, 0x44, darken);
case SOURCE_METHOD_NAME -> new ColorStep(step, 0xff, 0xff, 0x44, darken);
case SOURCE_MODULE_NAME -> new ColorStep(step, 0x88, 0xff, 0x44, darken);
case SOURCE_MODULE_VERSION -> new ColorStep(step, 0x44, 0xff, 0x44, darken);
case NDC -> new ColorStep(step, 0x44, 0xff, 0xaa, darken);
case PROCESS_ID -> new ColorStep(step, 0xdd, 0xbb, 0x77, darken);
case PROCESS_NAME -> new ColorStep(step, 0xdd, 0xdd, 0x77, darken);
case RELATIVE_TIME -> new ColorStep(step, 0xc0, 0xc0, 0xc0, darken);
case RESOURCE_KEY -> new ColorStep(step, 0x44, 0xff, 0x44, darken);
case SYSTEM_PROPERTY -> new ColorStep(step, 0x88, 0x88, 0x00, darken);
case TEXT -> new ColorStep(step, 0xd0, 0xd0, 0xd0, darken);
case THREAD_ID -> new ColorStep(step, 0x44, 0xaa, 0x44, darken);
case THREAD_NAME -> new ColorStep(step, 0x44, 0xaa, 0x44, darken);
default -> new ColorStep(step, 0xb0, 0xd0, 0xb0, darken);
};
}
private String colorizePlain(final String str) {

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.formatters;
import java.util.logging.Formatter;
import org.xbib.logging.ExtLogRecord;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.formatters;
import java.io.PrintWriter;
import java.time.Duration;
@ -18,6 +18,8 @@ import java.util.logging.LogRecord;
import java.util.regex.Pattern;
import org.xbib.logging.ExtFormatter;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.ext.util.formatter.ColorMap;
import org.xbib.logging.ext.io.StringBuilderWriter;
import org.xbib.logging.util.StackTraceFormatter;
import static java.lang.Math.max;
import static java.lang.Math.min;
@ -62,14 +64,17 @@ public final class Formatters {
*/
public static FormatStep textFormatStep(final String string) {
return new FormatStep() {
@Override
public void render(final StringBuilder builder, final ExtLogRecord record) {
builder.append(string);
}
@Override
public int estimateLength() {
return string.length();
}
@Override
public ItemType getItemType() {
return ItemType.TEXT;
}
@ -173,10 +178,12 @@ public final class Formatters {
this.maximumWidth = maximumWidth == 0 ? Integer.MAX_VALUE : maximumWidth;
}
@Override
public void render(final StringBuilder builder, final ExtLogRecord record) {
render(null, builder, record);
}
@Override
public void render(Formatter formatter, StringBuilder builder, ExtLogRecord record) {
final int minimumWidth = this.minimumWidth;
final int maximumWidth = this.maximumWidth;
@ -222,6 +229,7 @@ public final class Formatters {
}
}
@Override
public int estimateLength() {
final int maximumWidth = this.maximumWidth;
final int minimumWidth = this.minimumWidth;
@ -253,6 +261,7 @@ public final class Formatters {
this.precision = precision;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
if (precision == null) {
builder.append(applySegments(count, getSegmentedSubject(record)));
@ -296,6 +305,7 @@ public final class Formatters {
return ItemType.CATEGORY;
}
@Override
public String getSegmentedSubject(final ExtLogRecord record) {
return record.getLoggerName();
}
@ -341,6 +351,7 @@ public final class Formatters {
return true;
}
@Override
public ItemType getItemType() {
return ItemType.SOURCE_CLASS_NAME;
}
@ -386,6 +397,7 @@ public final class Formatters {
return true;
}
@Override
public ItemType getItemType() {
return ItemType.SOURCE_MODULE_NAME;
}
@ -415,6 +427,7 @@ public final class Formatters {
return true;
}
@Override
public ItemType getItemType() {
return ItemType.SOURCE_MODULE_VERSION;
}
@ -454,10 +467,12 @@ public final class Formatters {
final DateTimeFormatter dtf = DateTimeFormatter
.ofPattern(formatString == null ? "yyyy-MM-dd HH:mm:ss,SSS" : formatString);
@Override
public ItemType getItemType() {
return ItemType.DATE;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
dtf.formatTo(record.getInstant().atZone(timeZone.toZoneId()), builder);
}
@ -513,6 +528,7 @@ public final class Formatters {
return true;
}
@Override
public ItemType getItemType() {
return ItemType.SOURCE_FILE_NAME;
}
@ -554,10 +570,13 @@ public final class Formatters {
public static FormatStep processIdFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.PROCESS_ID;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(record.getProcessId());
}
@ -578,10 +597,13 @@ public final class Formatters {
final boolean truncateBeginning, final int maximumWidth, final boolean qualified) {
return qualified ? hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null)
: new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) {
@Override
public ItemType getItemType() {
return ItemType.HOST_NAME;
}
@Override
public String getSegmentedSubject(final ExtLogRecord record) {
final String hostName = record.getHostName();
final int idx = hostName.indexOf('.');
@ -604,10 +626,12 @@ public final class Formatters {
public static FormatStep hostnameFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth, final String precision) {
return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) {
@Override
public ItemType getItemType() {
return ItemType.HOST_NAME;
}
@Override
public String getSegmentedSubject(final ExtLogRecord record) {
final String hostName = record.getHostName();
// Check for a specified precision. This is not passed to the constructor because we want truncate
@ -662,6 +686,7 @@ public final class Formatters {
public static FormatStep locationInformationFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
final String fileName = record.getSourceFileName();
final int lineNumber = record.getSourceLineNumber();
@ -717,6 +742,7 @@ public final class Formatters {
return true;
}
@Override
public ItemType getItemType() {
return ItemType.SOURCE_LINE_NUMBER;
}
@ -747,6 +773,7 @@ public final class Formatters {
public static FormatStep messageFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
String formatted;
if (formatter == null
@ -764,6 +791,7 @@ public final class Formatters {
}
// not really correct but doesn't matter for now
@Override
public ItemType getItemType() {
return ItemType.MESSAGE;
}
@ -797,6 +825,7 @@ public final class Formatters {
public static FormatStep simpleMessageFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
String formatted;
if (formatter == null
@ -837,10 +866,12 @@ public final class Formatters {
public static FormatStep simpleMessageFormatStep(final ExtFormatter formatter, final boolean leftJustify,
final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(formatter.formatMessage(record));
}
@Override
public ItemType getItemType() {
return ItemType.MESSAGE;
}
@ -874,11 +905,14 @@ public final class Formatters {
public static FormatStep exceptionFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth, final String argument, final boolean extended) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
// not really correct but doesn't matter for now
@Override
public ItemType getItemType() {
return ItemType.EXCEPTION_TRACE;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
doExceptionFormatStep(builder, record, argument, extended);
}
@ -924,10 +958,12 @@ public final class Formatters {
public static FormatStep resourceKeyFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.RESOURCE_KEY;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
final String key = record.getResourceKey();
if (key != null)
@ -962,6 +998,7 @@ public final class Formatters {
public static FormatStep methodNameFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(record.getSourceMethodName());
}
@ -971,6 +1008,7 @@ public final class Formatters {
return true;
}
@Override
public ItemType getItemType() {
return ItemType.SOURCE_METHOD_NAME;
}
@ -1004,10 +1042,12 @@ public final class Formatters {
public static FormatStep lineSeparatorFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.SOURCE_LINE_NUMBER;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(separatorString);
}
@ -1038,10 +1078,12 @@ public final class Formatters {
public static FormatStep levelFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning,
final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.LEVEL;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
final Level level = record.getLevel();
builder.append(level.getName());
@ -1074,10 +1116,12 @@ public final class Formatters {
public static FormatStep localizedLevelFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.LEVEL;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
final Level level = record.getLevel();
builder.append(level.getResourceBundleName() != null ? level.getLocalizedName() : level.getName());
@ -1112,10 +1156,12 @@ public final class Formatters {
public static FormatStep relativeTimeFormatStep(final long baseTime, final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.RELATIVE_TIME;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(Duration.between(Instant.ofEpochMilli(baseTime), record.getInstant()).toMillis());
}
@ -1154,10 +1200,12 @@ public final class Formatters {
public static FormatStep threadIdFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.THREAD_ID;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(record.getLongThreadID());
}
@ -1188,10 +1236,12 @@ public final class Formatters {
public static FormatStep threadNameFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.THREAD_NAME;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(record.getThreadName());
}
@ -1223,10 +1273,12 @@ public final class Formatters {
public static FormatStep ndcFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning,
final int maximumWidth, final int count) {
return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, count) {
@Override
public ItemType getItemType() {
return ItemType.NDC;
}
@Override
public String getSegmentedSubject(final ExtLogRecord record) {
return record.getNdc();
}
@ -1258,10 +1310,12 @@ public final class Formatters {
public static FormatStep mdcFormatStep(final String key, final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.MDC;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
if (key == null) {
builder.append(new TreeMap<>(record.getMdcCopy()));
@ -1277,6 +1331,8 @@ public final class Formatters {
public static FormatStep formatColor(final ColorMap colors, final String color) {
return new FormatStep() {
@Override
public void render(final StringBuilder builder, final ExtLogRecord record) {
String code = colors.getCode(color, record.getLevel());
if (code != null) {
@ -1284,6 +1340,7 @@ public final class Formatters {
}
}
@Override
public int estimateLength() {
return 7;
}
@ -1309,10 +1366,13 @@ public final class Formatters {
throw new IllegalArgumentException("System property requires a key for the lookup");
}
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() {
return ItemType.SYSTEM_PROPERTY;
}
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
// Check for a default value
final String[] parts = argument.split("(?<!\\\\):");
@ -1337,18 +1397,18 @@ public final class Formatters {
len.append(c);
} else if (c == '.') {
pos++;
final int i = (len.length() > 0 ? Integer.parseInt(len.toString()) : 0);
segments.put(pos, new Segment(i, text.length() > 0 ? text.toString() : null));
final int i = (!len.isEmpty() ? Integer.parseInt(len.toString()) : 0);
segments.put(pos, new Segment(i, !text.isEmpty() ? text.toString() : null));
text = new StringBuilder();
len = new StringBuilder();
} else {
text.append(c);
}
}
if (len.length() > 0 || text.length() > 0) {
if (!len.isEmpty() || !text.isEmpty()) {
pos++;
final int i = (len.length() > 0 ? Integer.parseInt(len.toString()) : 0);
segments.put(pos, new Segment(i, text.length() > 0 ? text.toString() : null));
final int i = (!len.isEmpty() ? Integer.parseInt(len.toString()) : 0);
segments.put(pos, new Segment(i, !text.isEmpty() ? text.toString() : null));
}
return Collections.unmodifiableMap(segments);
}
@ -1359,7 +1419,7 @@ public final class Formatters {
StringBuilder cat = new StringBuilder();
for (char c : category.toCharArray()) {
if (c == '.') {
if (cat.length() > 0) {
if (!cat.isEmpty()) {
categorySegments.add(cat.toString());
cat = new StringBuilder();
} else {
@ -1369,7 +1429,7 @@ public final class Formatters {
cat.append(c);
}
}
if (cat.length() > 0) {
if (!cat.isEmpty()) {
categorySegments.add(cat.toString());
}
return categorySegments;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.formatters;
import org.xbib.logging.ExtFormatter;
import org.xbib.logging.ExtLogRecord;

View file

@ -1,4 +1,7 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.formatters;
import org.xbib.logging.ext.util.formatter.ColorMap;
import org.xbib.logging.ext.util.formatter.FormatStringParser;
/**
* A formatter which uses a text pattern to format messages.

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.formatters;
import java.io.Writer;
import java.time.ZoneId;
@ -9,6 +9,7 @@ import java.util.IdentityHashMap;
import java.util.Map;
import org.xbib.logging.ExtFormatter;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.ext.io.StringBuilderWriter;
import org.xbib.logging.util.PropertyValues;
import org.xbib.logging.util.StackTraceFormatter;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.formatters;
import java.io.IOException;
import java.io.InputStream;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.formatters;
import java.io.Writer;
import java.util.Map;
@ -6,6 +6,7 @@ import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.ext.io.IndentingXmlWriter;
import org.xbib.logging.util.PropertyValues;
/**

View file

@ -1,4 +1,4 @@
package org.xbib.logging.handlers;
package org.xbib.logging.ext.handlers;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
@ -23,8 +23,8 @@ public class AsyncHandler extends ExtHandler {
@SuppressWarnings("unused")
private volatile int state;
private static final AtomicIntegerFieldUpdater<AsyncHandler> stateUpdater = AtomicIntegerFieldUpdater
.newUpdater(AsyncHandler.class, "state");
private static final AtomicIntegerFieldUpdater<AsyncHandler> stateUpdater =
AtomicIntegerFieldUpdater.newUpdater(AsyncHandler.class, "state");
private static final int DEFAULT_QUEUE_LENGTH = 512;
@ -35,7 +35,7 @@ public class AsyncHandler extends ExtHandler {
* @param threadFactory the thread factory to use to construct the handler thread
*/
public AsyncHandler(final int queueLength, final ThreadFactory threadFactory) {
recordQueue = new ArrayBlockingQueue<ExtLogRecord>(queueLength);
recordQueue = new ArrayBlockingQueue<>(queueLength);
thread = threadFactory.newThread(new AsyncTask());
if (thread == null) {
throw new IllegalArgumentException("Thread factory did not create a thread");
@ -160,7 +160,7 @@ public class AsyncHandler extends ExtHandler {
boolean intr = false;
try {
for (; ; ) {
ExtLogRecord rec = null;
ExtLogRecord rec;
try {
if (state == 2) {
rec = recordQueue.poll();

View file

@ -1,4 +1,4 @@
package org.xbib.logging.handlers;
package org.xbib.logging.ext.handlers;
import java.util.ArrayDeque;
import java.util.Arrays;
@ -14,7 +14,7 @@ import java.util.logging.Level;
import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.LogContext;
import org.xbib.logging.formatters.PatternFormatter;
import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.util.StandardOutputStreams;
/**
@ -148,7 +148,7 @@ public class DelayedHandler extends ExtHandler {
* @param record the record
*/
private void enqueueOrdered(Deque<ExtLogRecord> q, ExtLogRecord record) {
assert lock.isHeldByCurrentThread();
if (lock.isHeldByCurrentThread()) {
ExtLogRecord last = q.peekLast();
if (last != null) {
// check the ordering
@ -166,9 +166,10 @@ public class DelayedHandler extends ExtHandler {
// order is OK
q.addLast(record);
}
}
private Supplier<ExtLogRecord> drain() {
assert lock.isHeldByCurrentThread();
if (lock.isHeldByCurrentThread()) {
if (queues.isEmpty()) {
return () -> null;
}
@ -181,7 +182,7 @@ public class DelayedHandler extends ExtHandler {
for (Deque<ExtLogRecord> value : values) {
current.set(i++, value.removeFirst());
}
return new Supplier<ExtLogRecord>() {
return new Supplier<>() {
@Override
public ExtLogRecord get() {
ExtLogRecord min = null;
@ -212,6 +213,8 @@ public class DelayedHandler extends ExtHandler {
}
};
}
return () -> null;
}
@Override
public final void close() {

View file

@ -1,4 +1,4 @@
package org.xbib.logging.handlers;
package org.xbib.logging.ext.handlers;
import java.io.File;
import java.io.FileNotFoundException;
@ -11,7 +11,8 @@ import java.time.temporal.ChronoUnit;
import java.util.TimeZone;
import java.util.logging.ErrorManager;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.util.SuffixRotator;
import org.xbib.logging.handlers.FileHandler;
import org.xbib.logging.ext.util.SuffixRotator;
/**
* A file handler which rotates the log at a preset time interval. The interval is determined by the content of the

View file

@ -1,4 +1,4 @@
package org.xbib.logging.handlers;
package org.xbib.logging.ext.handlers;
import java.io.File;
import java.io.FileNotFoundException;
@ -6,8 +6,8 @@ import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.ErrorManager;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.io.CountingOutputStream;
import org.xbib.logging.util.SuffixRotator;
import org.xbib.logging.ext.io.CountingOutputStream;
import org.xbib.logging.ext.util.SuffixRotator;
/**
* A file handler which rotates the log at a preset time interval or the size of the log.

View file

@ -1,4 +1,4 @@
package org.xbib.logging.handlers;
package org.xbib.logging.ext.handlers;
import java.util.ArrayDeque;
import java.util.Deque;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.handlers;
package org.xbib.logging.ext.handlers;
import java.io.File;
import java.io.FileNotFoundException;
@ -6,8 +6,9 @@ import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.ErrorManager;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.io.CountingOutputStream;
import org.xbib.logging.util.SuffixRotator;
import org.xbib.logging.handlers.FileHandler;
import org.xbib.logging.ext.io.CountingOutputStream;
import org.xbib.logging.ext.util.SuffixRotator;
public class SizeRotatingFileHandler extends FileHandler {

View file

@ -1,4 +1,4 @@
package org.xbib.logging.handlers;
package org.xbib.logging.ext.handlers;
import java.io.Closeable;
import java.io.Flushable;
@ -15,10 +15,10 @@ import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.io.TcpOutputStream;
import org.xbib.logging.io.UdpOutputStream;
import org.xbib.logging.ext.io.TcpOutputStream;
import org.xbib.logging.ext.io.UdpOutputStream;
import org.xbib.logging.io.UninterruptibleOutputStream;
import org.xbib.logging.net.ClientSocketFactory;
import org.xbib.logging.ext.net.ClientSocketFactory;
/**
* A handler used to communicate over a socket.

View file

@ -1,4 +1,4 @@
package org.xbib.logging.handlers;
package org.xbib.logging.ext.handlers;
import java.io.Closeable;
import java.io.Flushable;
@ -24,10 +24,10 @@ import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.io.TcpOutputStream;
import org.xbib.logging.io.UdpOutputStream;
import org.xbib.logging.net.ClientSocketFactory;
import org.xbib.logging.util.ByteStringBuilder;
import org.xbib.logging.ext.io.TcpOutputStream;
import org.xbib.logging.ext.io.UdpOutputStream;
import org.xbib.logging.ext.net.ClientSocketFactory;
import org.xbib.logging.ext.util.ByteStringBuilder;
import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.HOUR_OF_DAY;
import static java.time.temporal.ChronoField.MILLI_OF_SECOND;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.io;
package org.xbib.logging.ext.io;
import java.io.IOException;
import java.io.OutputStream;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.io;
import java.util.Iterator;
import java.util.NoSuchElementException;
@ -10,7 +10,7 @@ import javax.xml.stream.XMLStreamWriter;
/**
* An XML stream writer which pretty prints the XML.
*/
class IndentingXmlWriter implements XMLStreamWriter, XMLStreamConstants {
public class IndentingXmlWriter implements XMLStreamWriter, XMLStreamConstants {
private static final String SPACES = " ";
@ -19,7 +19,7 @@ class IndentingXmlWriter implements XMLStreamWriter, XMLStreamConstants {
private int state = START_DOCUMENT;
private boolean indentEnd;
IndentingXmlWriter(final XMLStreamWriter delegate) {
public IndentingXmlWriter(final XMLStreamWriter delegate) {
this.delegate = delegate;
index = 0;
indentEnd = false;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.io;
package org.xbib.logging.ext.io;
import java.io.Flushable;
import java.io.IOException;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.io;
import java.io.Writer;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.io;
package org.xbib.logging.ext.io;
import java.io.Closeable;
import java.io.Flushable;
@ -16,7 +16,7 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.SocketFactory;
import org.xbib.logging.net.ClientSocketFactory;
import org.xbib.logging.ext.net.ClientSocketFactory;
/**
* An output stream that writes data to a {@link Socket socket}.

View file

@ -1,4 +1,4 @@
package org.xbib.logging.io;
package org.xbib.logging.ext.io;
import java.io.Flushable;
import java.io.IOException;
@ -8,7 +8,7 @@ import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import org.xbib.logging.net.ClientSocketFactory;
import org.xbib.logging.ext.net.ClientSocketFactory;
/**
* An output stream that writes data to a {@link DatagramSocket DatagramSocket}.

View file

@ -1,4 +1,4 @@
package org.xbib.logging.net;
package org.xbib.logging.ext.net;
import java.io.IOException;
import java.net.DatagramSocket;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.util;
package org.xbib.logging.ext.util;
import java.util.Arrays;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.util;
package org.xbib.logging.ext.util;
import java.io.IOException;
import java.io.InputStream;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
import java.util.Collections;
import java.util.HashMap;
@ -29,16 +29,16 @@ public class ColorMap {
private static final String CLEAR = "\033[0m";
static final boolean SUPPORTS_COLOR;
public static final boolean SUPPORTS_COLOR;
private static final Map<String, String> codes;
private static final Map<String, String> reverseCodes;
private static final Map<String, Integer> levels = new HashMap<String, Integer>();
private static final Map<Integer, String> reverseLevels = new HashMap<Integer, String>();
private static final Map<String, Integer> levels = new HashMap<>();
private static final Map<Integer, String> reverseLevels = new HashMap<>();
private static final NavigableMap<Integer, String> defaultLevelMap = new TreeMap<Integer, String>();
private static final NavigableMap<Integer, String> defaultLevelMap = new TreeMap<>();
static final ColorMap DEFAULT_COLOR_MAP = new ColorMap(defaultLevelMap);
public static final ColorMap DEFAULT_COLOR_MAP = new ColorMap(defaultLevelMap);
private final NavigableMap<Integer, String> levelMap;
@ -90,12 +90,10 @@ public class ColorMap {
static final String BRIGHT_CYAN_NAME = "brightcyan";
static final String BRIGHT_WHITE_NAME = "brightwhite";
static final String CLEAR_NAME = "clear";
public static final String CLEAR_NAME = "clear";
static {
// Turn color on by default for everything but Windows, unless ansicon is used
String os = System.getProperty("os.name");
final boolean dft = os != null && (!os.toLowerCase(Locale.ROOT).contains("win") || System.getenv("ANSICON") != null);
final boolean dft = true;
final String nocolor = System.getProperty("org.xbib.logging.nocolor");
SUPPORTS_COLOR = (nocolor == null ? dft : "false".equalsIgnoreCase(nocolor));
@ -144,7 +142,7 @@ public class ColorMap {
codes.put(BRIGHT_WHITE_NAME, BRIGHT_WHITE);
codes.put(CLEAR_NAME, CLEAR);
reverseCodes = new HashMap<String, String>();
reverseCodes = new HashMap<>();
reverseCodes.put(DARK_BLACK, BLACK_NAME);
reverseCodes.put(DARK_RED, RED_NAME);
reverseCodes.put(DARK_GREEN, GREEN_NAME);
@ -170,27 +168,22 @@ public class ColorMap {
} else {
reverseCodes = codes = Collections.emptyMap();
}
}
static ColorMap create(String expression) {
public static ColorMap create(String expression) {
if (expression == null || expression.length() < 3) {
return DEFAULT_COLOR_MAP;
}
NavigableMap<Integer, String> levelMap = new TreeMap<Integer, String>();
NavigableMap<Integer, String> levelMap = new TreeMap<>();
for (String pair : expression.split(",")) {
String[] parts = pair.split(":");
if (parts.length != 2) {
continue;
}
String color = codes.get(parts[1].toLowerCase(Locale.ROOT));
if (color == null) {
continue;
}
try {
int i = Integer.parseInt(parts[0]);
levelMap.put(i, color);
@ -198,23 +191,19 @@ public class ColorMap {
} catch (NumberFormatException e) {
// eat
}
Integer i = levels.get(parts[0].toLowerCase(Locale.ROOT));
if (i == null) {
continue;
}
levelMap.put(i, color);
}
return new ColorMap(levelMap);
}
String getCode(String name, java.util.logging.Level level) {
public String getCode(String name, java.util.logging.Level level) {
if (name == null || !SUPPORTS_COLOR) {
return null;
}
String lower = name.toLowerCase(Locale.ROOT);
if (lower.equals(LEVEL_NAME)) {
Map.Entry<Integer, String> entry = levelMap.floorEntry(level.intValue());
@ -232,7 +221,7 @@ public class ColorMap {
builder.append(level == null ? num : level).append(":").append(reverseCodes.get(entry.getValue()))
.append(",");
}
if (builder.length() > 0) {
if (!builder.isEmpty()) {
builder.setLength(builder.length() - 1);
}

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
@ -9,11 +9,11 @@ import java.util.Locale;
import java.util.UUID;
import org.xbib.logging.handlers.ConsoleHandler;
class ColorPrintf extends Printf {
public class ColorPrintf extends Printf {
private final int darken;
private final boolean trueColor = ConsoleHandler.isTrueColor();
ColorPrintf(final int darken) {
public ColorPrintf(final int darken) {
super(Locale.getDefault());
this.darken = darken;
}

View file

@ -1,22 +1,19 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
/**
* This is a throwaway temp class.
*/
final class ColorUtil {
public final class ColorUtil {
private ColorUtil() {
}
static StringBuilder startFgColor(StringBuilder target, boolean trueColor, int r, int g, int b) {
public static StringBuilder startFgColor(StringBuilder target, boolean trueColor, int r, int g, int b) {
return startColor(target, 38, trueColor, r, g, b);
}
static StringBuilder startBgColor(StringBuilder target, boolean trueColor, int r, int g, int b) {
public static StringBuilder startBgColor(StringBuilder target, boolean trueColor, int r, int g, int b) {
return startColor(target, 48, trueColor, r, g, b);
}
static StringBuilder startColor(StringBuilder target, int mode, boolean trueColor, int r, int g, int b) {
public static StringBuilder startColor(StringBuilder target, int mode, boolean trueColor, int r, int g, int b) {
if (trueColor) {
return target.appendCodePoint(27).append('[').append(mode).append(';').append(2).append(';').append(clip(r))
.append(';').append(clip(g)).append(';').append(clip(b)).append('m');
@ -34,15 +31,15 @@ final class ColorUtil {
return Math.min(Math.max(0, color), 255);
}
static StringBuilder endFgColor(StringBuilder target) {
public static StringBuilder endFgColor(StringBuilder target) {
return endColor(target, 39);
}
static StringBuilder endBgColor(StringBuilder target) {
public static StringBuilder endBgColor(StringBuilder target) {
return endColor(target, 49);
}
static StringBuilder endColor(StringBuilder target, int mode) {
public static StringBuilder endColor(StringBuilder target, int mode) {
return target.appendCodePoint(27).append('[').append(mode).append('m');
}
}

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
import java.util.AbstractSet;
import java.util.Iterator;

View file

@ -1,9 +1,11 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
import java.util.ArrayList;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.xbib.logging.ext.formatters.Formatters;
import org.xbib.logging.ext.formatters.FormatStep;
/**
* A parser which can translate a log4j-style format string into a series of {@code FormatStep} instances.

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
/**
* General formatting flags.

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
import java.util.concurrent.atomic.AtomicReferenceArray;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
enum NumericFlag {
SIGN,

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
import java.util.concurrent.atomic.AtomicReferenceArray;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.formatters;
package org.xbib.logging.ext.util.formatter;
import java.io.IOException;
import java.math.BigDecimal;
@ -38,7 +38,15 @@ import static java.lang.Math.max;
/**
* A string formatter which can be customized.
*/
class Printf {
public class Printf {
private static final int ST_INITIAL = 0;
private static final int ST_PCT = 1;
private static final int ST_TIME = 2;
private static final int ST_WIDTH = 3;
private static final int ST_DOT = 4;
private static final int ST_PREC = 5;
private static final int ST_DOLLAR = 6;
private static final String someSpaces = " "; //32 spaces
private static final String someZeroes = "00000000000000000000000000000000"; //32 zeros
@ -60,14 +68,6 @@ class Printf {
return locale;
}
private static final int ST_INITIAL = 0;
private static final int ST_PCT = 1;
private static final int ST_TIME = 2;
private static final int ST_WIDTH = 3;
private static final int ST_DOT = 4;
private static final int ST_PREC = 5;
private static final int ST_DOLLAR = 6;
public String format(String format, Object... params) {
return formatDirect(new StringBuilder(), format, params).toString();
}
@ -340,7 +340,7 @@ class Printf {
appendStr(destination, genFlags, width, -1, b.toString());
break;
}
case 'R': {
case 'R', 'T': {
final StringBuilder b = new StringBuilder();
formatTimeField(b, ta, ChronoField.HOUR_OF_DAY, genFlags, -1, 2);
b.append(':');
@ -363,16 +363,6 @@ class Printf {
appendStr(destination, genFlags, width, -1, b.toString());
break;
}
case 'T': {
final StringBuilder b = new StringBuilder();
formatTimeField(b, ta, ChronoField.HOUR_OF_DAY, genFlags, -1, 2);
b.append(':');
formatTimeField(b, ta, ChronoField.MINUTE_OF_HOUR, genFlags, -1, 2);
b.append(':');
formatTimeField(b, ta, ChronoField.SECOND_OF_MINUTE, genFlags, -1, 2);
appendStr(destination, genFlags, width, -1, b.toString());
break;
}
default: {
throw unknownFormat(format, i);
}
@ -482,9 +472,9 @@ class Printf {
appendStr(destination, genFlags, width, precision, "null");
break;
} else if (argVal instanceof Character) {
cpa = ((Character) argVal).charValue();
cpa = (Character) argVal;
} else if (argVal instanceof Integer) {
cpa = ((Integer) argVal).intValue();
cpa = (Integer) argVal;
} else {
throw new IllegalFormatConversionException((char) cp, argVal.getClass());
}
@ -518,7 +508,6 @@ class Printf {
formatFloatingPointDecimal(destination, item, genFlags, numFlags, width, precision);
break;
} else {
assert cp == 'g' || cp == 'G';
formatFloatingPointGeneral(destination, item, genFlags, numFlags, width, precision);
break;
}
@ -832,23 +821,32 @@ class Printf {
}
}
protected void formatFloatingPointGeneral(StringBuilder target, Number item, GeneralFlags genFlags, NumericFlags numFlags,
protected void formatFloatingPointGeneral(StringBuilder target,
Number item,
GeneralFlags genFlags,
NumericFlags numFlags,
int width, int precision) {
if (item == null) {
appendStr(target, genFlags, width, precision, "null");
} else {
boolean sci;
if (item instanceof BigDecimal) {
final BigDecimal mag = ((BigDecimal) item).abs();
switch (item) {
case BigDecimal bigDecimal -> {
final BigDecimal mag = bigDecimal.abs();
sci = mag.compareTo(NEG_TEN_EM4) < 0 || mag.compareTo(BigDecimal.valueOf(10, precision)) >= 0;
} else if (item instanceof Float) {
}
case Float v -> {
final float fv = Math.abs(item.floatValue());
sci = Float.isFinite(fv) && (fv < 10e-4f || fv >= Math.pow(10, precision));
} else {
assert item instanceof Double;
}
case Double v -> {
final double dv = Math.abs(item.doubleValue());
sci = Double.isFinite(dv) && (dv < 10e-4f || dv >= Math.pow(10, precision));
}
default -> {
sci = false;
}
}
if (sci) {
formatFloatingPointSci(target, item, genFlags, numFlags, width, precision);
} else {
@ -902,7 +900,7 @@ class Printf {
target.append(iterator.current());
iterator.next(); // move
}
assert iterator.getAttribute(NumberFormat.Field.INTEGER) != null;
if (iterator.getAttribute(NumberFormat.Field.INTEGER) != null) {
if (zp && width > end) {
appendZeros(target, width - end);
}
@ -915,6 +913,7 @@ class Printf {
appendSpaces(target, width - end);
}
}
}
private static final BigDecimal NEG_ONE = BigDecimal.ONE.negate();
private static final BigDecimal NEG_TEN_EM4 = BigDecimal.valueOf(10, -4);
@ -937,10 +936,11 @@ class Printf {
return 32 - Integer.numberOfLeadingZeros(item.intValue());
} else if (item instanceof Long) {
return 64 - Long.numberOfLeadingZeros(item.longValue());
} else {
assert item instanceof BigInteger;
} else if (item instanceof BigInteger) {
return ((BigInteger) item).bitLength();
}
// impossible
return 0;
}
private static void appendOctal(StringBuilder target, final Number item) {

View file

@ -0,0 +1,10 @@
module org.xbib.logging.ext.test {
requires transitive org.junit.jupiter.api;
requires transitive org.xbib.logging.ext;
exports org.xbib.logging.ext.test;
exports org.xbib.logging.ext.test.formatters;
exports org.xbib.logging.ext.test.handlers;
opens org.xbib.logging.ext.test to org.junit.platform.commons;
opens org.xbib.logging.ext.test.formatters to org.junit.platform.commons;
opens org.xbib.logging.ext.test.handlers to org.junit.platform.commons;
}

View file

@ -1,10 +1,9 @@
package org.xbib.logging.test.handlers;
package org.xbib.logging.ext.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.ErrorManager;
import org.junit.jupiter.api.Assertions;
public class AssertingErrorManager extends ErrorManager {
@ -43,10 +42,13 @@ public class AssertingErrorManager extends ErrorManager {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)) {
pw.printf("LogManager error of type %s: %s%n", codeStr, msg);
if (ex != null) {
ex.printStackTrace(pw);
}
Assertions.fail(sw.toString());
} catch (IOException e) {
// This shouldn't happen, but just fail if it does
e.printStackTrace();
Assertions.fail(String.format("Failed to print error message: %s", e.getMessage()));
}
}

View file

@ -0,0 +1,61 @@
package org.xbib.logging.ext.test;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Supplier;
import org.junit.jupiter.api.Assertions;
public class MapTestUtils {
public MapTestUtils() {
}
/**
* Compares the two maps have the same keys and same values in any order.
*
* @param m1 the first map used to compare the keys and values
* @param m2 the second map used to compare the keys and values
* @param <K> the key type
* @param <V> the value type
*/
@SuppressWarnings("WeakerAccess")
public static <K, V> void compareMaps(final Map<K, V> m1, final Map<K, V> m2) {
Supplier<String> failureMessage = () -> String.format("Keys did not match%n%s%n%s%n", m1.keySet(), m2.keySet());
Assertions.assertTrue(m1.keySet().containsAll(m2.keySet()), failureMessage);
Assertions.assertTrue(m2.keySet().containsAll(m1.keySet()), failureMessage);
// At this point we know that all the keys match
for (Map.Entry<K, V> entry1 : m1.entrySet()) {
final V value2 = m2.get(entry1.getKey());
Assertions.assertEquals(entry1.getValue(), value2,
() -> String.format("Value %s from the first map does not match value %s from the second map with key %s.",
entry1.getValue(), value2, entry1.getKey()));
}
}
/**
* A helper to easily build maps. The resulting map is immutable and the order is predictable with the
* {@link #add(Object, Object)} order.
*/
public static class MapBuilder<K, V> {
private final Map<K, V> result;
private MapBuilder(final Map<K, V> result) {
this.result = result;
}
public static <K, V> MapBuilder<K, V> create() {
return new MapBuilder<>(new LinkedHashMap<K, V>());
}
public MapBuilder<K, V> add(final K key, final V value) {
result.put(key, value);
return this;
}
public Map<K, V> build() {
return Collections.unmodifiableMap(result);
}
}
}

View file

@ -1,8 +1,8 @@
package org.xbib.logging.test.formatters;
package org.xbib.logging.ext.test.formatters;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.ExtLogRecord.FormatStyle;
import org.xbib.logging.test.MapTestUtils;
import org.xbib.logging.ext.test.MapTestUtils;
abstract class AbstractTest extends MapTestUtils {

View file

@ -1,4 +1,4 @@
package org.xbib.logging.test.formatters;
package org.xbib.logging.ext.test.formatters;
import java.io.IOException;
import java.io.InputStream;
@ -7,11 +7,10 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
import java.util.function.Supplier;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.xbib.logging.formatters.PatternFormatter;
import org.xbib.logging.formatters.TextBannerFormatter;
import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.ext.formatters.TextBannerFormatter;
/**
* Tests of the banner formatting capability.
@ -35,7 +34,7 @@ public class BannerFormatterTests {
tbf = new TextBannerFormatter(createResourceSupplier("non-existent-banner.txt", fallbackSupplier), emptyFormatter);
Assertions.assertEquals(FALLBACK_OK, tbf.getHead(null));
tbf = new TextBannerFormatter(createResourceSupplier("test-banner.txt", fallbackSupplier), emptyFormatter);
final InputStream is = getClass().getResourceAsStream("/org/xbib/logging/test/formatters/test-banner.txt");
final InputStream is = getClass().getResourceAsStream("/org/xbib/logging/ext/test/formatters/test-banner.txt");
Assertions.assertNotNull(is);
try (is) {
final String s = new String(is.readAllBytes(), StandardCharsets.UTF_8);

View file

@ -1,15 +1,15 @@
package org.xbib.logging.test.formatters;
package org.xbib.logging.ext.test.formatters;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.MDC;
import org.xbib.logging.NDC;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.xbib.logging.formatters.PatternFormatter;
import org.xbib.logging.ext.formatters.PatternFormatter;
public class PatternFormatterTests {
static final String CATEGORY = "org.xbib.logging.formatters.PatternFormatterTests";
static final String CATEGORY = "org.xbib.logging.ext.test.formatters.PatternFormatterTests";
static {
// Set a system property
@ -20,7 +20,7 @@ public class PatternFormatterTests {
}
@Test
public void categories() throws Exception {
public void categories() {
final ExtLogRecord record = createLogRecord("test");
PatternFormatter formatter = new PatternFormatter("%c");
Assertions.assertEquals(CATEGORY, formatter.format(record));
@ -32,16 +32,16 @@ public class PatternFormatterTests {
Assertions.assertEquals("formatters.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%c{1.}");
Assertions.assertEquals("o.x.l.f.PatternFormatterTests", formatter.format(record));
Assertions.assertEquals("o.x.l.e.t.f.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%c{1.~}");
Assertions.assertEquals("o.~.~.~.PatternFormatterTests", formatter.format(record));
Assertions.assertEquals("o.~.~.~.~.~.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%c{.}");
Assertions.assertEquals("....PatternFormatterTests", formatter.format(record));
Assertions.assertEquals("......PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%c{1~.}");
Assertions.assertEquals("o~.x~.l~.f~.PatternFormatterTests", formatter.format(record));
Assertions.assertEquals("o~.x~.l~.e~.t~.f~.PatternFormatterTests", formatter.format(record));
// Test a simple logger name
record.setLoggerName("test");
@ -56,7 +56,7 @@ public class PatternFormatterTests {
}
@Test
public void classNames() throws Exception {
public void classNames() {
final ExtLogRecord record = createLogRecord("test");
PatternFormatter formatter = new PatternFormatter("%C");
Assertions.assertEquals(PatternFormatterTests.class.getName(), formatter.format(record));
@ -68,16 +68,16 @@ public class PatternFormatterTests {
Assertions.assertEquals("formatters.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%C{1.}");
Assertions.assertEquals("o.x.l.t.f.PatternFormatterTests", formatter.format(record));
Assertions.assertEquals("o.x.l.e.t.f.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%C{1.~}");
Assertions.assertEquals("o.~.~.~.~.PatternFormatterTests", formatter.format(record));
Assertions.assertEquals("o.~.~.~.~.~.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%C{.}");
Assertions.assertEquals(".....PatternFormatterTests", formatter.format(record));
Assertions.assertEquals("......PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%C{1~.}");
Assertions.assertEquals("o~.x~.l~.t~.f~.PatternFormatterTests", formatter.format(record));
Assertions.assertEquals("o~.x~.l~.e~.t~.f~.PatternFormatterTests", formatter.format(record));
}
@Test

View file

@ -1,8 +1,7 @@
package org.xbib.logging.test.formatters;
package org.xbib.logging.ext.test.formatters;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.xbib.logging.util.StackTraceFormatter;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.test.formatters;
package org.xbib.logging.ext.test.formatters;
import java.io.StringReader;
import java.time.ZoneId;
@ -6,7 +6,6 @@ import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
@ -18,16 +17,15 @@ import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xbib.logging.ExtFormatter;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level;
import org.xbib.logging.formatters.StructuredFormatter;
import org.xbib.logging.formatters.StructuredFormatter.Key;
import org.xbib.logging.formatters.XmlFormatter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.xbib.logging.ExtFormatter;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level;
import org.xbib.logging.ext.formatters.StructuredFormatter;
import org.xbib.logging.ext.formatters.StructuredFormatter.Key;
import org.xbib.logging.ext.formatters.XmlFormatter;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.test.handlers;
package org.xbib.logging.ext.test.handlers;
import java.io.BufferedReader;
import java.io.IOException;
@ -19,11 +19,14 @@ import java.util.zip.GZIPInputStream;
import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.formatters.PatternFormatter;
import org.junit.jupiter.api.Assertions;
import org.xbib.logging.ext.formatters.PatternFormatter;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.xbib.logging.ext.test.AssertingErrorManager;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class AbstractHandlerTest {
@ -44,7 +47,7 @@ public class AbstractHandlerTest {
@Test
public void simple() {
Assertions.assertTrue(testInfo.getTestMethod().isPresent());
assertTrue(testInfo.getTestMethod().isPresent());
}
protected Path resolvePath(final String filename) throws IOException {
@ -56,8 +59,8 @@ public class AbstractHandlerTest {
}
protected Path logDirectory(final TestInfo testInfo) throws IOException {
Assertions.assertTrue(testInfo.getTestClass().isPresent());
Assertions.assertTrue(testInfo.getTestMethod().isPresent());
assertTrue(testInfo.getTestClass().isPresent());
assertTrue(testInfo.getTestMethod().isPresent());
final Path dir =
BASE_LOG_DIR.resolve(testInfo.getTestClass().get().getSimpleName() + "-" + testInfo.getTestMethod().get().getName());
if (Files.notExists(dir)) {
@ -124,7 +127,7 @@ public class AbstractHandlerTest {
}
}
}
Assertions.fail(String.format("GZIP file %s missing contents: %s", path, expectedContains));
fail(String.format("GZIP file %s missing contents: %s", path, expectedContains));
}
/**
@ -142,11 +145,11 @@ public class AbstractHandlerTest {
try (final FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" + path.toUri().toASCIIString()),
Collections.singletonMap("create", "true"))) {
final Path file = zipFs.getPath(zipFs.getSeparator(), expectedFileName);
Assertions.assertTrue(Files.exists(file), () -> String.format("Expected file %s not found.", expectedFileName));
assertTrue(Files.exists(file), () -> String.format("Expected file %s not found.", expectedFileName));
final List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8);
Assertions.assertFalse(lines.isEmpty(),
assertFalse(lines.isEmpty(),
() -> String.format("File %s appears to be empty in zip file %s.", expectedFileName, path));
Assertions.assertTrue(lines.get(0).contains(expectedContains),
assertTrue(lines.getFirst().contains(expectedContains),
() -> String.format("ZIP file %s missing contents: %s", path, expectedContains));
}
}
@ -163,18 +166,17 @@ public class AbstractHandlerTest {
lines1 = readAllLinesFromGzip(archive1);
lines2 = readAllLinesFromGzip(archive2);
} else {
Assertions.fail(String.format("Files %s and %s are not archives.", archive1, archive2));
fail(String.format("Files %s and %s are not archives.", archive1, archive2));
}
// Assert the contents aren't empty
Assertions.assertFalse(lines1.isEmpty(), () -> String.format("Archive %s contained no data", archive1));
Assertions.assertFalse(lines2.isEmpty(), () -> String.format("Archive %s contained no data", archive2));
assertFalse(lines1.isEmpty(), () -> String.format("Archive %s contained no data", archive1));
assertFalse(lines2.isEmpty(), () -> String.format("Archive %s contained no data", archive2));
final Collection<String> copy1 = new ArrayList<>(lines1);
final Collection<String> copy2 = new ArrayList<>(lines2);
boolean altered = copy1.removeAll(copy2);
if (copy1.isEmpty()) {
Assertions.fail(String.format("The contents of %s and %s are identical and should not be", archive1, archive2));
fail(String.format("The contents of %s and %s are identical and should not be", archive1, archive2));
} else if (altered) {
final StringBuilder msg = new StringBuilder(1024)
.append("The following contents are in both ")
@ -187,7 +189,7 @@ public class AbstractHandlerTest {
msg.append(System.lineSeparator()).append(line);
}
}
Assertions.fail(msg.toString());
fail(msg.toString());
}
}
@ -195,7 +197,7 @@ public class AbstractHandlerTest {
try (final FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" + path.toUri().toASCIIString()),
Collections.singletonMap("create", "true"))) {
final Path file = zipFs.getPath(zipFs.getSeparator(), expectedFileName);
Assertions.assertTrue(Files.exists(file), () -> String.format("Expected file %s not found.", expectedFileName));
assertTrue(Files.exists(file), () -> String.format("Expected file %s not found.", expectedFileName));
return Files.readAllLines(file, StandardCharsets.UTF_8);
}
}

View file

@ -1,4 +1,4 @@
package org.xbib.logging.test.handlers;
package org.xbib.logging.ext.test.handlers;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
@ -9,13 +9,14 @@ import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level;
import org.xbib.logging.MDC;
import org.xbib.logging.NDC;
import org.xbib.logging.formatters.PatternFormatter;
import org.xbib.logging.handlers.AsyncHandler;
import org.xbib.logging.handlers.AsyncHandler.OverflowAction;
import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.ext.handlers.AsyncHandler;
import org.xbib.logging.ext.handlers.AsyncHandler.OverflowAction;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xbib.logging.ext.test.AssertingErrorManager;
public class AsyncHandlerTests {

View file

@ -1,4 +1,4 @@
package org.xbib.logging.test.handlers;
package org.xbib.logging.ext.test.handlers;
import java.util.ArrayList;
import java.util.Collections;
@ -11,8 +11,8 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.xbib.logging.handlers.DelayedHandler;
import org.xbib.logging.test.AssertingErrorManager;
import org.xbib.logging.ext.handlers.DelayedHandler;
import org.xbib.logging.ext.test.AssertingErrorManager;
import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.LogContext;

View file

@ -1,11 +1,11 @@
package org.xbib.logging.test.handlers;
package org.xbib.logging.ext.test.handlers;
import java.util.logging.SimpleFormatter;
import org.xbib.logging.test.AssertingErrorManager;
import org.xbib.logging.ExtHandler;
import org.xbib.logging.formatters.PatternFormatter;
import org.xbib.logging.ext.formatters.PatternFormatter;
import org.junit.jupiter.api.Test;
import org.xbib.logging.ext.test.AssertingErrorManager;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.test.handlers;
package org.xbib.logging.ext.test.handlers;
import java.util.ArrayList;
import java.util.Collection;
@ -8,8 +8,9 @@ import java.util.List;
import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level;
import org.xbib.logging.handlers.QueueHandler;
import org.xbib.logging.ext.handlers.QueueHandler;
import org.junit.jupiter.api.Test;
import org.xbib.logging.ext.test.AssertingErrorManager;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class QueueHandlerTests extends AbstractHandlerTest {

View file

@ -1,4 +1,4 @@
package org.xbib.logging.test.handlers;
package org.xbib.logging.ext.test.handlers;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

View file

@ -1,4 +1,4 @@
package org.xbib.logging.test.handlers;
package org.xbib.logging.ext.test.handlers;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
@ -12,11 +12,15 @@ import javax.net.ssl.SSLContext;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.LogContext;
import org.xbib.logging.Logger;
import org.xbib.logging.formatters.PatternFormatter;
import org.xbib.logging.handlers.SocketHandler;
import org.xbib.logging.handlers.SocketHandler.Protocol;
import org.junit.jupiter.api.Assertions;
import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.ext.handlers.SocketHandler;
import org.xbib.logging.ext.handlers.SocketHandler.Protocol;
import org.junit.jupiter.api.Test;
import org.xbib.logging.ext.test.AssertingErrorManager;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
public class SocketHandlerTests extends AbstractHandlerTest {
@ -33,8 +37,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
final ExtLogRecord record = createLogRecord("Test TCP handler");
handler.publish(record);
final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test TCP handler", msg);
assertNotNull(msg);
assertEquals("Test TCP handler", msg);
}
}
@ -45,8 +49,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
final ExtLogRecord record = createLogRecord("Test TLS handler");
handler.publish(record);
final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test TLS handler", msg);
assertNotNull(msg);
assertEquals("Test TLS handler", msg);
}
}
@ -57,8 +61,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
final ExtLogRecord record = createLogRecord("Test UDP handler");
handler.publish(record);
final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test UDP handler", msg);
assertNotNull(msg);
assertEquals("Test UDP handler", msg);
}
}
@ -73,20 +77,20 @@ public class SocketHandlerTests extends AbstractHandlerTest {
ExtLogRecord record = createLogRecord("Test TCP handler " + port);
handler.publish(record);
String msg = server1.timeoutPoll();
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test TCP handler " + port, msg);
assertNotNull(msg);
assertEquals("Test TCP handler " + port, msg);
// Change the port on the handler which should close the first connection and open a new one
handler.setPort(altPort);
record = createLogRecord("Test TCP handler " + altPort);
handler.publish(record);
msg = server2.timeoutPoll();
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test TCP handler " + altPort, msg);
assertNotNull(msg);
assertEquals("Test TCP handler " + altPort, msg);
// There should be nothing on server1, we won't know if the real connection is closed but we shouldn't
// have any data remaining on the first server
Assertions.assertNull(server1.peek(), "Expected no data on server1");
assertNull(server1.peek(), "Expected no data on server1");
}
}
@ -99,8 +103,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
final ExtLogRecord record = createLogRecord("Test TCP handler");
handler.publish(record);
final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test TCP handler", msg);
assertNotNull(msg);
assertEquals("Test TCP handler", msg);
}
// wait until the OS really release used port
Thread.sleep(50);
@ -112,8 +116,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
final ExtLogRecord record = createLogRecord("Test TLS handler");
handler.publish(record);
final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test TLS handler", msg);
assertNotNull(msg);
assertEquals("Test TLS handler", msg);
}
} finally {
if (handler != null) {
@ -128,15 +132,14 @@ public class SocketHandlerTests extends AbstractHandlerTest {
try {
// Publish a record to a running server
try (
SimpleServer server = SimpleServer.createTcpServer()) {
try (SimpleServer server = SimpleServer.createTcpServer()) {
handler = createHandler(Protocol.TCP, server.getPort());
handler.setErrorManager(AssertingErrorManager.of(ErrorManager.FLUSH_FAILURE));
final ExtLogRecord record = createLogRecord("Test TCP handler");
handler.publish(record);
final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test TCP handler", msg);
assertNotNull(msg);
assertEquals("Test TCP handler", msg);
}
// wait until the OS really release used port
Thread.sleep(50);
@ -158,8 +161,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
throw new RuntimeException(e);
}
}, 10);
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test TCP handler", msg);
assertNotNull(msg);
assertEquals("Test TCP handler", msg);
}
} finally {
if (handler != null) {
@ -188,8 +191,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
rootLogger.addHandler(socketHandler);
rootLogger.info("Test TCP handler " + port + " 1");
String msg = server.timeoutPoll();
Assertions.assertNotNull(msg);
Assertions.assertEquals("Test TCP handler " + port + " 1", msg);
assertNotNull(msg);
assertEquals("Test TCP handler " + port + " 1", msg);
}
}
@ -217,7 +220,7 @@ public class SocketHandlerTests extends AbstractHandlerTest {
TimeUnit.MILLISECONDS.sleep(sleep);
t -= sleep;
}
Assertions.assertFalse((t <= 0), () -> String.format("Failed to get value in %d seconds.", timeout));
assertFalse((t <= 0), () -> String.format("Failed to get value in %d seconds.", timeout));
return value;
}
}

View file

@ -1,4 +1,4 @@
package org.xbib.logging.test.handlers;
package org.xbib.logging.ext.test.handlers;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
@ -10,13 +10,14 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.formatters.PatternFormatter;
import org.xbib.logging.handlers.SyslogHandler;
import org.xbib.logging.handlers.SyslogHandler.SyslogType;
import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.ext.handlers.SyslogHandler;
import org.xbib.logging.ext.handlers.SyslogHandler.SyslogType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xbib.logging.ext.test.AssertingErrorManager;
public class SyslogHandlerTests {

View file

@ -12,8 +12,10 @@ import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@Disabled
public class SystemLoggerIT {
private Path stdout;

View file

@ -1,3 +1,8 @@
import org.xbib.logging.LogContextConfiguratorFactory;
import org.xbib.logging.LogManager;
import org.xbib.logging.LoggerFinder;
import org.xbib.logging.configuration.DefaultLogContextConfiguratorFactory;
module org.xbib.logging {
uses org.xbib.logging.LogContextInitializer;
uses org.xbib.logging.LogContextConfiguratorFactory;
@ -5,13 +10,15 @@ module org.xbib.logging {
uses org.xbib.logging.NDCProvider;
uses org.xbib.logging.MDCProvider;
requires transitive java.logging;
requires java.xml;
requires java.management;
exports org.xbib.logging;
exports org.xbib.logging.configuration;
exports org.xbib.logging.filters;
exports org.xbib.logging.formatters;
exports org.xbib.logging.handlers;
exports org.xbib.logging.net;
exports org.xbib.logging.io;
exports org.xbib.logging.util;
provides java.lang.System.LoggerFinder with LoggerFinder;
provides java.util.logging.LogManager with LogManager;
provides LogContextConfiguratorFactory with DefaultLogContextConfiguratorFactory;
}

View file

@ -28,6 +28,7 @@ public abstract class ExtErrorManager extends ErrorManager {
};
}
@Override
public void error(final String msg, final Exception ex, final int code) {
super.error(msg, ex, code);
}

View file

@ -37,6 +37,7 @@ public abstract class ExtFormatter extends Formatter {
/**
* {@inheritDoc}
*/
@Override
public final String format(final LogRecord record) {
return format(ExtLogRecord.wrap(record));
}
@ -173,22 +174,27 @@ public abstract class ExtFormatter extends Formatter {
this.delegate = Objects.requireNonNull(delegate, "delegate");
}
@Override
public String format(final ExtLogRecord record) {
return delegate.format(record);
}
@Override
public String formatMessage(final LogRecord record) {
return delegate.formatMessage(record);
}
@Override
public boolean isCallerCalculationRequired() {
return delegate.isCallerCalculationRequired();
}
@Override
public String getHead(final Handler h) {
return delegate.getHead(h);
}
@Override
public String getTail(final Handler h) {
return delegate.getTail(h);
}

View file

@ -15,6 +15,7 @@ import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.xbib.logging.errormanager.OnlyOnceErrorManager;
import org.xbib.logging.util.AtomicArray;
import org.xbib.logging.util.StandardOutputStreams;
/**
* An extended logger handler. Use this class as a base class for log handlers which require {@code ExtLogRecord}
@ -63,6 +64,7 @@ public abstract class ExtHandler extends Handler implements AutoCloseable, Flush
/**
* {@inheritDoc}
*/
@Override
public void publish(final LogRecord record) {
if (enabled && record != null && isLoggable(record)) {
doPublish(ExtLogRecord.wrap(record));
@ -480,9 +482,7 @@ public abstract class ExtHandler extends Handler implements AutoCloseable, Flush
try {
errorManager.error(msg, ex, code);
} catch (Exception ex2) {
// use the same message as the JDK
System.err.println("Handler.reportError caught:");
ex2.printStackTrace();
StandardOutputStreams.printError(ex2, "Handler.reportError caught: " + ex2.getMessage());
}
}
}

View file

@ -349,6 +349,7 @@ public class ExtLogRecord extends LogRecord {
/**
* {@inheritDoc}
*/
@Override
public String getSourceClassName() {
calculateCaller();
return super.getSourceClassName();
@ -357,6 +358,7 @@ public class ExtLogRecord extends LogRecord {
/**
* {@inheritDoc}
*/
@Override
public void setSourceClassName(final String sourceClassName) {
calculateCaller = false;
super.setSourceClassName(sourceClassName);
@ -365,6 +367,7 @@ public class ExtLogRecord extends LogRecord {
/**
* {@inheritDoc}
*/
@Override
public String getSourceMethodName() {
calculateCaller();
return super.getSourceMethodName();
@ -373,6 +376,7 @@ public class ExtLogRecord extends LogRecord {
/**
* {@inheritDoc}
*/
@Override
public void setSourceMethodName(final String sourceMethodName) {
calculateCaller = false;
super.setSourceMethodName(sourceMethodName);
@ -428,8 +432,9 @@ public class ExtLogRecord extends LogRecord {
public String getFormattedMessage() {
final ResourceBundle bundle = getResourceBundle();
String msg = getMessage();
if (msg == null)
if (msg == null) {
return null;
}
if (bundle != null) {
try {
msg = bundle.getString(msg);
@ -540,6 +545,7 @@ public class ExtLogRecord extends LogRecord {
*
* @param message the new raw message
*/
@Override
public void setMessage(final String message) {
setMessage(message, FormatStyle.MESSAGE_FORMAT);
}
@ -561,6 +567,7 @@ public class ExtLogRecord extends LogRecord {
*
* @param parameters the log message parameters. (may be null)
*/
@Override
public void setParameters(final Object[] parameters) {
super.setParameters(parameters);
}
@ -570,6 +577,7 @@ public class ExtLogRecord extends LogRecord {
*
* @param bundle localization bundle (may be null)
*/
@Override
public void setResourceBundle(final ResourceBundle bundle) {
super.setResourceBundle(bundle);
}
@ -579,6 +587,7 @@ public class ExtLogRecord extends LogRecord {
*
* @param name localization bundle name (may be null)
*/
@Override
public void setResourceBundleName(final String name) {
super.setResourceBundleName(name);
}

View file

@ -22,7 +22,6 @@ import org.xbib.logging.ref.References;
import org.xbib.logging.util.CopyOnWriteMap;
import org.xbib.logging.util.CopyOnWriteWeakMap;
/**
* A logging context, for producing isolated logging environments.
*/
@ -62,6 +61,7 @@ public final class LogContext implements AutoCloseable {
* before the class init is complete.
*/
private static final class LazyHolder {
private static final HashMap<String, Reference<Level, Void>> INITIAL_LEVEL_MAP;
private LazyHolder() {
@ -392,11 +392,7 @@ public final class LogContext implements AutoCloseable {
/**
* The default log context selector, which always returns the system log context.
*/
public static final LogContextSelector DEFAULT_LOG_CONTEXT_SELECTOR = new LogContextSelector() {
public LogContext getLogContext() {
return SYSTEM_CONTEXT;
}
};
public static final LogContextSelector DEFAULT_LOG_CONTEXT_SELECTOR = () -> SYSTEM_CONTEXT;
private static volatile LogContextSelector logContextSelector = DEFAULT_LOG_CONTEXT_SELECTOR;
@ -548,10 +544,11 @@ public final class LogContext implements AutoCloseable {
}
private void recursivelyClose(final LoggerNode loggerNode) {
assert treeLock.isHeldByCurrentThread();
if (treeLock.isHeldByCurrentThread()) {
for (LoggerNode child : loggerNode.getChildren()) {
recursivelyClose(child);
}
loggerNode.close();
}
}
}

View file

@ -76,11 +76,10 @@ public final class Logger extends java.util.logging.Logger {
this.loggerNode = loggerNode;
}
// Filter mgmt
/**
* {@inheritDoc}
*/
@Override
public void setFilter(Filter filter) {
loggerNode.setFilter(filter);
}
@ -88,17 +87,17 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public Filter getFilter() {
return loggerNode.getFilter();
}
// Level mgmt
/**
* {@inheritDoc} This implementation grabs a lock, so that only one thread may update the log level of any
* logger at a time, in order to allow readers to never block (though there is a window where retrieving the
* log level reflects an older effective level than the actual level).
*/
@Override
public void setLevel(Level newLevel) {
// We have to propagate our level to an internal data structure in the superclass
super.setLevel(newLevel);
@ -127,6 +126,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public Level getLevel() {
return loggerNode.getLevel();
}
@ -134,6 +134,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public boolean isLoggable(Level level) {
return loggerNode.isLoggableLevel(level.intValue());
}
@ -193,11 +194,10 @@ public final class Logger extends java.util.logging.Logger {
return loggerNode.detach(key);
}
// Handler mgmt
/**
* {@inheritDoc}
*/
@Override
public void addHandler(Handler handler) {
if (handler == null) {
throw new NullPointerException("handler is null");
@ -208,6 +208,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void removeHandler(Handler handler) {
if (handler == null) {
return;
@ -218,6 +219,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public Handler[] getHandlers() {
final Handler[] handlers = loggerNode.getHandlers();
return handlers.length > 0 ? handlers.clone() : handlers;
@ -290,6 +292,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void setUseParentHandlers(boolean useParentHandlers) {
loggerNode.setUseParentHandlers(useParentHandlers);
}
@ -297,6 +300,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public boolean getUseParentHandlers() {
return loggerNode.getUseParentHandlers();
}
@ -322,11 +326,10 @@ public final class Logger extends java.util.logging.Logger {
return loggerNode.getUseParentFilters();
}
// Parent/child
/**
* {@inheritDoc}
*/
@Override
public Logger getParent() {
final LoggerNode parentNode = loggerNode.getParent();
return parentNode == null ? null : parentNode.createLogger();
@ -335,6 +338,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* <b>Not allowed.</b> This method may never be called.
*/
@Override
public void setParent(java.util.logging.Logger parent) {
throw new UnsupportedOperationException();
}
@ -363,6 +367,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void log(LogRecord record) {
if (!loggerNode.isLoggableLevel(record.getLevel().intValue())) {
return;
@ -373,6 +378,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void entering(final String sourceClass, final String sourceMethod) {
if (!loggerNode.isLoggableLevel(FINER_INT)) {
return;
@ -386,6 +392,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void entering(final String sourceClass, final String sourceMethod, final Object param1) {
if (!loggerNode.isLoggableLevel(FINER_INT)) {
return;
@ -400,6 +407,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void entering(final String sourceClass, final String sourceMethod, final Object[] params) {
if (!loggerNode.isLoggableLevel(FINER_INT)) {
return;
@ -420,6 +428,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void exiting(final String sourceClass, final String sourceMethod) {
if (!loggerNode.isLoggableLevel(FINER_INT)) {
return;
@ -433,6 +442,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void exiting(final String sourceClass, final String sourceMethod, final Object result) {
if (!loggerNode.isLoggableLevel(FINER_INT)) {
return;
@ -447,6 +457,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void throwing(final String sourceClass, final String sourceMethod, final Throwable thrown) {
if (!loggerNode.isLoggableLevel(FINER_INT)) {
return;
@ -461,6 +472,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void severe(final String msg) {
if (!loggerNode.isLoggableLevel(SEVERE_INT)) {
return;
@ -481,6 +493,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void warning(final String msg) {
if (!loggerNode.isLoggableLevel(WARNING_INT)) {
return;
@ -501,6 +514,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void info(final String msg) {
if (!loggerNode.isLoggableLevel(INFO_INT)) {
return;
@ -521,6 +535,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void config(final String msg) {
if (!loggerNode.isLoggableLevel(CONFIG_INT)) {
return;
@ -541,6 +556,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void fine(final String msg) {
if (!loggerNode.isLoggableLevel(FINE_INT)) {
return;
@ -561,6 +577,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void finer(final String msg) {
if (!loggerNode.isLoggableLevel(FINER_INT)) {
return;
@ -581,6 +598,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void finest(final String msg) {
if (!loggerNode.isLoggableLevel(FINEST_INT)) {
return;
@ -601,6 +619,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void log(final Level level, final String msg) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
return;
@ -621,6 +640,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void log(final Level level, final String msg, final Object param1) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
return;
@ -633,6 +653,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void log(final Level level, final String msg, final Object[] params) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
return;
@ -646,6 +667,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void log(final Level level, final String msg, final Throwable thrown) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
return;
@ -668,6 +690,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
return;
@ -693,6 +716,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg,
final Object param1) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
@ -708,6 +732,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg,
final Object[] params) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
@ -724,6 +749,7 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Override
public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg,
final Throwable thrown) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
@ -752,7 +778,8 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Deprecated(since = "3.0", forRemoval = true)
@Deprecated(since = "0.0.1", forRemoval = true)
@Override
public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName,
final String msg) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
@ -765,7 +792,8 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Deprecated(since = "3.0", forRemoval = true)
@Deprecated(since = "0.0.1", forRemoval = true)
@Override
public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName,
final String msg, final Object param1) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
@ -778,7 +806,8 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Deprecated(since = "3.0", forRemoval = true)
@Deprecated(since = "0.0.1", forRemoval = true)
@Override
public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName,
final String msg, final Object[] params) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
@ -791,7 +820,8 @@ public final class Logger extends java.util.logging.Logger {
/**
* {@inheritDoc}
*/
@Deprecated(since = "3.0", forRemoval = true)
@Deprecated(since = "0.0.1", forRemoval = true)
@Override
public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName,
final String msg, final Throwable thrown) {
if (!loggerNode.isLoggableLevel(level.intValue())) {
@ -981,6 +1011,7 @@ public final class Logger extends java.util.logging.Logger {
}
}
@Override
public String toString() {
return "Logger '" + getName() + "' in context " + loggerNode.getContext();
}

View file

@ -72,32 +72,38 @@ public class LoggerFinder extends System.LoggerFinder {
return delegate.isLoggable(LEVELS.getOrDefault(level, java.util.logging.Level.INFO));
}
@Override
public void log(final Level level, final String msg) {
log(level, null, msg, (Object[]) null);
}
@Override
public void log(final Level level, final Supplier<String> msgSupplier) {
if (isLoggable(level)) {
log(level, null, msgSupplier.get(), (Object[]) null);
}
}
@Override
public void log(final Level level, final Object obj) {
if (isLoggable(level)) {
this.log(level, null, obj.toString(), (Object[]) null);
}
}
@Override
public void log(final Level level, final String msg, final Throwable thrown) {
this.log(level, null, msg, thrown);
}
@Override
public void log(final Level level, final Supplier<String> msgSupplier, final Throwable thrown) {
if (isLoggable(level)) {
this.log(level, null, msgSupplier.get(), thrown);
}
}
@Override
public void log(final Level level, final String format, final Object... params) {
this.log(level, null, format, params);
}

View file

@ -4,6 +4,7 @@ import java.util.Iterator;
import java.util.Map;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import org.xbib.logging.util.StandardOutputStreams;
/**
* Mapped diagnostic context. This is a thread-local map used to hold loggable information.
@ -32,8 +33,7 @@ public final class MDC {
}
return iterator.next();
} catch (ServiceConfigurationError | RuntimeException e) {
System.err.print("Warning: failed to load MDC Provider: ");
e.printStackTrace(System.err);
StandardOutputStreams.printError(e, "Warning: failed to load MDC Provider: " + e.getMessage());
}
}

View file

@ -3,6 +3,7 @@ package org.xbib.logging;
import java.util.Iterator;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import org.xbib.logging.util.StandardOutputStreams;
/**
* Nested diagnostic context. This is basically a thread-local stack that holds a string which can be included
@ -32,8 +33,7 @@ public final class NDC {
}
return iterator.next();
} catch (ServiceConfigurationError | RuntimeException e) {
System.err.print("Warning: failed to load NDC Provider: ");
e.printStackTrace(System.err);
StandardOutputStreams.printError(e, "Warning: failed to load NDC Provider: " + e.getMessage());
}
}

View file

@ -4,6 +4,7 @@ import java.util.Map;
import org.xbib.logging.util.FastCopyHashMap;
final class ThreadLocalMDC implements MDCProvider {
private static final Holder mdc = new Holder();
@Override

View file

@ -3,6 +3,7 @@ package org.xbib.logging;
import java.util.Arrays;
final class ThreadLocalNDC implements NDCProvider {
private static final Holder ndc = new Holder();
@Override
@ -56,6 +57,8 @@ final class ThreadLocalNDC implements NDCProvider {
}
private static final class Holder extends ThreadLocal<Stack<String>> {
@Override
protected Stack<String> initialValue() {
return new Stack<>();
}
@ -107,6 +110,7 @@ final class ThreadLocalNDC implements NDCProvider {
return n < sp ? (T) data[n] : null;
}
@Override
public String toString() {
final StringBuilder b = new StringBuilder();
final int sp = this.sp;

View file

@ -19,10 +19,12 @@ class WrappedExtLogRecord extends ExtLogRecord {
this.logRecord = logRecord;
}
@Override
public String getLoggerName() {
return logRecord.getLoggerName();
}
@Override
public void setLoggerName(final String name) {
super.setLoggerName(name);
logRecord.setLoggerName(name);
@ -126,11 +128,13 @@ class WrappedExtLogRecord extends ExtLogRecord {
return super.getSourceLineNumber();
}
@Override
public void setSourceLineNumber(final int sourceLineNumber) {
resolved = true;
super.setSourceLineNumber(sourceLineNumber);
}
@Override
public String getSourceFileName() {
if (!resolved) {
resolve();
@ -173,12 +177,14 @@ class WrappedExtLogRecord extends ExtLogRecord {
@Deprecated
@SuppressWarnings("deprecation")
@Override
public int getThreadID() {
return logRecord.getThreadID();
}
@Deprecated
@SuppressWarnings("deprecation")
@Override
public void setThreadID(final int threadID) {
super.setThreadID(threadID);
logRecord.setThreadID(threadID);

View file

@ -26,14 +26,20 @@ import org.xbib.logging.Logger;
* wrapped and considered a {@linkplain ConfigurationResource#of(Supplier) lazy resource}.
* </p>
*/
@SuppressWarnings({"UnusedReturnValue", "unused"})
public class ContextConfiguration implements AutoCloseable {
public static final Logger.AttachmentKey<ContextConfiguration> CONTEXT_CONFIGURATION_KEY = new Logger.AttachmentKey<>();
private final LogContext context;
private final Map<String, ConfigurationResource<ErrorManager>> errorManagers;
private final Map<String, ConfigurationResource<Filter>> filters;
private final Map<String, ConfigurationResource<Formatter>> formatters;
private final Map<String, ConfigurationResource<Handler>> handlers;
private final Map<String, ConfigurationResource<Object>> objects;
/**
@ -383,10 +389,10 @@ public class ContextConfiguration implements AutoCloseable {
}
private static void closeResources(final Map<String, ? extends ConfigurationResource<?>> resources) {
final var iter = resources.entrySet().iterator();
while (iter.hasNext()) {
var entry = iter.next();
iter.remove();
final var iterator = resources.entrySet().iterator();
while (iterator.hasNext()) {
var entry = iterator.next();
iterator.remove();
try {
entry.getValue().close();
} catch (Throwable ignore) {
@ -394,5 +400,4 @@ public class ContextConfiguration implements AutoCloseable {
}
}
}
}

View file

@ -18,6 +18,7 @@ import org.xbib.logging.configuration.filters.FilterExpressions;
import org.xbib.logging.expression.Expression;
import org.xbib.logging.filters.AcceptAllFilter;
import org.xbib.logging.filters.DenyAllFilter;
import org.xbib.logging.util.ObjectBuilder;
import org.xbib.logging.util.StandardOutputStreams;
/**

View file

@ -13,7 +13,7 @@ import java.util.logging.Logger;
import org.xbib.logging.Level;
import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextConfigurator;
import org.xbib.logging.formatters.SimpleFormatter;
import org.xbib.logging.formatters.DefaultFormatter;
import org.xbib.logging.handlers.ConsoleHandler;
import org.xbib.logging.util.StandardOutputStreams;
@ -64,7 +64,7 @@ public class PropertyLogContextConfigurator implements LogContextConfigurator {
logContextConfigurator.configure(context, null);
} else {
// Configure a default console handler, thread formatter and associated with the root logger
final ConsoleHandler handler = new ConsoleHandler(new SimpleFormatter());
final ConsoleHandler handler = new ConsoleHandler(new DefaultFormatter());
handler.setLevel(Level.INFO);
handler.setAutoFlush(true);
final Logger rootLogger = context.getLogger("");

View file

@ -7,6 +7,7 @@ import org.xbib.logging.ExtErrorManager;
* An error manager which publishes errors to a handler.
*/
public final class HandlerErrorManager extends ExtErrorManager {
private static final ThreadLocal<Boolean> handlingError = new ThreadLocal<>();
private final Handler handler;
@ -20,6 +21,7 @@ public final class HandlerErrorManager extends ExtErrorManager {
this.handler = handler;
}
@Override
public void error(final String msg, final Exception ex, final int code) {
if (handlingError.get() != Boolean.TRUE) {
handlingError.set(Boolean.TRUE);

View file

@ -29,6 +29,7 @@ public final class OnlyOnceErrorManager extends ExtErrorManager {
/**
* {@inheritDoc}
*/
@Override
public void error(final String msg, final Exception ex, final int code) {
ErrorManager delegate = this.delegate;
if (delegate == null) {

View file

@ -7,6 +7,8 @@ import org.xbib.logging.util.StandardOutputStreams;
* An error manager which simply prints a message the system error stream.
*/
public class SimpleErrorManager extends ExtErrorManager {
@Override
public void error(final String msg, final Exception ex, final int code) {
StandardOutputStreams.printError(ex, "LogManager error of type %s: %s%n", nameForCode(code), msg);
}

View file

@ -14,6 +14,7 @@ final class CompositeNode extends Node {
this.subNodes = subNodes.toArray(NO_NODES);
}
@Override
<E extends Exception> void emit(final ResolveContext<E> context,
final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E {
for (Node subNode : subNodes) {
@ -21,12 +22,14 @@ final class CompositeNode extends Node {
}
}
@Override
void catalog(final HashSet<String> strings) {
for (Node node : subNodes) {
node.catalog(strings);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append('*');

View file

@ -323,9 +323,8 @@ public final class Expression {
// otherwise treat it as a properly terminated expression
start = itr.getNextIdx();
continue;
} else {
} else if (itr.peekNext() == '}') {
// TP 11
assert itr.peekNext() == '}';
itr.next(); // consume
if (general) {
if (!itr.hasNext()) {
@ -357,11 +356,9 @@ public final class Expression {
start = itr.getNextIdx();
continue;
}
//throw Assert.unreachableCode();
}
} else {
} else if (itr.peekNext() == '}') {
// TP 12
assert itr.peekNext() == '}';
itr.next(); // consume
list.add(new ExpressionNode(general, keyNode, Node.NULL));
if (general) {
@ -394,7 +391,6 @@ public final class Expression {
start = itr.getNextIdx();
continue;
}
//throw Assert.unreachableCode();
}
case '$': {
// $$
@ -440,7 +436,6 @@ public final class Expression {
throw invalidExpressionSyntax(itr.getStr(), idx);
}
}
//throw Assert.unreachableCode();
}
case ':': {
// $:
@ -474,7 +469,6 @@ public final class Expression {
throw invalidExpressionSyntax(itr.getStr(), idx);
}
}
//throw Assert.unreachableCode();
}
default: {
// $ followed by anything else
@ -493,10 +487,8 @@ public final class Expression {
// TP 27
throw invalidExpressionSyntax(itr.getStr(), idx);
}
//throw Assert.unreachableCode();
}
}
//throw Assert.unreachableCode();
}
case ':': {
if (endOnColon) {
@ -511,7 +503,6 @@ public final class Expression {
// plain content always
continue;
}
//throw Assert.unreachableCode();
}
case '{': {
if (!flags.contains(Flag.NO_SMART_BRACES)) {
@ -539,7 +530,6 @@ public final class Expression {
// treat as plain content
continue;
}
//throw Assert.unreachableCode();
}
case '\\': {
if (flags.contains(Flag.ESCAPES)) {
@ -617,7 +607,6 @@ public final class Expression {
continue;
}
}
//throw Assert.unreachableCode();
}
final int length = itr.getStr().length();
if (length > start) {

View file

@ -13,6 +13,7 @@ class ExpressionNode extends Node {
this.defaultValue = defaultValue;
}
@Override
<E extends Exception> void emit(final ResolveContext<E> context,
final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E {
ExpressionNode oldCurrent = context.setCurrent(this);
@ -23,6 +24,7 @@ class ExpressionNode extends Node {
}
}
@Override
void catalog(final HashSet<String> strings) {
if (key instanceof LiteralNode) {
strings.add(key.toString());
@ -44,6 +46,7 @@ class ExpressionNode extends Node {
return defaultValue;
}
@Override
public String toString() {
return String.format("Expr<%s:%s>", key, defaultValue);
}

View file

@ -30,14 +30,17 @@ class LiteralNode extends Node {
this(literalValue, 0, literalValue.length());
}
@Override
<E extends Exception> void emit(final ResolveContext<E> context,
final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E {
context.getStringBuilder().append(literalValue, start, end);
}
@Override
void catalog(final HashSet<String> strings) {
}
@Override
public String toString() {
final String toString = this.toString;
return toString != null ? toString : (this.toString = literalValue.substring(start, end));

View file

@ -21,13 +21,17 @@ abstract class Node {
}
static final Node NULL = new Node() {
@Override
<E extends Exception> void emit(final ResolveContext<E> context,
final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E {
}
@Override
void catalog(final HashSet<String> strings) {
}
@Override
public String toString() {
return "<<null>>";
}

View file

@ -9,8 +9,11 @@ package org.xbib.logging.expression;
* @param <E> the exception type that can be thrown by the expansion function
*/
public final class ResolveContext<E extends Exception> {
private final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> function;
private StringBuilder builder;
private ExpressionNode current;
ResolveContext(final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> function, final StringBuilder builder) {
@ -27,8 +30,9 @@ public final class ResolveContext<E extends Exception> {
* @throws E if the recursive expansion threw an exception
*/
public String getKey() throws E {
if (current == null)
if (current == null) {
throw new IllegalStateException();
}
final Node key = current.getKey();
if (key instanceof LiteralNode) {
return key.toString();
@ -49,14 +53,15 @@ public final class ResolveContext<E extends Exception> {
* @throws E if the recursive expansion threw an exception
*/
public void expandDefault(StringBuilder target) throws E {
if (current == null)
if (current == null) {
throw new IllegalStateException();
}
emitToBuilder(target, current.getDefaultValue());
}
private void emitToBuilder(final StringBuilder target, final Node node) throws E {
if (node == Node.NULL) {
} else if (node instanceof LiteralNode) {
if (node != Node.NULL) {
if (node instanceof LiteralNode) {
target.append(node);
} else {
final StringBuilder old = builder;
@ -68,6 +73,7 @@ public final class ResolveContext<E extends Exception> {
}
}
}
}
/**
* Expand the default value to the current target string builder. If the default value contains an expression, it will
@ -89,8 +95,9 @@ public final class ResolveContext<E extends Exception> {
* @throws E if the recursive expansion threw an exception
*/
public String getExpandedDefault() throws E {
if (current == null)
if (current == null) {
throw new IllegalStateException();
}
final Node defaultValue = current.getDefaultValue();
if (defaultValue instanceof LiteralNode) {
return defaultValue.toString();

View file

@ -7,6 +7,7 @@ import java.util.logging.LogRecord;
* An accept-all filter.
*/
public final class AcceptAllFilter implements Filter {
private AcceptAllFilter() {
}
@ -18,6 +19,7 @@ public final class AcceptAllFilter implements Filter {
* @param record ignored
* @return {@code true}
*/
@Override
public boolean isLoggable(final LogRecord record) {
return true;
}

View file

@ -10,6 +10,7 @@ import java.util.logging.LogRecord;
* this instance always returns {@code true}.
*/
public final class AllFilter implements Filter {
private final Filter[] filters;
/**
@ -59,6 +60,7 @@ public final class AllFilter implements Filter {
* @param record the log record
* @return {@code true} if all the constituent filters return {@code true}
*/
@Override
public boolean isLoggable(final LogRecord record) {
for (Filter filter : filters) {
if (!filter.isLoggable(record)) {

View file

@ -10,6 +10,7 @@ import java.util.logging.LogRecord;
* instance always returns {@code false}.
*/
public final class AnyFilter implements Filter {
private final Filter[] filters;
/**
@ -59,6 +60,7 @@ public final class AnyFilter implements Filter {
* @param record the log record
* @return {@code true} if any of the constituent filters return {@code true}
*/
@Override
public boolean isLoggable(final LogRecord record) {
for (Filter filter : filters) {
if (filter.isLoggable(record)) {

View file

@ -7,6 +7,7 @@ import java.util.logging.LogRecord;
* A deny-all filter.
*/
public final class DenyAllFilter implements Filter {
private DenyAllFilter() {
}
@ -18,6 +19,7 @@ public final class DenyAllFilter implements Filter {
* @param record ignored
* @return {@code false}
*/
@Override
public boolean isLoggable(final LogRecord record) {
return false;
}

View file

@ -24,6 +24,7 @@ public final class InvertFilter implements Filter {
* @param record the log record
* @return {@code true} if the target filter returns {@code false}, {@code false} otherwise
*/
@Override
public boolean isLoggable(final LogRecord record) {
return !target.isLoggable(record);
}

View file

@ -27,6 +27,7 @@ public final class LevelChangingFilter implements Filter {
* @param record the record to inspect and possibly update
* @return {@code true} always
*/
@Override
public boolean isLoggable(final LogRecord record) {
record.setLevel(newLevel);
return true;

Some files were not shown because too many files have changed in this diff Show more