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 { plugins {
id 'pmd'
id 'maven-publish' id 'maven-publish'
id 'signing' id 'signing'
id "io.github.gradle-nexus.publish-plugin" version "2.0.0-rc-1" 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/compile/java.gradle')
apply from: rootProject.file('gradle/test/junit5.gradle') apply from: rootProject.file('gradle/test/junit5.gradle')
apply from: rootProject.file('gradle/publish/maven.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/sonatype.gradle')
apply from: rootProject.file('gradle/publish/forgejo.gradle') apply from: rootProject.file('gradle/publish/forgejo.gradle')

View file

@ -12,6 +12,6 @@ tasks.withType(Pmd) {
pmd { pmd {
ignoreFailures = true ignoreFailures = true
consoleOutput = false consoleOutput = false
toolVersion = "6.51.0" toolVersion = "7.3.0"
ruleSetFiles = rootProject.files('gradle/quality/pmd/category/java/bestpractices.xml') 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 { dependencies {
api project(':logging') api project(':logging')
api libs.log4j.core api libs.log4j.core
testImplementation project(':logging-ext')
} }
def moduleName = 'org.xbib.logging.log4j.test' def moduleName = 'org.xbib.logging.log4j.test'

View file

@ -1,8 +1,8 @@
module org.xbib.logging.log4j.test { module org.xbib.logging.log4j.test {
requires transitive java.logging; requires transitive org.xbib.logging.ext;
requires org.apache.logging.log4j; requires org.apache.logging.log4j;
requires org.junit.jupiter.api; requires org.junit.jupiter.api;
requires transitive org.xbib.logging;
requires org.xbib.logging.adapter.log4j; requires org.xbib.logging.adapter.log4j;
exports org.xbib.logging.log4j.test to org.junit.platform.commons; 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.apache.logging.log4j.ThreadContext;
import org.xbib.logging.MDC; import org.xbib.logging.MDC;
import org.xbib.logging.NDC; 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.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;

View file

@ -23,6 +23,7 @@ import org.slf4j.Marker;
import org.slf4j.helpers.BasicMarkerFactory; import org.slf4j.helpers.BasicMarkerFactory;
import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals; 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.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
@ -58,7 +59,7 @@ public class LoggerTest {
@Test @Test
public void testLogger() { public void testLogger() {
final Logger logger = LoggerFactory.getLogger(LoggerTest.class); 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 // Ensure the logger logs something
final String testMsg = "This is a test message"; 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.Collections;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentMap; 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.CopyOnWriteMap;
import org.xbib.logging.util.StackWalkerUtil; 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.Collections;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import java.util.function.Function; 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.CopyOnWriteMap;
import org.xbib.logging.util.StackWalkerUtil; 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 * {@inheritDoc} This instance will consult the call stack to see if any calling classloader is associated
* with any log context. * with any log context.
*/ */
@Override
public LogContext getLogContext() { public LogContext getLogContext() {
final LogContext result = StackWalkerUtil.logContextFinder(logApiClassLoaders, logContextFinder); final LogContext result = StackWalkerUtil.logContextFinder(logApiClassLoaders, logContextFinder);
if (result != null) { if (result != null) {

View file

@ -1,6 +1,8 @@
package org.xbib.logging; package org.xbib.logging.ext;
import java.util.concurrent.ConcurrentMap; 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.CopyOnWriteMap;
import static java.lang.Thread.currentThread; import static java.lang.Thread.currentThread;
@ -28,6 +30,7 @@ public final class ContextClassLoaderLogContextSelector implements LogContextSel
private final ConcurrentMap<ClassLoader, LogContext> contextMap = new CopyOnWriteMap<>(); private final ConcurrentMap<ClassLoader, LogContext> contextMap = new CopyOnWriteMap<>();
@Override
public LogContext getLogContext() { public LogContext getLogContext() {
ClassLoader cl = currentThread().getContextClassLoader(); ClassLoader cl = currentThread().getContextClassLoader();
if (cl != null) { 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. * 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.Formatter;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level; import org.xbib.logging.Level;
import org.xbib.logging.handlers.ConsoleHandler; 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; import static java.lang.Math.abs;
/** /**
@ -25,7 +28,7 @@ public class ColorPatternFormatter extends PatternFormatter {
public ColorPatternFormatter(int darken) { public ColorPatternFormatter(int darken) {
this.darken = darken; this.darken = darken;
printf = new ColorPrintf(darken); this.printf = new ColorPrintf(darken);
} }
public ColorPatternFormatter(int darken, final String pattern) { public ColorPatternFormatter(int darken, final String pattern) {
@ -42,58 +45,32 @@ public class ColorPatternFormatter extends PatternFormatter {
} }
private FormatStep colorize(final FormatStep step) { private FormatStep colorize(final FormatStep step) {
switch (step.getItemType()) { return switch (step.getItemType()) {
case LEVEL: case LEVEL -> new LevelColorStep(step, darken);
return new LevelColorStep(step, darken); case SOURCE_CLASS_NAME -> new ColorStep(step, 0xff, 0xff, 0x44, darken);
case SOURCE_CLASS_NAME: case DATE -> new ColorStep(step, 0xc0, 0xc0, 0xc0, darken);
return new ColorStep(step, 0xff, 0xff, 0x44, darken); case SOURCE_FILE_NAME -> new ColorStep(step, 0xff, 0xff, 0x44, darken);
case DATE: case HOST_NAME -> new ColorStep(step, 0x44, 0xff, 0x44, darken);
return new ColorStep(step, 0xc0, 0xc0, 0xc0, darken); case SOURCE_LINE_NUMBER -> new ColorStep(step, 0xff, 0xff, 0x44, darken);
case SOURCE_FILE_NAME: case LINE_SEPARATOR -> step;
return new ColorStep(step, 0xff, 0xff, 0x44, darken); case CATEGORY -> new ColorStep(step, 0x44, 0x88, 0xff, darken);
case HOST_NAME: case MDC -> new ColorStep(step, 0x44, 0xff, 0xaa, darken);
return new ColorStep(step, 0x44, 0xff, 0x44, darken); case MESSAGE -> new ColorStep(step, 0xff, 0xff, 0xff, darken);
case SOURCE_LINE_NUMBER: case EXCEPTION_TRACE -> new ColorStep(step, 0xff, 0x44, 0x44, darken);
return new ColorStep(step, 0xff, 0xff, 0x44, darken); case SOURCE_METHOD_NAME -> new ColorStep(step, 0xff, 0xff, 0x44, darken);
case LINE_SEPARATOR: case SOURCE_MODULE_NAME -> new ColorStep(step, 0x88, 0xff, 0x44, darken);
return step; case SOURCE_MODULE_VERSION -> new ColorStep(step, 0x44, 0xff, 0x44, darken);
case CATEGORY: case NDC -> new ColorStep(step, 0x44, 0xff, 0xaa, darken);
return new ColorStep(step, 0x44, 0x88, 0xff, darken); case PROCESS_ID -> new ColorStep(step, 0xdd, 0xbb, 0x77, darken);
case MDC: case PROCESS_NAME -> new ColorStep(step, 0xdd, 0xdd, 0x77, darken);
return new ColorStep(step, 0x44, 0xff, 0xaa, darken); case RELATIVE_TIME -> new ColorStep(step, 0xc0, 0xc0, 0xc0, darken);
case MESSAGE: case RESOURCE_KEY -> new ColorStep(step, 0x44, 0xff, 0x44, darken);
return new ColorStep(step, 0xff, 0xff, 0xff, darken); case SYSTEM_PROPERTY -> new ColorStep(step, 0x88, 0x88, 0x00, darken);
case EXCEPTION_TRACE: case TEXT -> new ColorStep(step, 0xd0, 0xd0, 0xd0, darken);
return new ColorStep(step, 0xff, 0x44, 0x44, darken); case THREAD_ID -> new ColorStep(step, 0x44, 0xaa, 0x44, darken);
case SOURCE_METHOD_NAME: case THREAD_NAME -> new ColorStep(step, 0x44, 0xaa, 0x44, darken);
return new ColorStep(step, 0xff, 0xff, 0x44, darken); default -> new ColorStep(step, 0xb0, 0xd0, 0xb0, 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);
}
} }
private String colorizePlain(final String str) { 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 java.util.logging.Formatter;
import org.xbib.logging.ExtLogRecord; 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.io.PrintWriter;
import java.time.Duration; import java.time.Duration;
@ -18,6 +18,8 @@ import java.util.logging.LogRecord;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.xbib.logging.ExtFormatter; import org.xbib.logging.ExtFormatter;
import org.xbib.logging.ExtLogRecord; 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 org.xbib.logging.util.StackTraceFormatter;
import static java.lang.Math.max; import static java.lang.Math.max;
import static java.lang.Math.min; import static java.lang.Math.min;
@ -62,14 +64,17 @@ public final class Formatters {
*/ */
public static FormatStep textFormatStep(final String string) { public static FormatStep textFormatStep(final String string) {
return new FormatStep() { return new FormatStep() {
@Override
public void render(final StringBuilder builder, final ExtLogRecord record) { public void render(final StringBuilder builder, final ExtLogRecord record) {
builder.append(string); builder.append(string);
} }
@Override
public int estimateLength() { public int estimateLength() {
return string.length(); return string.length();
} }
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.TEXT; return ItemType.TEXT;
} }
@ -173,10 +178,12 @@ public final class Formatters {
this.maximumWidth = maximumWidth == 0 ? Integer.MAX_VALUE : maximumWidth; this.maximumWidth = maximumWidth == 0 ? Integer.MAX_VALUE : maximumWidth;
} }
@Override
public void render(final StringBuilder builder, final ExtLogRecord record) { public void render(final StringBuilder builder, final ExtLogRecord record) {
render(null, builder, record); render(null, builder, record);
} }
@Override
public void render(Formatter formatter, StringBuilder builder, ExtLogRecord record) { public void render(Formatter formatter, StringBuilder builder, ExtLogRecord record) {
final int minimumWidth = this.minimumWidth; final int minimumWidth = this.minimumWidth;
final int maximumWidth = this.maximumWidth; final int maximumWidth = this.maximumWidth;
@ -222,6 +229,7 @@ public final class Formatters {
} }
} }
@Override
public int estimateLength() { public int estimateLength() {
final int maximumWidth = this.maximumWidth; final int maximumWidth = this.maximumWidth;
final int minimumWidth = this.minimumWidth; final int minimumWidth = this.minimumWidth;
@ -253,6 +261,7 @@ public final class Formatters {
this.precision = precision; this.precision = precision;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
if (precision == null) { if (precision == null) {
builder.append(applySegments(count, getSegmentedSubject(record))); builder.append(applySegments(count, getSegmentedSubject(record)));
@ -296,6 +305,7 @@ public final class Formatters {
return ItemType.CATEGORY; return ItemType.CATEGORY;
} }
@Override
public String getSegmentedSubject(final ExtLogRecord record) { public String getSegmentedSubject(final ExtLogRecord record) {
return record.getLoggerName(); return record.getLoggerName();
} }
@ -341,6 +351,7 @@ public final class Formatters {
return true; return true;
} }
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.SOURCE_CLASS_NAME; return ItemType.SOURCE_CLASS_NAME;
} }
@ -386,6 +397,7 @@ public final class Formatters {
return true; return true;
} }
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.SOURCE_MODULE_NAME; return ItemType.SOURCE_MODULE_NAME;
} }
@ -415,6 +427,7 @@ public final class Formatters {
return true; return true;
} }
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.SOURCE_MODULE_VERSION; return ItemType.SOURCE_MODULE_VERSION;
} }
@ -454,10 +467,12 @@ public final class Formatters {
final DateTimeFormatter dtf = DateTimeFormatter final DateTimeFormatter dtf = DateTimeFormatter
.ofPattern(formatString == null ? "yyyy-MM-dd HH:mm:ss,SSS" : formatString); .ofPattern(formatString == null ? "yyyy-MM-dd HH:mm:ss,SSS" : formatString);
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.DATE; return ItemType.DATE;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
dtf.formatTo(record.getInstant().atZone(timeZone.toZoneId()), builder); dtf.formatTo(record.getInstant().atZone(timeZone.toZoneId()), builder);
} }
@ -513,6 +528,7 @@ public final class Formatters {
return true; return true;
} }
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.SOURCE_FILE_NAME; return ItemType.SOURCE_FILE_NAME;
} }
@ -554,10 +570,13 @@ public final class Formatters {
public static FormatStep processIdFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep processIdFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.PROCESS_ID; return ItemType.PROCESS_ID;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(record.getProcessId()); builder.append(record.getProcessId());
} }
@ -578,10 +597,13 @@ public final class Formatters {
final boolean truncateBeginning, final int maximumWidth, final boolean qualified) { final boolean truncateBeginning, final int maximumWidth, final boolean qualified) {
return qualified ? hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) return qualified ? hostnameFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null)
: new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) { : new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.HOST_NAME; return ItemType.HOST_NAME;
} }
@Override
public String getSegmentedSubject(final ExtLogRecord record) { public String getSegmentedSubject(final ExtLogRecord record) {
final String hostName = record.getHostName(); final String hostName = record.getHostName();
final int idx = hostName.indexOf('.'); final int idx = hostName.indexOf('.');
@ -604,10 +626,12 @@ public final class Formatters {
public static FormatStep hostnameFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep hostnameFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth, final String precision) { final boolean truncateBeginning, final int maximumWidth, final String precision) {
return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) { return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, null) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.HOST_NAME; return ItemType.HOST_NAME;
} }
@Override
public String getSegmentedSubject(final ExtLogRecord record) { public String getSegmentedSubject(final ExtLogRecord record) {
final String hostName = record.getHostName(); final String hostName = record.getHostName();
// Check for a specified precision. This is not passed to the constructor because we want truncate // 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, public static FormatStep locationInformationFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
final String fileName = record.getSourceFileName(); final String fileName = record.getSourceFileName();
final int lineNumber = record.getSourceLineNumber(); final int lineNumber = record.getSourceLineNumber();
@ -717,6 +742,7 @@ public final class Formatters {
return true; return true;
} }
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.SOURCE_LINE_NUMBER; return ItemType.SOURCE_LINE_NUMBER;
} }
@ -747,6 +773,7 @@ public final class Formatters {
public static FormatStep messageFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep messageFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
String formatted; String formatted;
if (formatter == null if (formatter == null
@ -764,6 +791,7 @@ public final class Formatters {
} }
// not really correct but doesn't matter for now // not really correct but doesn't matter for now
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.MESSAGE; return ItemType.MESSAGE;
} }
@ -797,6 +825,7 @@ public final class Formatters {
public static FormatStep simpleMessageFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep simpleMessageFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
String formatted; String formatted;
if (formatter == null if (formatter == null
@ -837,10 +866,12 @@ public final class Formatters {
public static FormatStep simpleMessageFormatStep(final ExtFormatter formatter, final boolean leftJustify, public static FormatStep simpleMessageFormatStep(final ExtFormatter formatter, final boolean leftJustify,
final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) { final int minimumWidth, final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(formatter.formatMessage(record)); builder.append(formatter.formatMessage(record));
} }
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.MESSAGE; return ItemType.MESSAGE;
} }
@ -874,11 +905,14 @@ public final class Formatters {
public static FormatStep exceptionFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep exceptionFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth, final String argument, final boolean extended) { final boolean truncateBeginning, final int maximumWidth, final String argument, final boolean extended) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
// not really correct but doesn't matter for now // not really correct but doesn't matter for now
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.EXCEPTION_TRACE; return ItemType.EXCEPTION_TRACE;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
doExceptionFormatStep(builder, record, argument, extended); doExceptionFormatStep(builder, record, argument, extended);
} }
@ -924,10 +958,12 @@ public final class Formatters {
public static FormatStep resourceKeyFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep resourceKeyFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.RESOURCE_KEY; return ItemType.RESOURCE_KEY;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
final String key = record.getResourceKey(); final String key = record.getResourceKey();
if (key != null) if (key != null)
@ -962,6 +998,7 @@ public final class Formatters {
public static FormatStep methodNameFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep methodNameFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(record.getSourceMethodName()); builder.append(record.getSourceMethodName());
} }
@ -971,6 +1008,7 @@ public final class Formatters {
return true; return true;
} }
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.SOURCE_METHOD_NAME; return ItemType.SOURCE_METHOD_NAME;
} }
@ -1004,10 +1042,12 @@ public final class Formatters {
public static FormatStep lineSeparatorFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep lineSeparatorFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.SOURCE_LINE_NUMBER; return ItemType.SOURCE_LINE_NUMBER;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(separatorString); builder.append(separatorString);
} }
@ -1038,10 +1078,12 @@ public final class Formatters {
public static FormatStep levelFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning, public static FormatStep levelFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning,
final int maximumWidth) { final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.LEVEL; return ItemType.LEVEL;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
final Level level = record.getLevel(); final Level level = record.getLevel();
builder.append(level.getName()); builder.append(level.getName());
@ -1074,10 +1116,12 @@ public final class Formatters {
public static FormatStep localizedLevelFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep localizedLevelFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.LEVEL; return ItemType.LEVEL;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
final Level level = record.getLevel(); final Level level = record.getLevel();
builder.append(level.getResourceBundleName() != null ? level.getLocalizedName() : level.getName()); 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, public static FormatStep relativeTimeFormatStep(final long baseTime, final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.RELATIVE_TIME; return ItemType.RELATIVE_TIME;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(Duration.between(Instant.ofEpochMilli(baseTime), record.getInstant()).toMillis()); 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, public static FormatStep threadIdFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.THREAD_ID; return ItemType.THREAD_ID;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(record.getLongThreadID()); builder.append(record.getLongThreadID());
} }
@ -1188,10 +1236,12 @@ public final class Formatters {
public static FormatStep threadNameFormatStep(final boolean leftJustify, final int minimumWidth, public static FormatStep threadNameFormatStep(final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.THREAD_NAME; return ItemType.THREAD_NAME;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
builder.append(record.getThreadName()); 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, public static FormatStep ndcFormatStep(final boolean leftJustify, final int minimumWidth, final boolean truncateBeginning,
final int maximumWidth, final int count) { final int maximumWidth, final int count) {
return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, count) { return new SegmentedFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth, count) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.NDC; return ItemType.NDC;
} }
@Override
public String getSegmentedSubject(final ExtLogRecord record) { public String getSegmentedSubject(final ExtLogRecord record) {
return record.getNdc(); return record.getNdc();
} }
@ -1258,10 +1310,12 @@ public final class Formatters {
public static FormatStep mdcFormatStep(final String key, final boolean leftJustify, final int minimumWidth, public static FormatStep mdcFormatStep(final String key, final boolean leftJustify, final int minimumWidth,
final boolean truncateBeginning, final int maximumWidth) { final boolean truncateBeginning, final int maximumWidth) {
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.MDC; return ItemType.MDC;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
if (key == null) { if (key == null) {
builder.append(new TreeMap<>(record.getMdcCopy())); builder.append(new TreeMap<>(record.getMdcCopy()));
@ -1277,6 +1331,8 @@ public final class Formatters {
public static FormatStep formatColor(final ColorMap colors, final String color) { public static FormatStep formatColor(final ColorMap colors, final String color) {
return new FormatStep() { return new FormatStep() {
@Override
public void render(final StringBuilder builder, final ExtLogRecord record) { public void render(final StringBuilder builder, final ExtLogRecord record) {
String code = colors.getCode(color, record.getLevel()); String code = colors.getCode(color, record.getLevel());
if (code != null) { if (code != null) {
@ -1284,6 +1340,7 @@ public final class Formatters {
} }
} }
@Override
public int estimateLength() { public int estimateLength() {
return 7; return 7;
} }
@ -1309,10 +1366,13 @@ public final class Formatters {
throw new IllegalArgumentException("System property requires a key for the lookup"); throw new IllegalArgumentException("System property requires a key for the lookup");
} }
return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) { return new JustifyingFormatStep(leftJustify, minimumWidth, truncateBeginning, maximumWidth) {
@Override
public ItemType getItemType() { public ItemType getItemType() {
return ItemType.SYSTEM_PROPERTY; return ItemType.SYSTEM_PROPERTY;
} }
@Override
public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) { public void renderRaw(Formatter formatter, final StringBuilder builder, final ExtLogRecord record) {
// Check for a default value // Check for a default value
final String[] parts = argument.split("(?<!\\\\):"); final String[] parts = argument.split("(?<!\\\\):");
@ -1337,18 +1397,18 @@ public final class Formatters {
len.append(c); len.append(c);
} else if (c == '.') { } else if (c == '.') {
pos++; pos++;
final int i = (len.length() > 0 ? Integer.parseInt(len.toString()) : 0); final int i = (!len.isEmpty() ? Integer.parseInt(len.toString()) : 0);
segments.put(pos, new Segment(i, text.length() > 0 ? text.toString() : null)); segments.put(pos, new Segment(i, !text.isEmpty() ? text.toString() : null));
text = new StringBuilder(); text = new StringBuilder();
len = new StringBuilder(); len = new StringBuilder();
} else { } else {
text.append(c); text.append(c);
} }
} }
if (len.length() > 0 || text.length() > 0) { if (!len.isEmpty() || !text.isEmpty()) {
pos++; pos++;
final int i = (len.length() > 0 ? Integer.parseInt(len.toString()) : 0); final int i = (!len.isEmpty() ? Integer.parseInt(len.toString()) : 0);
segments.put(pos, new Segment(i, text.length() > 0 ? text.toString() : null)); segments.put(pos, new Segment(i, !text.isEmpty() ? text.toString() : null));
} }
return Collections.unmodifiableMap(segments); return Collections.unmodifiableMap(segments);
} }
@ -1359,7 +1419,7 @@ public final class Formatters {
StringBuilder cat = new StringBuilder(); StringBuilder cat = new StringBuilder();
for (char c : category.toCharArray()) { for (char c : category.toCharArray()) {
if (c == '.') { if (c == '.') {
if (cat.length() > 0) { if (!cat.isEmpty()) {
categorySegments.add(cat.toString()); categorySegments.add(cat.toString());
cat = new StringBuilder(); cat = new StringBuilder();
} else { } else {
@ -1369,7 +1429,7 @@ public final class Formatters {
cat.append(c); cat.append(c);
} }
} }
if (cat.length() > 0) { if (!cat.isEmpty()) {
categorySegments.add(cat.toString()); categorySegments.add(cat.toString());
} }
return categorySegments; 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.ExtFormatter;
import org.xbib.logging.ExtLogRecord; 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. * 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.io.Writer;
import java.time.ZoneId; import java.time.ZoneId;
@ -9,6 +9,7 @@ import java.util.IdentityHashMap;
import java.util.Map; import java.util.Map;
import org.xbib.logging.ExtFormatter; import org.xbib.logging.ExtFormatter;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.ext.io.StringBuilderWriter;
import org.xbib.logging.util.PropertyValues; import org.xbib.logging.util.PropertyValues;
import org.xbib.logging.util.StackTraceFormatter; 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.IOException;
import java.io.InputStream; 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.io.Writer;
import java.util.Map; import java.util.Map;
@ -6,6 +6,7 @@ import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter; import javax.xml.stream.XMLStreamWriter;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.ext.io.IndentingXmlWriter;
import org.xbib.logging.util.PropertyValues; 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.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
@ -23,8 +23,8 @@ public class AsyncHandler extends ExtHandler {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private volatile int state; private volatile int state;
private static final AtomicIntegerFieldUpdater<AsyncHandler> stateUpdater = AtomicIntegerFieldUpdater private static final AtomicIntegerFieldUpdater<AsyncHandler> stateUpdater =
.newUpdater(AsyncHandler.class, "state"); AtomicIntegerFieldUpdater.newUpdater(AsyncHandler.class, "state");
private static final int DEFAULT_QUEUE_LENGTH = 512; 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 * @param threadFactory the thread factory to use to construct the handler thread
*/ */
public AsyncHandler(final int queueLength, final ThreadFactory threadFactory) { public AsyncHandler(final int queueLength, final ThreadFactory threadFactory) {
recordQueue = new ArrayBlockingQueue<ExtLogRecord>(queueLength); recordQueue = new ArrayBlockingQueue<>(queueLength);
thread = threadFactory.newThread(new AsyncTask()); thread = threadFactory.newThread(new AsyncTask());
if (thread == null) { if (thread == null) {
throw new IllegalArgumentException("Thread factory did not create a thread"); throw new IllegalArgumentException("Thread factory did not create a thread");
@ -160,7 +160,7 @@ public class AsyncHandler extends ExtHandler {
boolean intr = false; boolean intr = false;
try { try {
for (; ; ) { for (; ; ) {
ExtLogRecord rec = null; ExtLogRecord rec;
try { try {
if (state == 2) { if (state == 2) {
rec = recordQueue.poll(); 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.ArrayDeque;
import java.util.Arrays; import java.util.Arrays;
@ -14,7 +14,7 @@ import java.util.logging.Level;
import org.xbib.logging.ExtHandler; import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.LogContext; import org.xbib.logging.LogContext;
import org.xbib.logging.formatters.PatternFormatter; import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.util.StandardOutputStreams; import org.xbib.logging.util.StandardOutputStreams;
/** /**
@ -148,69 +148,72 @@ public class DelayedHandler extends ExtHandler {
* @param record the record * @param record the record
*/ */
private void enqueueOrdered(Deque<ExtLogRecord> q, ExtLogRecord record) { private void enqueueOrdered(Deque<ExtLogRecord> q, ExtLogRecord record) {
assert lock.isHeldByCurrentThread(); if (lock.isHeldByCurrentThread()) {
ExtLogRecord last = q.peekLast(); ExtLogRecord last = q.peekLast();
if (last != null) { if (last != null) {
// check the ordering // check the ordering
if (Long.compareUnsigned(last.getSequenceNumber(), record.getSequenceNumber()) > 0) { if (Long.compareUnsigned(last.getSequenceNumber(), record.getSequenceNumber()) > 0) {
// out of order; we have to re-sort.. typically, it's only going to be out of order by a couple though // out of order; we have to re-sort.. typically, it's only going to be out of order by a couple though
q.pollLast(); q.pollLast();
try { try {
enqueueOrdered(q, record); enqueueOrdered(q, record);
} finally { } finally {
q.addLast(last); q.addLast(last);
}
return;
} }
return;
} }
// order is OK
q.addLast(record);
} }
// order is OK
q.addLast(record);
} }
private Supplier<ExtLogRecord> drain() { private Supplier<ExtLogRecord> drain() {
assert lock.isHeldByCurrentThread(); if (lock.isHeldByCurrentThread()) {
if (queues.isEmpty()) { if (queues.isEmpty()) {
return () -> null; return () -> null;
} }
List<Deque<ExtLogRecord>> values = List.copyOf(queues.values()); List<Deque<ExtLogRecord>> values = List.copyOf(queues.values());
queues.clear(); queues.clear();
int size = values.size(); int size = values.size();
List<ExtLogRecord> current = Arrays.asList(new ExtLogRecord[size]); List<ExtLogRecord> current = Arrays.asList(new ExtLogRecord[size]);
// every queue must have at least one item in it // every queue must have at least one item in it
int i = 0; int i = 0;
for (Deque<ExtLogRecord> value : values) { for (Deque<ExtLogRecord> value : values) {
current.set(i++, value.removeFirst()); current.set(i++, value.removeFirst());
} }
return new Supplier<ExtLogRecord>() { return new Supplier<>() {
@Override @Override
public ExtLogRecord get() { public ExtLogRecord get() {
ExtLogRecord min = null; ExtLogRecord min = null;
int minIdx = 0; int minIdx = 0;
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
ExtLogRecord item = current.get(i); ExtLogRecord item = current.get(i);
if (compareSeq(min, item) > 0) { if (compareSeq(min, item) > 0) {
min = item; min = item;
minIdx = i; minIdx = i;
}
}
if (min == null) {
return null;
}
current.set(minIdx, values.get(minIdx).pollFirst());
return min;
}
private int compareSeq(ExtLogRecord min, ExtLogRecord testItem) {
if (min == null) {
// null is greater than everything
return testItem == null ? 0 : 1;
} else if (testItem == null) {
return -1;
} else {
return Long.compareUnsigned(min.getSequenceNumber(), testItem.getSequenceNumber());
} }
} }
if (min == null) { };
return null; }
} return () -> null;
current.set(minIdx, values.get(minIdx).pollFirst());
return min;
}
private int compareSeq(ExtLogRecord min, ExtLogRecord testItem) {
if (min == null) {
// null is greater than everything
return testItem == null ? 0 : 1;
} else if (testItem == null) {
return -1;
} else {
return Long.compareUnsigned(min.getSequenceNumber(), testItem.getSequenceNumber());
}
}
};
} }
@Override @Override

View file

@ -1,4 +1,4 @@
package org.xbib.logging.handlers; package org.xbib.logging.ext.handlers;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -11,7 +11,8 @@ import java.time.temporal.ChronoUnit;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.logging.ErrorManager; import java.util.logging.ErrorManager;
import org.xbib.logging.ExtLogRecord; 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 * 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.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -6,8 +6,8 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.logging.ErrorManager; import java.util.logging.ErrorManager;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.io.CountingOutputStream; import org.xbib.logging.ext.io.CountingOutputStream;
import org.xbib.logging.util.SuffixRotator; 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. * 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.ArrayDeque;
import java.util.Deque; 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.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -6,8 +6,9 @@ import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.logging.ErrorManager; import java.util.logging.ErrorManager;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.io.CountingOutputStream; import org.xbib.logging.handlers.FileHandler;
import org.xbib.logging.util.SuffixRotator; import org.xbib.logging.ext.io.CountingOutputStream;
import org.xbib.logging.ext.util.SuffixRotator;
public class SizeRotatingFileHandler extends FileHandler { 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.Closeable;
import java.io.Flushable; import java.io.Flushable;
@ -15,10 +15,10 @@ import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import org.xbib.logging.ExtHandler; import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.io.TcpOutputStream; import org.xbib.logging.ext.io.TcpOutputStream;
import org.xbib.logging.io.UdpOutputStream; import org.xbib.logging.ext.io.UdpOutputStream;
import org.xbib.logging.io.UninterruptibleOutputStream; 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. * 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.Closeable;
import java.io.Flushable; import java.io.Flushable;
@ -24,10 +24,10 @@ import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import org.xbib.logging.ExtHandler; import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.io.TcpOutputStream; import org.xbib.logging.ext.io.TcpOutputStream;
import org.xbib.logging.io.UdpOutputStream; import org.xbib.logging.ext.io.UdpOutputStream;
import org.xbib.logging.net.ClientSocketFactory; import org.xbib.logging.ext.net.ClientSocketFactory;
import org.xbib.logging.util.ByteStringBuilder; import org.xbib.logging.ext.util.ByteStringBuilder;
import static java.time.temporal.ChronoField.DAY_OF_MONTH; import static java.time.temporal.ChronoField.DAY_OF_MONTH;
import static java.time.temporal.ChronoField.HOUR_OF_DAY; import static java.time.temporal.ChronoField.HOUR_OF_DAY;
import static java.time.temporal.ChronoField.MILLI_OF_SECOND; 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.IOException;
import java.io.OutputStream; 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.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
@ -10,7 +10,7 @@ import javax.xml.stream.XMLStreamWriter;
/** /**
* An XML stream writer which pretty prints the XML. * 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 = " "; private static final String SPACES = " ";
@ -19,7 +19,7 @@ class IndentingXmlWriter implements XMLStreamWriter, XMLStreamConstants {
private int state = START_DOCUMENT; private int state = START_DOCUMENT;
private boolean indentEnd; private boolean indentEnd;
IndentingXmlWriter(final XMLStreamWriter delegate) { public IndentingXmlWriter(final XMLStreamWriter delegate) {
this.delegate = delegate; this.delegate = delegate;
index = 0; index = 0;
indentEnd = false; 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.Flushable;
import java.io.IOException; 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; 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.Closeable;
import java.io.Flushable; import java.io.Flushable;
@ -16,7 +16,7 @@ import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import javax.net.SocketFactory; 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}. * 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.Flushable;
import java.io.IOException; import java.io.IOException;
@ -8,7 +8,7 @@ import java.net.DatagramSocket;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.net.SocketException; 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}. * 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.io.IOException;
import java.net.DatagramSocket; 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; 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.IOException;
import java.io.InputStream; 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.Collections;
import java.util.HashMap; import java.util.HashMap;
@ -29,16 +29,16 @@ public class ColorMap {
private static final String CLEAR = "\033[0m"; 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> codes;
private static final Map<String, String> reverseCodes; private static final Map<String, String> reverseCodes;
private static final Map<String, Integer> levels = new HashMap<String, Integer>(); private static final Map<String, Integer> levels = new HashMap<>();
private static final Map<Integer, String> reverseLevels = new HashMap<Integer, String>(); 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; private final NavigableMap<Integer, String> levelMap;
@ -90,12 +90,10 @@ public class ColorMap {
static final String BRIGHT_CYAN_NAME = "brightcyan"; static final String BRIGHT_CYAN_NAME = "brightcyan";
static final String BRIGHT_WHITE_NAME = "brightwhite"; static final String BRIGHT_WHITE_NAME = "brightwhite";
static final String CLEAR_NAME = "clear"; public static final String CLEAR_NAME = "clear";
static { static {
// Turn color on by default for everything but Windows, unless ansicon is used final boolean dft = true;
String os = System.getProperty("os.name");
final boolean dft = os != null && (!os.toLowerCase(Locale.ROOT).contains("win") || System.getenv("ANSICON") != null);
final String nocolor = System.getProperty("org.xbib.logging.nocolor"); final String nocolor = System.getProperty("org.xbib.logging.nocolor");
SUPPORTS_COLOR = (nocolor == null ? dft : "false".equalsIgnoreCase(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(BRIGHT_WHITE_NAME, BRIGHT_WHITE);
codes.put(CLEAR_NAME, CLEAR); codes.put(CLEAR_NAME, CLEAR);
reverseCodes = new HashMap<String, String>(); reverseCodes = new HashMap<>();
reverseCodes.put(DARK_BLACK, BLACK_NAME); reverseCodes.put(DARK_BLACK, BLACK_NAME);
reverseCodes.put(DARK_RED, RED_NAME); reverseCodes.put(DARK_RED, RED_NAME);
reverseCodes.put(DARK_GREEN, GREEN_NAME); reverseCodes.put(DARK_GREEN, GREEN_NAME);
@ -170,27 +168,22 @@ public class ColorMap {
} else { } else {
reverseCodes = codes = Collections.emptyMap(); reverseCodes = codes = Collections.emptyMap();
} }
} }
static ColorMap create(String expression) { public static ColorMap create(String expression) {
if (expression == null || expression.length() < 3) { if (expression == null || expression.length() < 3) {
return DEFAULT_COLOR_MAP; return DEFAULT_COLOR_MAP;
} }
NavigableMap<Integer, String> levelMap = new TreeMap<>();
NavigableMap<Integer, String> levelMap = new TreeMap<Integer, String>();
for (String pair : expression.split(",")) { for (String pair : expression.split(",")) {
String[] parts = pair.split(":"); String[] parts = pair.split(":");
if (parts.length != 2) { if (parts.length != 2) {
continue; continue;
} }
String color = codes.get(parts[1].toLowerCase(Locale.ROOT)); String color = codes.get(parts[1].toLowerCase(Locale.ROOT));
if (color == null) { if (color == null) {
continue; continue;
} }
try { try {
int i = Integer.parseInt(parts[0]); int i = Integer.parseInt(parts[0]);
levelMap.put(i, color); levelMap.put(i, color);
@ -198,23 +191,19 @@ public class ColorMap {
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
// eat // eat
} }
Integer i = levels.get(parts[0].toLowerCase(Locale.ROOT)); Integer i = levels.get(parts[0].toLowerCase(Locale.ROOT));
if (i == null) { if (i == null) {
continue; continue;
} }
levelMap.put(i, color); levelMap.put(i, color);
} }
return new ColorMap(levelMap); 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) { if (name == null || !SUPPORTS_COLOR) {
return null; return null;
} }
String lower = name.toLowerCase(Locale.ROOT); String lower = name.toLowerCase(Locale.ROOT);
if (lower.equals(LEVEL_NAME)) { if (lower.equals(LEVEL_NAME)) {
Map.Entry<Integer, String> entry = levelMap.floorEntry(level.intValue()); 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())) builder.append(level == null ? num : level).append(":").append(reverseCodes.get(entry.getValue()))
.append(","); .append(",");
} }
if (builder.length() > 0) { if (!builder.isEmpty()) {
builder.setLength(builder.length() - 1); 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.Executable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -9,11 +9,11 @@ import java.util.Locale;
import java.util.UUID; import java.util.UUID;
import org.xbib.logging.handlers.ConsoleHandler; import org.xbib.logging.handlers.ConsoleHandler;
class ColorPrintf extends Printf { public class ColorPrintf extends Printf {
private final int darken; private final int darken;
private final boolean trueColor = ConsoleHandler.isTrueColor(); private final boolean trueColor = ConsoleHandler.isTrueColor();
ColorPrintf(final int darken) { public ColorPrintf(final int darken) {
super(Locale.getDefault()); super(Locale.getDefault());
this.darken = darken; this.darken = darken;
} }

View file

@ -1,22 +1,19 @@
package org.xbib.logging.formatters; package org.xbib.logging.ext.util.formatter;
/** public final class ColorUtil {
* This is a throwaway temp class.
*/
final class ColorUtil {
private 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); 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); 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) { if (trueColor) {
return target.appendCodePoint(27).append('[').append(mode).append(';').append(2).append(';').append(clip(r)) return target.appendCodePoint(27).append('[').append(mode).append(';').append(2).append(';').append(clip(r))
.append(';').append(clip(g)).append(';').append(clip(b)).append('m'); .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); return Math.min(Math.max(0, color), 255);
} }
static StringBuilder endFgColor(StringBuilder target) { public static StringBuilder endFgColor(StringBuilder target) {
return endColor(target, 39); return endColor(target, 39);
} }
static StringBuilder endBgColor(StringBuilder target) { public static StringBuilder endBgColor(StringBuilder target) {
return endColor(target, 49); 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'); 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.AbstractSet;
import java.util.Iterator; 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.ArrayList;
import java.util.TimeZone; import java.util.TimeZone;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; 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. * 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. * 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; 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 { enum NumericFlag {
SIGN, 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; 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.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
@ -38,7 +38,15 @@ import static java.lang.Math.max;
/** /**
* A string formatter which can be customized. * 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 someSpaces = " "; //32 spaces
private static final String someZeroes = "00000000000000000000000000000000"; //32 zeros private static final String someZeroes = "00000000000000000000000000000000"; //32 zeros
@ -60,14 +68,6 @@ class Printf {
return locale; 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) { public String format(String format, Object... params) {
return formatDirect(new StringBuilder(), format, params).toString(); return formatDirect(new StringBuilder(), format, params).toString();
} }
@ -340,7 +340,7 @@ class Printf {
appendStr(destination, genFlags, width, -1, b.toString()); appendStr(destination, genFlags, width, -1, b.toString());
break; break;
} }
case 'R': { case 'R', 'T': {
final StringBuilder b = new StringBuilder(); final StringBuilder b = new StringBuilder();
formatTimeField(b, ta, ChronoField.HOUR_OF_DAY, genFlags, -1, 2); formatTimeField(b, ta, ChronoField.HOUR_OF_DAY, genFlags, -1, 2);
b.append(':'); b.append(':');
@ -363,16 +363,6 @@ class Printf {
appendStr(destination, genFlags, width, -1, b.toString()); appendStr(destination, genFlags, width, -1, b.toString());
break; 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: { default: {
throw unknownFormat(format, i); throw unknownFormat(format, i);
} }
@ -482,9 +472,9 @@ class Printf {
appendStr(destination, genFlags, width, precision, "null"); appendStr(destination, genFlags, width, precision, "null");
break; break;
} else if (argVal instanceof Character) { } else if (argVal instanceof Character) {
cpa = ((Character) argVal).charValue(); cpa = (Character) argVal;
} else if (argVal instanceof Integer) { } else if (argVal instanceof Integer) {
cpa = ((Integer) argVal).intValue(); cpa = (Integer) argVal;
} else { } else {
throw new IllegalFormatConversionException((char) cp, argVal.getClass()); throw new IllegalFormatConversionException((char) cp, argVal.getClass());
} }
@ -518,7 +508,6 @@ class Printf {
formatFloatingPointDecimal(destination, item, genFlags, numFlags, width, precision); formatFloatingPointDecimal(destination, item, genFlags, numFlags, width, precision);
break; break;
} else { } else {
assert cp == 'g' || cp == 'G';
formatFloatingPointGeneral(destination, item, genFlags, numFlags, width, precision); formatFloatingPointGeneral(destination, item, genFlags, numFlags, width, precision);
break; break;
} }
@ -832,22 +821,31 @@ 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) { int width, int precision) {
if (item == null) { if (item == null) {
appendStr(target, genFlags, width, precision, "null"); appendStr(target, genFlags, width, precision, "null");
} else { } else {
boolean sci; boolean sci;
if (item instanceof BigDecimal) { switch (item) {
final BigDecimal mag = ((BigDecimal) item).abs(); case BigDecimal bigDecimal -> {
sci = mag.compareTo(NEG_TEN_EM4) < 0 || mag.compareTo(BigDecimal.valueOf(10, precision)) >= 0; final BigDecimal mag = bigDecimal.abs();
} else if (item instanceof Float) { sci = mag.compareTo(NEG_TEN_EM4) < 0 || mag.compareTo(BigDecimal.valueOf(10, precision)) >= 0;
final float fv = Math.abs(item.floatValue()); }
sci = Float.isFinite(fv) && (fv < 10e-4f || fv >= Math.pow(10, precision)); case Float v -> {
} else { final float fv = Math.abs(item.floatValue());
assert item instanceof Double; sci = Float.isFinite(fv) && (fv < 10e-4f || fv >= Math.pow(10, precision));
final double dv = Math.abs(item.doubleValue()); }
sci = Double.isFinite(dv) && (dv < 10e-4f || dv >= Math.pow(10, precision)); 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) { if (sci) {
formatFloatingPointSci(target, item, genFlags, numFlags, width, precision); formatFloatingPointSci(target, item, genFlags, numFlags, width, precision);
@ -902,17 +900,18 @@ class Printf {
target.append(iterator.current()); target.append(iterator.current());
iterator.next(); // move iterator.next(); // move
} }
assert iterator.getAttribute(NumberFormat.Field.INTEGER) != null; if (iterator.getAttribute(NumberFormat.Field.INTEGER) != null) {
if (zp && width > end) { if (zp && width > end) {
appendZeros(target, width - end); appendZeros(target, width - end);
} }
// now continue to the end // now continue to the end
while (iterator.getIndex() < end) { while (iterator.getIndex() < end) {
target.append(iterator.current()); target.append(iterator.current());
iterator.next(); // move iterator.next(); // move
} }
if (lj && width > end) { if (lj && width > end) {
appendSpaces(target, width - end); appendSpaces(target, width - end);
}
} }
} }
@ -937,10 +936,11 @@ class Printf {
return 32 - Integer.numberOfLeadingZeros(item.intValue()); return 32 - Integer.numberOfLeadingZeros(item.intValue());
} else if (item instanceof Long) { } else if (item instanceof Long) {
return 64 - Long.numberOfLeadingZeros(item.longValue()); return 64 - Long.numberOfLeadingZeros(item.longValue());
} else { } else if (item instanceof BigInteger) {
assert item instanceof BigInteger;
return ((BigInteger) item).bitLength(); return ((BigInteger) item).bitLength();
} }
// impossible
return 0;
} }
private static void appendOctal(StringBuilder target, final Number item) { 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.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.logging.ErrorManager; import java.util.logging.ErrorManager;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
public class AssertingErrorManager extends ErrorManager { public class AssertingErrorManager extends ErrorManager {
@ -43,10 +42,13 @@ public class AssertingErrorManager extends ErrorManager {
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)) { PrintWriter pw = new PrintWriter(sw)) {
pw.printf("LogManager error of type %s: %s%n", codeStr, msg); pw.printf("LogManager error of type %s: %s%n", codeStr, msg);
ex.printStackTrace(pw); if (ex != null) {
ex.printStackTrace(pw);
}
Assertions.fail(sw.toString()); Assertions.fail(sw.toString());
} catch (IOException e) { } catch (IOException e) {
// This shouldn't happen, but just fail if it does // This shouldn't happen, but just fail if it does
e.printStackTrace();
Assertions.fail(String.format("Failed to print error message: %s", e.getMessage())); 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;
import org.xbib.logging.ExtLogRecord.FormatStyle; import org.xbib.logging.ExtLogRecord.FormatStyle;
import org.xbib.logging.test.MapTestUtils; import org.xbib.logging.ext.test.MapTestUtils;
abstract class AbstractTest extends 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.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -7,11 +7,10 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Objects; import java.util.Objects;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.xbib.logging.formatters.PatternFormatter; import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.formatters.TextBannerFormatter; import org.xbib.logging.ext.formatters.TextBannerFormatter;
/** /**
* Tests of the banner formatting capability. * Tests of the banner formatting capability.
@ -35,7 +34,7 @@ public class BannerFormatterTests {
tbf = new TextBannerFormatter(createResourceSupplier("non-existent-banner.txt", fallbackSupplier), emptyFormatter); tbf = new TextBannerFormatter(createResourceSupplier("non-existent-banner.txt", fallbackSupplier), emptyFormatter);
Assertions.assertEquals(FALLBACK_OK, tbf.getHead(null)); Assertions.assertEquals(FALLBACK_OK, tbf.getHead(null));
tbf = new TextBannerFormatter(createResourceSupplier("test-banner.txt", fallbackSupplier), emptyFormatter); 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); Assertions.assertNotNull(is);
try (is) { try (is) {
final String s = new String(is.readAllBytes(), StandardCharsets.UTF_8); 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.ExtLogRecord;
import org.xbib.logging.MDC; import org.xbib.logging.MDC;
import org.xbib.logging.NDC; import org.xbib.logging.NDC;
import org.junit.jupiter.api.Assertions; import org.xbib.logging.ext.formatters.PatternFormatter;
import org.junit.jupiter.api.Test;
import org.xbib.logging.formatters.PatternFormatter;
public class PatternFormatterTests { public class PatternFormatterTests {
static final String CATEGORY = "org.xbib.logging.formatters.PatternFormatterTests"; static final String CATEGORY = "org.xbib.logging.ext.test.formatters.PatternFormatterTests";
static { static {
// Set a system property // Set a system property
@ -20,7 +20,7 @@ public class PatternFormatterTests {
} }
@Test @Test
public void categories() throws Exception { public void categories() {
final ExtLogRecord record = createLogRecord("test"); final ExtLogRecord record = createLogRecord("test");
PatternFormatter formatter = new PatternFormatter("%c"); PatternFormatter formatter = new PatternFormatter("%c");
Assertions.assertEquals(CATEGORY, formatter.format(record)); Assertions.assertEquals(CATEGORY, formatter.format(record));
@ -32,16 +32,16 @@ public class PatternFormatterTests {
Assertions.assertEquals("formatters.PatternFormatterTests", formatter.format(record)); Assertions.assertEquals("formatters.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%c{1.}"); 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.~}"); formatter = new PatternFormatter("%c{1.~}");
Assertions.assertEquals("o.~.~.~.PatternFormatterTests", formatter.format(record)); Assertions.assertEquals("o.~.~.~.~.~.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%c{.}"); formatter = new PatternFormatter("%c{.}");
Assertions.assertEquals("....PatternFormatterTests", formatter.format(record)); Assertions.assertEquals("......PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%c{1~.}"); 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 // Test a simple logger name
record.setLoggerName("test"); record.setLoggerName("test");
@ -56,7 +56,7 @@ public class PatternFormatterTests {
} }
@Test @Test
public void classNames() throws Exception { public void classNames() {
final ExtLogRecord record = createLogRecord("test"); final ExtLogRecord record = createLogRecord("test");
PatternFormatter formatter = new PatternFormatter("%C"); PatternFormatter formatter = new PatternFormatter("%C");
Assertions.assertEquals(PatternFormatterTests.class.getName(), formatter.format(record)); Assertions.assertEquals(PatternFormatterTests.class.getName(), formatter.format(record));
@ -68,16 +68,16 @@ public class PatternFormatterTests {
Assertions.assertEquals("formatters.PatternFormatterTests", formatter.format(record)); Assertions.assertEquals("formatters.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%C{1.}"); 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.~}"); formatter = new PatternFormatter("%C{1.~}");
Assertions.assertEquals("o.~.~.~.~.PatternFormatterTests", formatter.format(record)); Assertions.assertEquals("o.~.~.~.~.~.PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%C{.}"); formatter = new PatternFormatter("%C{.}");
Assertions.assertEquals(".....PatternFormatterTests", formatter.format(record)); Assertions.assertEquals("......PatternFormatterTests", formatter.format(record));
formatter = new PatternFormatter("%C{1~.}"); 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 @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.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.xbib.logging.util.StackTraceFormatter; 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.io.StringReader;
import java.time.ZoneId; import java.time.ZoneId;
@ -6,7 +6,6 @@ import java.time.format.DateTimeFormatter;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import javax.xml.XMLConstants; import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
@ -18,16 +17,15 @@ import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema; import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory; import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator; 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.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.w3c.dom.Document; 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.ErrorHandler;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.SAXException; 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.BufferedReader;
import java.io.IOException; import java.io.IOException;
@ -19,11 +19,14 @@ import java.util.zip.GZIPInputStream;
import org.xbib.logging.ExtHandler; import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.formatters.PatternFormatter; import org.xbib.logging.ext.formatters.PatternFormatter;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo; 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 { public class AbstractHandlerTest {
@ -44,7 +47,7 @@ public class AbstractHandlerTest {
@Test @Test
public void simple() { public void simple() {
Assertions.assertTrue(testInfo.getTestMethod().isPresent()); assertTrue(testInfo.getTestMethod().isPresent());
} }
protected Path resolvePath(final String filename) throws IOException { protected Path resolvePath(final String filename) throws IOException {
@ -56,8 +59,8 @@ public class AbstractHandlerTest {
} }
protected Path logDirectory(final TestInfo testInfo) throws IOException { protected Path logDirectory(final TestInfo testInfo) throws IOException {
Assertions.assertTrue(testInfo.getTestClass().isPresent()); assertTrue(testInfo.getTestClass().isPresent());
Assertions.assertTrue(testInfo.getTestMethod().isPresent()); assertTrue(testInfo.getTestMethod().isPresent());
final Path dir = final Path dir =
BASE_LOG_DIR.resolve(testInfo.getTestClass().get().getSimpleName() + "-" + testInfo.getTestMethod().get().getName()); BASE_LOG_DIR.resolve(testInfo.getTestClass().get().getSimpleName() + "-" + testInfo.getTestMethod().get().getName());
if (Files.notExists(dir)) { 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()), try (final FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" + path.toUri().toASCIIString()),
Collections.singletonMap("create", "true"))) { Collections.singletonMap("create", "true"))) {
final Path file = zipFs.getPath(zipFs.getSeparator(), expectedFileName); 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); 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)); () -> 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)); () -> String.format("ZIP file %s missing contents: %s", path, expectedContains));
} }
} }
@ -163,18 +166,17 @@ public class AbstractHandlerTest {
lines1 = readAllLinesFromGzip(archive1); lines1 = readAllLinesFromGzip(archive1);
lines2 = readAllLinesFromGzip(archive2); lines2 = readAllLinesFromGzip(archive2);
} else { } 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 assertFalse(lines1.isEmpty(), () -> String.format("Archive %s contained no data", archive1));
Assertions.assertFalse(lines1.isEmpty(), () -> String.format("Archive %s contained no data", archive1)); assertFalse(lines2.isEmpty(), () -> String.format("Archive %s contained no data", archive2));
Assertions.assertFalse(lines2.isEmpty(), () -> String.format("Archive %s contained no data", archive2));
final Collection<String> copy1 = new ArrayList<>(lines1); final Collection<String> copy1 = new ArrayList<>(lines1);
final Collection<String> copy2 = new ArrayList<>(lines2); final Collection<String> copy2 = new ArrayList<>(lines2);
boolean altered = copy1.removeAll(copy2); boolean altered = copy1.removeAll(copy2);
if (copy1.isEmpty()) { 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) { } else if (altered) {
final StringBuilder msg = new StringBuilder(1024) final StringBuilder msg = new StringBuilder(1024)
.append("The following contents are in both ") .append("The following contents are in both ")
@ -187,7 +189,7 @@ public class AbstractHandlerTest {
msg.append(System.lineSeparator()).append(line); 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()), try (final FileSystem zipFs = FileSystems.newFileSystem(URI.create("jar:" + path.toUri().toASCIIString()),
Collections.singletonMap("create", "true"))) { Collections.singletonMap("create", "true"))) {
final Path file = zipFs.getPath(zipFs.getSeparator(), expectedFileName); 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); 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.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingDeque;
@ -9,13 +9,14 @@ import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level; import org.xbib.logging.Level;
import org.xbib.logging.MDC; import org.xbib.logging.MDC;
import org.xbib.logging.NDC; import org.xbib.logging.NDC;
import org.xbib.logging.formatters.PatternFormatter; import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.handlers.AsyncHandler; import org.xbib.logging.ext.handlers.AsyncHandler;
import org.xbib.logging.handlers.AsyncHandler.OverflowAction; import org.xbib.logging.ext.handlers.AsyncHandler.OverflowAction;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.xbib.logging.ext.test.AssertingErrorManager;
public class AsyncHandlerTests { 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.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -11,8 +11,8 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.xbib.logging.handlers.DelayedHandler; import org.xbib.logging.ext.handlers.DelayedHandler;
import org.xbib.logging.test.AssertingErrorManager; import org.xbib.logging.ext.test.AssertingErrorManager;
import org.xbib.logging.ExtHandler; import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.LogContext; 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 java.util.logging.SimpleFormatter;
import org.xbib.logging.test.AssertingErrorManager;
import org.xbib.logging.ExtHandler; 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.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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue; 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.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -8,8 +8,9 @@ import java.util.List;
import org.xbib.logging.ExtHandler; import org.xbib.logging.ExtHandler;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.Level; 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.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.assertEquals;
public class QueueHandlerTests extends AbstractHandlerTest { 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.ByteArrayOutputStream;
import java.io.IOException; 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.io.UnsupportedEncodingException;
import java.net.InetAddress; import java.net.InetAddress;
@ -12,11 +12,15 @@ import javax.net.ssl.SSLContext;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.LogContext; import org.xbib.logging.LogContext;
import org.xbib.logging.Logger; import org.xbib.logging.Logger;
import org.xbib.logging.formatters.PatternFormatter; import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.handlers.SocketHandler; import org.xbib.logging.ext.handlers.SocketHandler;
import org.xbib.logging.handlers.SocketHandler.Protocol; import org.xbib.logging.ext.handlers.SocketHandler.Protocol;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; 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 { public class SocketHandlerTests extends AbstractHandlerTest {
@ -33,8 +37,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
final ExtLogRecord record = createLogRecord("Test TCP handler"); final ExtLogRecord record = createLogRecord("Test TCP handler");
handler.publish(record); handler.publish(record);
final String msg = server.timeoutPoll(); final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test TCP handler", msg); assertEquals("Test TCP handler", msg);
} }
} }
@ -45,8 +49,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
final ExtLogRecord record = createLogRecord("Test TLS handler"); final ExtLogRecord record = createLogRecord("Test TLS handler");
handler.publish(record); handler.publish(record);
final String msg = server.timeoutPoll(); final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test TLS handler", msg); assertEquals("Test TLS handler", msg);
} }
} }
@ -57,8 +61,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
final ExtLogRecord record = createLogRecord("Test UDP handler"); final ExtLogRecord record = createLogRecord("Test UDP handler");
handler.publish(record); handler.publish(record);
final String msg = server.timeoutPoll(); final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test UDP handler", msg); assertEquals("Test UDP handler", msg);
} }
} }
@ -73,20 +77,20 @@ public class SocketHandlerTests extends AbstractHandlerTest {
ExtLogRecord record = createLogRecord("Test TCP handler " + port); ExtLogRecord record = createLogRecord("Test TCP handler " + port);
handler.publish(record); handler.publish(record);
String msg = server1.timeoutPoll(); String msg = server1.timeoutPoll();
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test TCP handler " + port, msg); assertEquals("Test TCP handler " + port, msg);
// Change the port on the handler which should close the first connection and open a new one // Change the port on the handler which should close the first connection and open a new one
handler.setPort(altPort); handler.setPort(altPort);
record = createLogRecord("Test TCP handler " + altPort); record = createLogRecord("Test TCP handler " + altPort);
handler.publish(record); handler.publish(record);
msg = server2.timeoutPoll(); msg = server2.timeoutPoll();
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test TCP handler " + altPort, 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 // 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 // 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"); final ExtLogRecord record = createLogRecord("Test TCP handler");
handler.publish(record); handler.publish(record);
final String msg = server.timeoutPoll(); final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test TCP handler", msg); assertEquals("Test TCP handler", msg);
} }
// wait until the OS really release used port // wait until the OS really release used port
Thread.sleep(50); Thread.sleep(50);
@ -112,8 +116,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
final ExtLogRecord record = createLogRecord("Test TLS handler"); final ExtLogRecord record = createLogRecord("Test TLS handler");
handler.publish(record); handler.publish(record);
final String msg = server.timeoutPoll(); final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test TLS handler", msg); assertEquals("Test TLS handler", msg);
} }
} finally { } finally {
if (handler != null) { if (handler != null) {
@ -128,15 +132,14 @@ public class SocketHandlerTests extends AbstractHandlerTest {
try { try {
// Publish a record to a running server // Publish a record to a running server
try ( try (SimpleServer server = SimpleServer.createTcpServer()) {
SimpleServer server = SimpleServer.createTcpServer()) {
handler = createHandler(Protocol.TCP, server.getPort()); handler = createHandler(Protocol.TCP, server.getPort());
handler.setErrorManager(AssertingErrorManager.of(ErrorManager.FLUSH_FAILURE)); handler.setErrorManager(AssertingErrorManager.of(ErrorManager.FLUSH_FAILURE));
final ExtLogRecord record = createLogRecord("Test TCP handler"); final ExtLogRecord record = createLogRecord("Test TCP handler");
handler.publish(record); handler.publish(record);
final String msg = server.timeoutPoll(); final String msg = server.timeoutPoll();
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test TCP handler", msg); assertEquals("Test TCP handler", msg);
} }
// wait until the OS really release used port // wait until the OS really release used port
Thread.sleep(50); Thread.sleep(50);
@ -158,8 +161,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
}, 10); }, 10);
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test TCP handler", msg); assertEquals("Test TCP handler", msg);
} }
} finally { } finally {
if (handler != null) { if (handler != null) {
@ -188,8 +191,8 @@ public class SocketHandlerTests extends AbstractHandlerTest {
rootLogger.addHandler(socketHandler); rootLogger.addHandler(socketHandler);
rootLogger.info("Test TCP handler " + port + " 1"); rootLogger.info("Test TCP handler " + port + " 1");
String msg = server.timeoutPoll(); String msg = server.timeoutPoll();
Assertions.assertNotNull(msg); assertNotNull(msg);
Assertions.assertEquals("Test TCP handler " + port + " 1", msg); assertEquals("Test TCP handler " + port + " 1", msg);
} }
} }
@ -217,7 +220,7 @@ public class SocketHandlerTests extends AbstractHandlerTest {
TimeUnit.MILLISECONDS.sleep(sleep); TimeUnit.MILLISECONDS.sleep(sleep);
t -= 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; 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.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
@ -10,13 +10,14 @@ import java.util.concurrent.TimeUnit;
import java.util.logging.Level; import java.util.logging.Level;
import org.xbib.logging.ExtLogRecord; import org.xbib.logging.ExtLogRecord;
import org.xbib.logging.formatters.PatternFormatter; import org.xbib.logging.ext.formatters.PatternFormatter;
import org.xbib.logging.handlers.SyslogHandler; import org.xbib.logging.ext.handlers.SyslogHandler;
import org.xbib.logging.handlers.SyslogHandler.SyslogType; import org.xbib.logging.ext.handlers.SyslogHandler.SyslogType;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.xbib.logging.ext.test.AssertingErrorManager;
public class SyslogHandlerTests { 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.AfterEach;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@Disabled
public class SystemLoggerIT { public class SystemLoggerIT {
private Path stdout; 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 { module org.xbib.logging {
uses org.xbib.logging.LogContextInitializer; uses org.xbib.logging.LogContextInitializer;
uses org.xbib.logging.LogContextConfiguratorFactory; uses org.xbib.logging.LogContextConfiguratorFactory;
@ -5,13 +10,15 @@ module org.xbib.logging {
uses org.xbib.logging.NDCProvider; uses org.xbib.logging.NDCProvider;
uses org.xbib.logging.MDCProvider; uses org.xbib.logging.MDCProvider;
requires transitive java.logging; requires transitive java.logging;
requires java.xml;
requires java.management; requires java.management;
exports org.xbib.logging; exports org.xbib.logging;
exports org.xbib.logging.configuration; exports org.xbib.logging.configuration;
exports org.xbib.logging.filters; exports org.xbib.logging.filters;
exports org.xbib.logging.formatters; exports org.xbib.logging.formatters;
exports org.xbib.logging.handlers; exports org.xbib.logging.handlers;
exports org.xbib.logging.net; exports org.xbib.logging.io;
exports org.xbib.logging.util; 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) { public void error(final String msg, final Exception ex, final int code) {
super.error(msg, ex, code); super.error(msg, ex, code);
} }

View file

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

View file

@ -15,6 +15,7 @@ import java.util.logging.Level;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
import org.xbib.logging.errormanager.OnlyOnceErrorManager; import org.xbib.logging.errormanager.OnlyOnceErrorManager;
import org.xbib.logging.util.AtomicArray; 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} * 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} * {@inheritDoc}
*/ */
@Override
public void publish(final LogRecord record) { public void publish(final LogRecord record) {
if (enabled && record != null && isLoggable(record)) { if (enabled && record != null && isLoggable(record)) {
doPublish(ExtLogRecord.wrap(record)); doPublish(ExtLogRecord.wrap(record));
@ -480,9 +482,7 @@ public abstract class ExtHandler extends Handler implements AutoCloseable, Flush
try { try {
errorManager.error(msg, ex, code); errorManager.error(msg, ex, code);
} catch (Exception ex2) { } catch (Exception ex2) {
// use the same message as the JDK StandardOutputStreams.printError(ex2, "Handler.reportError caught: " + ex2.getMessage());
System.err.println("Handler.reportError caught:");
ex2.printStackTrace();
} }
} }
} }

View file

@ -349,6 +349,7 @@ public class ExtLogRecord extends LogRecord {
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override
public String getSourceClassName() { public String getSourceClassName() {
calculateCaller(); calculateCaller();
return super.getSourceClassName(); return super.getSourceClassName();
@ -357,6 +358,7 @@ public class ExtLogRecord extends LogRecord {
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override
public void setSourceClassName(final String sourceClassName) { public void setSourceClassName(final String sourceClassName) {
calculateCaller = false; calculateCaller = false;
super.setSourceClassName(sourceClassName); super.setSourceClassName(sourceClassName);
@ -365,6 +367,7 @@ public class ExtLogRecord extends LogRecord {
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override
public String getSourceMethodName() { public String getSourceMethodName() {
calculateCaller(); calculateCaller();
return super.getSourceMethodName(); return super.getSourceMethodName();
@ -373,6 +376,7 @@ public class ExtLogRecord extends LogRecord {
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override
public void setSourceMethodName(final String sourceMethodName) { public void setSourceMethodName(final String sourceMethodName) {
calculateCaller = false; calculateCaller = false;
super.setSourceMethodName(sourceMethodName); super.setSourceMethodName(sourceMethodName);
@ -428,8 +432,9 @@ public class ExtLogRecord extends LogRecord {
public String getFormattedMessage() { public String getFormattedMessage() {
final ResourceBundle bundle = getResourceBundle(); final ResourceBundle bundle = getResourceBundle();
String msg = getMessage(); String msg = getMessage();
if (msg == null) if (msg == null) {
return null; return null;
}
if (bundle != null) { if (bundle != null) {
try { try {
msg = bundle.getString(msg); msg = bundle.getString(msg);
@ -540,6 +545,7 @@ public class ExtLogRecord extends LogRecord {
* *
* @param message the new raw message * @param message the new raw message
*/ */
@Override
public void setMessage(final String message) { public void setMessage(final String message) {
setMessage(message, FormatStyle.MESSAGE_FORMAT); setMessage(message, FormatStyle.MESSAGE_FORMAT);
} }
@ -561,6 +567,7 @@ public class ExtLogRecord extends LogRecord {
* *
* @param parameters the log message parameters. (may be null) * @param parameters the log message parameters. (may be null)
*/ */
@Override
public void setParameters(final Object[] parameters) { public void setParameters(final Object[] parameters) {
super.setParameters(parameters); super.setParameters(parameters);
} }
@ -570,6 +577,7 @@ public class ExtLogRecord extends LogRecord {
* *
* @param bundle localization bundle (may be null) * @param bundle localization bundle (may be null)
*/ */
@Override
public void setResourceBundle(final ResourceBundle bundle) { public void setResourceBundle(final ResourceBundle bundle) {
super.setResourceBundle(bundle); super.setResourceBundle(bundle);
} }
@ -579,6 +587,7 @@ public class ExtLogRecord extends LogRecord {
* *
* @param name localization bundle name (may be null) * @param name localization bundle name (may be null)
*/ */
@Override
public void setResourceBundleName(final String name) { public void setResourceBundleName(final String name) {
super.setResourceBundleName(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.CopyOnWriteMap;
import org.xbib.logging.util.CopyOnWriteWeakMap; import org.xbib.logging.util.CopyOnWriteWeakMap;
/** /**
* A logging context, for producing isolated logging environments. * A logging context, for producing isolated logging environments.
*/ */
@ -62,6 +61,7 @@ public final class LogContext implements AutoCloseable {
* before the class init is complete. * before the class init is complete.
*/ */
private static final class LazyHolder { private static final class LazyHolder {
private static final HashMap<String, Reference<Level, Void>> INITIAL_LEVEL_MAP; private static final HashMap<String, Reference<Level, Void>> INITIAL_LEVEL_MAP;
private LazyHolder() { private LazyHolder() {
@ -392,11 +392,7 @@ public final class LogContext implements AutoCloseable {
/** /**
* The default log context selector, which always returns the system log context. * The default log context selector, which always returns the system log context.
*/ */
public static final LogContextSelector DEFAULT_LOG_CONTEXT_SELECTOR = new LogContextSelector() { public static final LogContextSelector DEFAULT_LOG_CONTEXT_SELECTOR = () -> SYSTEM_CONTEXT;
public LogContext getLogContext() {
return SYSTEM_CONTEXT;
}
};
private static volatile LogContextSelector logContextSelector = DEFAULT_LOG_CONTEXT_SELECTOR; 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) { private void recursivelyClose(final LoggerNode loggerNode) {
assert treeLock.isHeldByCurrentThread(); if (treeLock.isHeldByCurrentThread()) {
for (LoggerNode child : loggerNode.getChildren()) { for (LoggerNode child : loggerNode.getChildren()) {
recursivelyClose(child); recursivelyClose(child);
}
loggerNode.close();
} }
loggerNode.close();
} }
} }

View file

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

View file

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

View file

@ -3,6 +3,7 @@ package org.xbib.logging;
import java.util.Iterator; import java.util.Iterator;
import java.util.ServiceConfigurationError; import java.util.ServiceConfigurationError;
import java.util.ServiceLoader; 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 * 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(); return iterator.next();
} catch (ServiceConfigurationError | RuntimeException e) { } catch (ServiceConfigurationError | RuntimeException e) {
System.err.print("Warning: failed to load NDC Provider: "); StandardOutputStreams.printError(e, "Warning: failed to load NDC Provider: " + e.getMessage());
e.printStackTrace(System.err);
} }
} }

View file

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

View file

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

View file

@ -19,10 +19,12 @@ class WrappedExtLogRecord extends ExtLogRecord {
this.logRecord = logRecord; this.logRecord = logRecord;
} }
@Override
public String getLoggerName() { public String getLoggerName() {
return logRecord.getLoggerName(); return logRecord.getLoggerName();
} }
@Override
public void setLoggerName(final String name) { public void setLoggerName(final String name) {
super.setLoggerName(name); super.setLoggerName(name);
logRecord.setLoggerName(name); logRecord.setLoggerName(name);
@ -126,11 +128,13 @@ class WrappedExtLogRecord extends ExtLogRecord {
return super.getSourceLineNumber(); return super.getSourceLineNumber();
} }
@Override
public void setSourceLineNumber(final int sourceLineNumber) { public void setSourceLineNumber(final int sourceLineNumber) {
resolved = true; resolved = true;
super.setSourceLineNumber(sourceLineNumber); super.setSourceLineNumber(sourceLineNumber);
} }
@Override
public String getSourceFileName() { public String getSourceFileName() {
if (!resolved) { if (!resolved) {
resolve(); resolve();
@ -173,12 +177,14 @@ class WrappedExtLogRecord extends ExtLogRecord {
@Deprecated @Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override
public int getThreadID() { public int getThreadID() {
return logRecord.getThreadID(); return logRecord.getThreadID();
} }
@Deprecated @Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Override
public void setThreadID(final int threadID) { public void setThreadID(final int threadID) {
super.setThreadID(threadID); super.setThreadID(threadID);
logRecord.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}. * wrapped and considered a {@linkplain ConfigurationResource#of(Supplier) lazy resource}.
* </p> * </p>
*/ */
@SuppressWarnings({"UnusedReturnValue", "unused"})
public class ContextConfiguration implements AutoCloseable { public class ContextConfiguration implements AutoCloseable {
public static final Logger.AttachmentKey<ContextConfiguration> CONTEXT_CONFIGURATION_KEY = new Logger.AttachmentKey<>(); public static final Logger.AttachmentKey<ContextConfiguration> CONTEXT_CONFIGURATION_KEY = new Logger.AttachmentKey<>();
private final LogContext context; private final LogContext context;
private final Map<String, ConfigurationResource<ErrorManager>> errorManagers; private final Map<String, ConfigurationResource<ErrorManager>> errorManagers;
private final Map<String, ConfigurationResource<Filter>> filters; private final Map<String, ConfigurationResource<Filter>> filters;
private final Map<String, ConfigurationResource<Formatter>> formatters; private final Map<String, ConfigurationResource<Formatter>> formatters;
private final Map<String, ConfigurationResource<Handler>> handlers; private final Map<String, ConfigurationResource<Handler>> handlers;
private final Map<String, ConfigurationResource<Object>> objects; 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) { private static void closeResources(final Map<String, ? extends ConfigurationResource<?>> resources) {
final var iter = resources.entrySet().iterator(); final var iterator = resources.entrySet().iterator();
while (iter.hasNext()) { while (iterator.hasNext()) {
var entry = iter.next(); var entry = iterator.next();
iter.remove(); iterator.remove();
try { try {
entry.getValue().close(); entry.getValue().close();
} catch (Throwable ignore) { } 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.expression.Expression;
import org.xbib.logging.filters.AcceptAllFilter; import org.xbib.logging.filters.AcceptAllFilter;
import org.xbib.logging.filters.DenyAllFilter; import org.xbib.logging.filters.DenyAllFilter;
import org.xbib.logging.util.ObjectBuilder;
import org.xbib.logging.util.StandardOutputStreams; 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.Level;
import org.xbib.logging.LogContext; import org.xbib.logging.LogContext;
import org.xbib.logging.LogContextConfigurator; 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.handlers.ConsoleHandler;
import org.xbib.logging.util.StandardOutputStreams; import org.xbib.logging.util.StandardOutputStreams;
@ -64,7 +64,7 @@ public class PropertyLogContextConfigurator implements LogContextConfigurator {
logContextConfigurator.configure(context, null); logContextConfigurator.configure(context, null);
} else { } else {
// Configure a default console handler, thread formatter and associated with the root logger // 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.setLevel(Level.INFO);
handler.setAutoFlush(true); handler.setAutoFlush(true);
final Logger rootLogger = context.getLogger(""); 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. * An error manager which publishes errors to a handler.
*/ */
public final class HandlerErrorManager extends ExtErrorManager { public final class HandlerErrorManager extends ExtErrorManager {
private static final ThreadLocal<Boolean> handlingError = new ThreadLocal<>(); private static final ThreadLocal<Boolean> handlingError = new ThreadLocal<>();
private final Handler handler; private final Handler handler;
@ -20,6 +21,7 @@ public final class HandlerErrorManager extends ExtErrorManager {
this.handler = handler; this.handler = handler;
} }
@Override
public void error(final String msg, final Exception ex, final int code) { public void error(final String msg, final Exception ex, final int code) {
if (handlingError.get() != Boolean.TRUE) { if (handlingError.get() != Boolean.TRUE) {
handlingError.set(Boolean.TRUE); handlingError.set(Boolean.TRUE);

View file

@ -29,6 +29,7 @@ public final class OnlyOnceErrorManager extends ExtErrorManager {
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
@Override
public void error(final String msg, final Exception ex, final int code) { public void error(final String msg, final Exception ex, final int code) {
ErrorManager delegate = this.delegate; ErrorManager delegate = this.delegate;
if (delegate == null) { 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. * An error manager which simply prints a message the system error stream.
*/ */
public class SimpleErrorManager extends ExtErrorManager { public class SimpleErrorManager extends ExtErrorManager {
@Override
public void error(final String msg, final Exception ex, final int code) { 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); 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); this.subNodes = subNodes.toArray(NO_NODES);
} }
@Override
<E extends Exception> void emit(final ResolveContext<E> context, <E extends Exception> void emit(final ResolveContext<E> context,
final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E { final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E {
for (Node subNode : subNodes) { for (Node subNode : subNodes) {
@ -21,12 +22,14 @@ final class CompositeNode extends Node {
} }
} }
@Override
void catalog(final HashSet<String> strings) { void catalog(final HashSet<String> strings) {
for (Node node : subNodes) { for (Node node : subNodes) {
node.catalog(strings); node.catalog(strings);
} }
} }
@Override
public String toString() { public String toString() {
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
b.append('*'); b.append('*');

View file

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

View file

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

View file

@ -30,14 +30,17 @@ class LiteralNode extends Node {
this(literalValue, 0, literalValue.length()); this(literalValue, 0, literalValue.length());
} }
@Override
<E extends Exception> void emit(final ResolveContext<E> context, <E extends Exception> void emit(final ResolveContext<E> context,
final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E { final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E {
context.getStringBuilder().append(literalValue, start, end); context.getStringBuilder().append(literalValue, start, end);
} }
@Override
void catalog(final HashSet<String> strings) { void catalog(final HashSet<String> strings) {
} }
@Override
public String toString() { public String toString() {
final String toString = this.toString; final String toString = this.toString;
return toString != null ? toString : (this.toString = literalValue.substring(start, end)); 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() { static final Node NULL = new Node() {
@Override
<E extends Exception> void emit(final ResolveContext<E> context, <E extends Exception> void emit(final ResolveContext<E> context,
final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E { final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> resolveFunction) throws E {
} }
@Override
void catalog(final HashSet<String> strings) { void catalog(final HashSet<String> strings) {
} }
@Override
public String toString() { public String toString() {
return "<<null>>"; 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 * @param <E> the exception type that can be thrown by the expansion function
*/ */
public final class ResolveContext<E extends Exception> { public final class ResolveContext<E extends Exception> {
private final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> function; private final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> function;
private StringBuilder builder; private StringBuilder builder;
private ExpressionNode current; private ExpressionNode current;
ResolveContext(final ExceptionBiConsumer<ResolveContext<E>, StringBuilder, E> function, final StringBuilder builder) { 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 * @throws E if the recursive expansion threw an exception
*/ */
public String getKey() throws E { public String getKey() throws E {
if (current == null) if (current == null) {
throw new IllegalStateException(); throw new IllegalStateException();
}
final Node key = current.getKey(); final Node key = current.getKey();
if (key instanceof LiteralNode) { if (key instanceof LiteralNode) {
return key.toString(); return key.toString();
@ -49,22 +53,24 @@ public final class ResolveContext<E extends Exception> {
* @throws E if the recursive expansion threw an exception * @throws E if the recursive expansion threw an exception
*/ */
public void expandDefault(StringBuilder target) throws E { public void expandDefault(StringBuilder target) throws E {
if (current == null) if (current == null) {
throw new IllegalStateException(); throw new IllegalStateException();
}
emitToBuilder(target, current.getDefaultValue()); emitToBuilder(target, current.getDefaultValue());
} }
private void emitToBuilder(final StringBuilder target, final Node node) throws E { private void emitToBuilder(final StringBuilder target, final Node node) throws E {
if (node == Node.NULL) { if (node != Node.NULL) {
} else if (node instanceof LiteralNode) { if (node instanceof LiteralNode) {
target.append(node); target.append(node);
} else { } else {
final StringBuilder old = builder; final StringBuilder old = builder;
try { try {
builder = target; builder = target;
node.emit(this, function); node.emit(this, function);
} finally { } finally {
builder = old; builder = old;
}
} }
} }
} }
@ -89,8 +95,9 @@ public final class ResolveContext<E extends Exception> {
* @throws E if the recursive expansion threw an exception * @throws E if the recursive expansion threw an exception
*/ */
public String getExpandedDefault() throws E { public String getExpandedDefault() throws E {
if (current == null) if (current == null) {
throw new IllegalStateException(); throw new IllegalStateException();
}
final Node defaultValue = current.getDefaultValue(); final Node defaultValue = current.getDefaultValue();
if (defaultValue instanceof LiteralNode) { if (defaultValue instanceof LiteralNode) {
return defaultValue.toString(); return defaultValue.toString();

View file

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

View file

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

View file

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

View file

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

View file

@ -24,6 +24,7 @@ public final class InvertFilter implements Filter {
* @param record the log record * @param record the log record
* @return {@code true} if the target filter returns {@code false}, {@code false} otherwise * @return {@code true} if the target filter returns {@code false}, {@code false} otherwise
*/ */
@Override
public boolean isLoggable(final LogRecord record) { public boolean isLoggable(final LogRecord record) {
return !target.isLoggable(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 * @param record the record to inspect and possibly update
* @return {@code true} always * @return {@code true} always
*/ */
@Override
public boolean isLoggable(final LogRecord record) { public boolean isLoggable(final LogRecord record) {
record.setLevel(newLevel); record.setLevel(newLevel);
return true; return true;

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