Skip to content

Commit

Permalink
use log4j-api instead of slf4j for internal logging, split utility.lo…
Browse files Browse the repository at this point in the history
…gging
  • Loading branch information
xzel23 committed Oct 31, 2023
1 parent f6abf25 commit e03b212
Show file tree
Hide file tree
Showing 37 changed files with 271 additions and 106 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,13 @@ the parameter.
## Changes
- all internal logging is done through log4j-api instead of slf4j
- introduced util-logging-slf4j as sub project of util-logging. Note that util-logging is not intended as a production logging
replacement. It is intended to provide utilites to capture and display log data in an application window.
### 12.0.0 (to be released)
-
### 11.1.3
- update log4j to 2.21.0 (according to release notes now fully JLink compatible)
Expand Down
4 changes: 2 additions & 2 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ subprojects {
compileOnly(rootProject.libs.cabe.annotations)

// SLF4J
implementation(rootProject.libs.slf4j.api)
testImplementation(rootProject.libs.slf4j.simple)
implementation(rootProject.libs.log4j.api)
testImplementation(rootProject.libs.log4j.core)

// JUnit
testImplementation(rootProject.libs.junit.jupiter.api)
Expand Down
6 changes: 5 additions & 1 deletion settings.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
rootProject.name = "dua3-utility"
val projectVersion = "11.1.4-SNAPSHOT"
val projectVersion = "12.0.0-SNAPSHOT"

include("utility")
include("utility-db")
include("utility-swing")
include("utility-logging")
include("utility-logging:utility-logging-slf4j")
include("utility-samples")

dependencyResolutionManagement {
Expand All @@ -30,11 +31,14 @@ dependencyResolutionManagement {
library("cabe-annotations", "com.dua3.cabe", "cabe-annotations").versionRef("cabe")

library("slf4j-api", "org.slf4j", "slf4j-api").versionRef("slf4j")
//library("slf4j-core", "org.slf4j", "slf4j-core").versionRef("slf4j")
library("slf4j-simple", "org.slf4j", "slf4j-simple").versionRef("slf4j")
library("jul-to-slf4j", "org.slf4j", "jul-to-slf4j").versionRef("slf4j")

library("miglayout-swing", "com.miglayout", "miglayout-swing").versionRef("miglayout")

library("log4j-api", "org.apache.logging.log4j", "log4j-api").versionRef("log4j")
library("log4j-core", "org.apache.logging.log4j", "log4j-core").versionRef("log4j")
library("log4j-to-slf4j", "org.apache.logging.log4j", "log4j-to-slf4j").versionRef("log4j")

library("junit-jupiter-api", "org.junit.jupiter", "junit-jupiter-api").versionRef("junit")
Expand Down
6 changes: 3 additions & 3 deletions utility-db/src/main/java/com/dua3/utility/db/DbUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
import com.dua3.utility.lang.LangUtil;
import com.dua3.utility.lang.WrappedException;
import com.dua3.utility.options.Arguments;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import javax.sql.DataSource;
import java.io.BufferedReader;
Expand Down Expand Up @@ -53,7 +53,7 @@ public final class DbUtil {
/**
* Logger instance.
*/
private static final Logger LOG = LoggerFactory.getLogger(DbUtil.class);
private static final Logger LOG = LogManager.getLogger(DbUtil.class);
/**
* List of know JDBC drivers.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import com.dua3.utility.options.Arguments;
import com.dua3.utility.options.SimpleOption;
import com.dua3.utility.text.TextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import java.nio.file.Paths;
import java.util.ArrayList;
Expand Down Expand Up @@ -45,7 +45,7 @@ public class JdbcDriverInfo {
* Type identifier String for double options.
*/
public static final String OPTION_TYPE_DOUBLE = "double";
private static final Logger LOG = LoggerFactory.getLogger(JdbcDriverInfo.class);
private static final Logger LOG = LogManager.getLogger(JdbcDriverInfo.class);
private static final String PATTERN_VAR_START = "\\$\\{";
private static final String PATTERN_VAR_NAME = "(?<name>\\p{Alpha}(\\p{Alnum}|_)*)";
private static final String PATTERN_VAR_ARG_1 = "(:((?<arg1>\\p{Alpha}(\\p{Alnum}|_)*)=(?<value1>[^,}]*)))";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
package com.dua3.utility.db;

import com.dua3.cabe.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import java.io.InputStream;
import java.io.Reader;
Expand Down Expand Up @@ -87,7 +87,7 @@ public class NamedParameterStatement implements AutoCloseable {
/**
* Logger instance.
*/
private static final Logger LOG = LoggerFactory.getLogger(NamedParameterStatement.class);
private static final Logger LOG = LogManager.getLogger(NamedParameterStatement.class);
private static boolean showUnknownParameterTypeAsWarning = true;
/**
* The statement this object is wrapping.
Expand Down
2 changes: 1 addition & 1 deletion utility-db/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@
requires transitive java.sql;

requires com.dua3.utility;
requires org.slf4j;
requires org.apache.logging.log4j;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.dua3.utility.data.Color;
import com.dua3.utility.data.Pair;
import com.dua3.utility.io.AnsiCode;
import org.slf4j.event.Level;

import java.io.PrintStream;
import java.util.EnumMap;
Expand All @@ -15,11 +14,8 @@
*/
public class ConsoleHandler implements LogEntryHandler {
private static final String NEWLINE = "%n".formatted();
private static final Pair<String, String> NO_ESCAPE_SEQUENCES = Pair.of("", "");
private static final String ESC_RESET = AnsiCode.reset();

private final PrintStream out;
private final Map<Level, Pair<String, String>> brackets = new EnumMap<>(Level.class);
private final Map<LogLevel, Pair<String, String>> colorMap = new EnumMap<>(LogLevel.class);

/**
* Constructs a ConsoleHandler with the specified PrintStream and colored flag.
Expand All @@ -29,19 +25,25 @@ public class ConsoleHandler implements LogEntryHandler {
*/
public ConsoleHandler(PrintStream out, boolean colored) {
this.out = out;

if (colored) {
brackets.put(Level.TRACE, Pair.of(AnsiCode.fg(Color.DARKGRAY), ESC_RESET));
brackets.put(Level.DEBUG, Pair.of(AnsiCode.fg(Color.BLACK), ESC_RESET));
brackets.put(Level.INFO, Pair.of(AnsiCode.fg(Color.BLUE), ESC_RESET));
brackets.put(Level.WARN, Pair.of(AnsiCode.fg(Color.ORANGERED), ESC_RESET));
brackets.put(Level.ERROR, Pair.of(AnsiCode.fg(Color.DARKRED), ESC_RESET));
colorMap.put(LogLevel.TRACE, Pair.of(AnsiCode.fg(Color.DARKGRAY), AnsiCode.reset()+NEWLINE));
colorMap.put(LogLevel.DEBUG, Pair.of(AnsiCode.fg(Color.BLACK), AnsiCode.reset()+NEWLINE));
colorMap.put(LogLevel.INFO, Pair.of(AnsiCode.fg(Color.BLUE), AnsiCode.reset()+NEWLINE));
colorMap.put(LogLevel.WARN, Pair.of(AnsiCode.fg(Color.ORANGERED), AnsiCode.reset()+NEWLINE));
colorMap.put(LogLevel.ERROR, Pair.of(AnsiCode.fg(Color.DARKRED), AnsiCode.reset()+NEWLINE));
} else {
colorMap.put(LogLevel.TRACE, Pair.of("", NEWLINE));
colorMap.put(LogLevel.DEBUG, Pair.of("", NEWLINE));
colorMap.put(LogLevel.INFO, Pair.of("", NEWLINE));
colorMap.put(LogLevel.WARN, Pair.of("", NEWLINE));
colorMap.put(LogLevel.ERROR, Pair.of("", NEWLINE));
}
}

@Override
public void handleEntry(LogEntry entry) {
var esc = brackets.getOrDefault(entry.level(), NO_ESCAPE_SEQUENCES);
out.append(esc.first()).append(String.valueOf(entry)).append(esc.second()).append(NEWLINE);
var colors = colorMap.get(entry.level());
out.append(entry.format(colors.first(), colors.second()));
}

}
Original file line number Diff line number Diff line change
@@ -1,30 +1,51 @@
package com.dua3.utility.logging;

import com.dua3.cabe.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.Marker;
import org.slf4j.event.Level;
import org.slf4j.helpers.MessageFormatter;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.function.Supplier;

/**
* Represents a log entry with information about the log message, time, level, logger, and optional marker and throwable.
*/
public record LogEntry(Logger logger, Instant time, Level level, @Nullable Marker marker, String msg,
@Nullable Object[] arguments, @Nullable Throwable throwable) implements Serializable {
public final class LogEntry {
private final String loggerName;
private final Instant time;
private final LogLevel level;
private final String marker;
private Supplier<String> messageFormatter;
private String formattedMessage;
private final Throwable throwable;

/**
*
*/
public LogEntry(String loggerName, Instant time, LogLevel level, @Nullable String marker, Supplier<String> messageFormatter,
@Nullable Throwable throwable) {
this.loggerName = loggerName;
this.time = time;
this.level = level;
this.marker = marker;
this.messageFormatter = messageFormatter;
this.throwable = throwable;
}

/**
* Formats the message using MessageFormatter.basicArrayFormat.
*
* @return the formatted message as a string.
*/
public String formatMessage() {
return MessageFormatter.basicArrayFormat(msg, arguments);
if (formattedMessage==null) {
formattedMessage = messageFormatter.get();
messageFormatter = null;
}
return formattedMessage;
}

/**
Expand All @@ -48,10 +69,57 @@ public String formatThrowable() {

@Override
public String toString() {
return format("", "");
}

String format(String prefix, String suffix) {
if (throwable() == null) {
return "[%-5s] %s %s\t%s".formatted(level, DateTimeFormatter.ISO_INSTANT.format(time), logger.getName(), formatMessage());
return "%s[%-5s] %s %s\t%s%s".formatted(prefix, level, DateTimeFormatter.ISO_INSTANT.format(time), loggerName, formatMessage(), suffix);
} else {
return "[%-5s] %s %s\t%s%n%s".formatted(level, DateTimeFormatter.ISO_INSTANT.format(time), logger.getName(), formatMessage(), formatThrowable());
return "%s[%-5s] %s %s\t%s%n%s%s".formatted(prefix, level, DateTimeFormatter.ISO_INSTANT.format(time), loggerName, formatMessage(), formatThrowable(), suffix);
}
}

public String loggerName() {
return loggerName;
}

public Instant time() {
return time;
}

public LogLevel level() {
return level;
}

public String marker() {
return marker;
}

public Supplier<String> messageFormatter() {
return messageFormatter;
}

public Throwable throwable() {
return throwable;
}

@Override
public boolean equals(@Nullable Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
var that = (LogEntry) obj;
return Objects.equals(this.loggerName, that.loggerName) &&
Objects.equals(this.time, that.time) &&
Objects.equals(this.level, that.level) &&
Objects.equals(this.marker, that.marker) &&
Objects.equals(this.messageFormatter, that.messageFormatter) &&
Objects.equals(this.throwable, that.throwable);
}

@Override
public int hashCode() {
return Objects.hash(loggerName, time, level, marker, messageFormatter, throwable);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.dua3.utility.logging;

import com.dua3.utility.data.Color;
import com.dua3.utility.io.AnsiCode;

public enum LogLevel {
TRACE(AnsiCode.fg(Color.DARKGRAY), AnsiCode.reset()),
DEBUG(AnsiCode.fg(Color.BLACK), AnsiCode.reset()),
INFO(AnsiCode.fg(Color.BLUE), AnsiCode.reset()),
WARN(AnsiCode.fg(Color.ORANGERED), AnsiCode.reset()),
ERROR(AnsiCode.fg(Color.DARKRED), AnsiCode.reset());

LogLevel(String escStart, String escEnd) {
this.escStart = escStart;
this.escEnd = escEnd;
}

String escStart;
String escEnd;

String colorize(String text, boolean colored) {
return colored ? escStart+text+escEnd : text;
}
}
5 changes: 1 addition & 4 deletions utility-logging/src/main/java/module-info.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,11 @@
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT

import org.slf4j.spi.SLF4JServiceProvider;

open module com.dua3.utility.logging {
exports com.dua3.utility.logging;
provides SLF4JServiceProvider with com.dua3.utility.logging.LoggingServiceProvider;

requires static com.dua3.cabe.annotations;

requires org.slf4j;
requires org.apache.logging.log4j;
requires com.dua3.utility;
}

This file was deleted.

7 changes: 7 additions & 0 deletions utility-logging/utility-logging-slf4j/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
description = "Java utilities (logging)"

dependencies {
implementation(project(":utility"))
implementation(rootProject.libs.slf4j.api)
api(project(":utility-logging"))
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package com.dua3.utility.logging;
package com.dua3.utility.logging.slf4j;

import com.dua3.cabe.annotations.Nullable;
import com.dua3.utility.logging.LogEntry;
import com.dua3.utility.logging.LogEntryHandler;
import com.dua3.utility.logging.LogLevel;
import org.slf4j.Marker;
import org.slf4j.event.Level;
import org.slf4j.helpers.AbstractLogger;
import org.slf4j.helpers.MessageFormatter;
import org.slf4j.spi.LocationAwareLogger;

import java.time.Instant;
import java.util.HashMap;
Expand Down Expand Up @@ -38,7 +43,25 @@ protected String getFullyQualifiedCallerName() {

@Override
protected void handleNormalizedLoggingCall(Level level, @Nullable Marker marker, String messagePattern, @Nullable Object[] arguments, @Nullable Throwable throwable) {
handlers.forEach(handler -> handler.handleEntry(new LogEntry(this, Instant.now(), level, marker, messagePattern, arguments, throwable)));
String markerName = marker != null ? marker.getName() : null;
handlers.forEach(handler -> handler.handleEntry(new LogEntry(name, Instant.now(), translate(level), markerName, () -> MessageFormatter.basicArrayFormat(messagePattern, arguments), throwable)));
}

private LogLevel translate(Level level) {
int levelInt = level.toInt();
if (levelInt < LocationAwareLogger.DEBUG_INT) {
return LogLevel.TRACE;
}
if (levelInt < LocationAwareLogger.INFO_INT) {
return LogLevel.DEBUG;
}
if (levelInt < LocationAwareLogger.WARN_INT) {
return LogLevel.INFO;
}
if (levelInt < LocationAwareLogger.ERROR_INT) {
return LogLevel.WARN;
}
return LogLevel.ERROR;
}

@Override
Expand Down
Loading

0 comments on commit e03b212

Please sign in to comment.