Skip to content

Latest commit

 

History

History
1718 lines (1351 loc) · 67.3 KB

SCRIBE.adoc

File metadata and controls

1718 lines (1351 loc) · 67.3 KB

SmallMind Scribe

Table of Contents

The smallmind-scribe module is a Java logging framework that exists because every non-trivial service ends up fighting the same fight: it picks a logging implementation, commits its source to that implementation’s API, and then discovers, later, that the shape of the implementation no longer matches what the service needs — either because a library upstream prefers SLF4J, a downstream deployment wants java.util.logging, an infrastructure team wants everything routed through Log4J, or an operator wants log events shipped to Fluent Bit, CloudWatch, syslog, and email digests at the same time.

Scribe’s response is to draw a hard line between the logging contract that application code is written against and the logging implementation that actually publishes records. The application writes against a small, stable Logger class. The implementation is selected at classpath assembly time — java.util.logging, Log4J 2, SLF4J, Apache Commons Logging, or Scribe’s own "indigenous" backend — and swapping implementations requires changing one dependency, not one line of application code.

The framework is organized as four independently publishable artifact sets:

  • scribe-pen — the contract and the toolkit. Defines Logger, Level, Record, Template, Appender, Filter, Formatter, Enhancer, the rollover and cleanup machinery, and the Spring integration beans. This is the artifact every other Scribe artifact depends on, and the artifact that application code writes against.

  • scribe-ink — backend implementations of the LoggingBlueprint SPI. Three sub-artifacts: scribe-ink-indigenous (Scribe’s own in-process backend), scribe-ink-jdk (routes through java.util.logging), and scribe-ink-log4j (routes through Log4J 2 directly, with additivity disabled).

  • scribe-slf4j — an SLF4J provider binding that installs Scribe as the backend for org.slf4j.Logger calls. Lets libraries that log through SLF4J flow into the same appender/template pipeline as code written directly against Scribe.

  • scribe-apache — a Commons Logging bridge that satisfies org.apache.commons.logging.Log by delegating to Scribe, for legacy libraries that have not moved off JCL.

The module is deliberate about where it draws its boundaries. It owns the Logger API, the record pipeline (filters, enhancers, appenders), the formatter and template system, the file rollover and cleanup policies, and the dispatch fan-out to backends. It does not own the process of choosing a backend — that is a classpath decision, enforced by a ServiceLoader-based LoggingBlueprint discovery contract that requires exactly one implementation present at class-load time.

There are many fine Java logging frameworks available, but this deciison is one often made by libraries that foist those decisions on their clients. You add SLF4J because the library you imported needed it. You add Log4J because the platform team standardized on it. You add java.util.logging because the Servlet container used it. Years later you have three logging frameworks, two bridges, a logback.xml, a log4j2.xml, and a logging.properties, and no single configuration surface. Scribe takes a different shape:

  1. One API, selected once. Application code writes against org.smallmind.scribe.pen.Logger. The LoggingBlueprint implementation discovered on the classpath decides how records are actually published. Swapping backends changes the dependency, not the code.

  2. One pipeline for configuration. Appenders, filters, enhancers, and templates live in the scribe-pen package regardless of backend. A ConsoleAppender is a ConsoleAppender whether the active backend is indigenous, JDK, or Log4J.

  3. One set of formatters. The PatternFormatter language (%d %n %+5l [%T] - %m) works identically everywhere. The XMLFormatter and MessagePackFormatter options are available to every appender that understands a Formatter.

  4. One template system for live configuration. A registered Template is a live configuration object: mutating its level or its appender list propagates immediately to every logger it matches. There is no restart, no reload, no file-watch.

  5. Dynamic logger-to-template matching. When a new template is registered or an existing one is removed, every logger re-runs template matching and the highest-priority matching template wins. Loggers that were previously governed by a catch-all can be re-governed by a more specific template mid-process.

  6. Caller context is first-class. Every record can carry a LoggerContext — the fully qualified class, method name, file name, line number, and native-method flag of the call site. Capture is opt-in (the autoFillLoggerContext flag) because a stack walk is not free.

  7. Async dispatch is a wrapping decorator, not a flag. AsynchronousAppender wraps any other Appender and decouples the caller thread from I/O. Buffer size and worker count are explicit constructor arguments, not implicit defaults hidden in config.

  8. File rollover and cleanup are composable rule sets, not a parser. A Rollover holds zero or more RolloverRule instances (FileSizeRolloverRule, TimestampRolloverRule); a Cleanup holds zero or more CleanupRule instances (FileCountCleanupRule, LastModifiedCleanupRule). No magic strings, no implicit policy.

  9. The parameter order is fixed: throwable first, then message, then natural varargs. logger.error(ex, "failed for %s", id) is a single, unambiguous call. SLF4J, Log4J, JUL, and Commons Logging all place the Throwable last, which collides with trailing varargs — SLF4J papers over it with a placeholder-counting convention that silently breaks when a {} is added; older Log4J APIs require an Object[] cast; JUL forces distinct method names. Scribe makes the common case (exception plus formatted message plus arguments) a single varargs call with no conversion, no ambiguity, and no wrapper array.

  10. Expensive messages are lazy without an isDebugEnabled guard. Every level has a Supplier<String> overload (lambdas) and a plain Object overload whose toString() is only invoked if the record will actually be published. That removes the if (logger.isDebugEnabled()) { logger.debug(expensiveToString()); } pattern that is endemic in codebases using other frameworks: wrap the expensive work in a lambda or a holder’s toString() and the framework defers the work for you.

  • Defines the user-facing Logger class with per-level convenience methods (trace, debug, info, warn, error, fatal) plus generic log(Level, …​) overloads, each available in six shapes: throwable-only, printf-style message, throwable + message, object (toString), lazy Supplier<String>, and throwable + supplier.

  • Caches loggers statically (LoggerManager.getLogger) using double-checked locking and associates each with the highest-priority matching template.

  • Dispatches through a LoggingBlueprint SPI discovered via ServiceLoader, so the backend is a classpath decision enforced at class-load time (exactly one implementation required; zero or many throws StaticInitializationError).

  • Publishes records through a pipeline of filters (veto points) and enhancers (mutation points) before fanning out to a set of Appender instances.

  • Carries Parameter key/value pairs per logger (MDC-equivalent), retrievable by the %p pattern token in formatter output.

  • Publishes via a pattern-driven PatternFormatter with 13 conversion tokens and a syntax (headers, footers, padding, precision, multi-line prefixes) that covers the common cases without scripting.

  • Writes to files with rotation and cleanup through FileAppender + Rollover
    Cleanup, atomically renaming the active file on rollover and invoking the cleanup pass afterward.

  • Decouples callers from I/O with AsynchronousAppender, a decorator that buffers records in a LinkedBlockingQueue and drains via daemon worker threads.

  • Registers live-updating configuration via Template.register(), so changes to a registered template propagate immediately to every logger it governs — no restart.

  • Exposes Spring factory beans (DateTimeFormatterFactoryBean, TemplateInitializingBean, DynamicClassNameTemplateInitializingBean, ExceptionSuppressingLogInitializingBean) and a LoggingPlan family (ConsoleLoggingPlan, FileLoggingPlan, FluentBitLoggingPlan) that wrap a concrete appender in AsynchronousAppender, install a DefaultTemplate, and register per-class overrides from a simple Log[] list.

  • Ships backend adapters (scribe-ink-indigenous, scribe-ink-jdk, scribe-ink-log4j) and front-end bridges (scribe-slf4j, scribe-apache) so that Scribe can be dropped into services whose library ecosystem already standardized on SLF4J or Commons Logging, and whose deployment environment expects events to surface in a specific backend.

  • It does not parse logging configuration files. Configuration is Java or Spring: build a Template, call register(), move on. There is no scribe.xml or scribe.properties parser.

  • It does not support multiple active backends. The LoggingBlueprint contract requires exactly one implementation on the classpath. If multiple META-INF/services/ entries for LoggingBlueprint exist, the framework fails fast at class load time.

  • It does not attempt to detect backend selection dynamically. The backend is chosen when the artifact set is assembled, not at runtime.

  • It does not provide a REST or web admin console. The live-update path is the Template API.

  • It does not replace MDC semantics — the Parameter machinery intentionally mirrors MDC, but is exposed through Logger.putParameter(key, value) and rendered through the %p pattern token rather than the SLF4J MDC API. The scribe-slf4j binding routes SLF4J’s MDC writes to the same parameter store.

Three audiences typically land on this document. Each wants a different path through it.

First-time adopter. You have never used Scribe. Read At A Glance, Installation, and Quick Start. Write a throwaway class that constructs a Logger, logs at several levels, and registers a DefaultTemplate pointing at a ConsoleAppender. Then come back to Conceptual Model.

Library author. You are writing a reusable library that should log, but you do not want to force a backend on your downstream callers. Depend only on scribe-pen, write against org.smallmind.scribe.pen.Logger, and register no templates. Your downstream callers will add the backend artifact and register their own templates. Read Conceptual Model, Logger API, and Parameters And Context.

Application author. You run the process. You decide which backend, which appenders, which templates, which rollover policies. Read Installation, Appenders, Templates And Live Configuration, Rollover And Cleanup, and Spring Integration.

Backend integrator. You are running on an existing infrastructure (a Servlet container with JUL, a legacy service using Log4J, a fleet that ships logs via SLF4J bindings). Read Backend Ink Packages and SLF4J Binding to understand which Scribe artifact to add.

I want to…​ Read…​ Code hook

Log a message at DEBUG

Logger API

LoggerManager.getLogger(MyClass.class).debug("msg %s", arg)

Send logs to a file with rotation and cleanup

Rollover And Cleanup

FileAppender + Rollover + Cleanup

Run appender I/O off the logging thread

Asynchronous Appender

Wrap appender in new AsynchronousAppender(delegate, buffer, workers)

Configure a group of loggers by class name pattern

Templates

new ClassNameTemplate(Level.DEBUG, true, "com.example.*", appender).register()

Change log level at runtime without restart

Templates

Call template.setLevel(Level.TRACE) on a registered template

Route Log4J-coded library output through Scribe pipeline

Backend Ink Packages

Add scribe-ink-log4j as the sole blueprint artifact

Route SLF4J-coded library output through Scribe pipeline

SLF4J Binding

Add scribe-slf4j; SLF4J discovery binds automatically

Attach MDC-like context to log records

Parameters And Context

logger.putParameter("requestId", id)

Wire everything from Spring XML

Spring Integration

ConsoleLoggingPlan, FileLoggingPlan, or FluentBitLoggingPlan

Scribe is a Maven-published multi-module project. Every dependency in this section assumes ${project.version} resolves to the SmallMind version you build against.

A library that should log but should not impose a backend on downstream callers depends only on scribe-pen.

<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>scribe-pen</artifactId>
  <version>${project.version}</version>
</dependency>

Module name (for requires): org.smallmind.scribe.pen

With scribe-pen alone, LoggingBlueprintFactory will fail at class-load time because no LoggingBlueprint is discovered. That is the correct shape for a library jar: downstream applications supply the blueprint.

An application must additionally choose exactly one backend. The three shipped backends are the three scribe-ink-* artifacts:

<!-- Scribe's own in-process backend -->
<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>scribe-ink-indigenous</artifactId>
  <version>${project.version}</version>
</dependency>

<!-- OR: route through java.util.logging -->
<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>scribe-ink-jdk</artifactId>
  <version>${project.version}</version>
</dependency>

<!-- OR: route through Log4J 2 -->
<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>scribe-ink-log4j</artifactId>
  <version>${project.version}</version>
</dependency>
Artifact Module name

scribe-ink-indigenous

org.smallmind.scribe.ink.indigenous

scribe-ink-jdk

org.smallmind.scribe.ink.jdk

scribe-ink-log4j

org.smallmind.scribe.ink.log4j

Important

Only one scribe-ink-* artifact may be on the classpath. LoggingBlueprintFactory discovers blueprints via ServiceLoader and fails fast if it finds zero or more than one.

If the application (or any library in its closure) already logs through SLF4J or Apache Commons Logging, add the matching bridge so those calls flow into the Scribe pipeline.

<!-- SLF4J provider binding: org.slf4j.Logger calls route to Scribe -->
<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>scribe-slf4j</artifactId>
  <version>${project.version}</version>
</dependency>

<!-- Commons Logging bridge: org.apache.commons.logging.Log delegates to Scribe -->
<dependency>
  <groupId>org.smallmind</groupId>
  <artifactId>scribe-apache</artifactId>
  <version>${project.version}</version>
</dependency>
Artifact Module name

scribe-slf4j

org.smallmind.scribe.slf4j

scribe-apache

org.smallmind.scribe.apache

Several appenders and formatters rely on optional dependencies that scribe-pen declares as optional. An application that uses them must explicitly depend on them:

Feature Required runtime dependencies

AWSAppender (CloudWatch Logs)

software.amazon.awssdk:auth, aws-core, cloudwatchlogs, regions

SyslogAppender

org.syslog4j:syslog4j

FluentBitAppender + MessagePackFormatter

org.msgpack:jackson-dataformat-msgpack, which brings the Jackson 2 artifacts com.fasterxml.jackson.core:jackson-core and jackson-databind that these classes use

EmailAppender

The Jakarta Mail dependencies of smallmind-nutsnbolts’s `Postman: jakarta.mail:jakarta.mail-api plus a Jakarta Mail runtime, and jakarta.activation:jakarta.activation-api

LevelEnumXmlAdapter (JAXB binding of Level)

jakarta.xml.bind:jakarta.xml.bind-api

Spring bean support (LoggingPlan, factory beans)

org.springframework:spring-beans

Every Scribe artifact ships an explicit module descriptor under the names in the tables above. On the classpath the descriptors are ignored. The repository-wide rules are in Module Path And Classpath; this section lists what is specific to Scribe. It covers scribe-pen first, then the backends and bridges.

Required modules. The descriptor exports all six packages and re-exports org.smallmind.nutsnbolts (requires transitive).

Optional modules. Every dependency in the table above is requires static, and none of them is re-exported. On the module path, a module you use must be resolved by your own requires or by --add-modules; its jar being present is not enough. @Nullable from JSpecify, which arrives with Spring, is also requires static; it is needed only to compile against DateTimeFormatterFactoryBean.

Artifact Module name Kind

com.fasterxml.jackson.core:jackson-core

com.fasterxml.jackson.core

explicit

com.fasterxml.jackson.core:jackson-databind

com.fasterxml.jackson.databind

explicit

jakarta.activation:jakarta.activation-api

jakarta.activation

explicit

jakarta.xml.bind:jakarta.xml.bind-api

jakarta.xml.bind

explicit

org.jspecify:jspecify

org.jspecify

explicit

org.msgpack:jackson-dataformat-msgpack

jackson.dataformat.msgpack

derived

org.syslog4j:syslog4j

syslog4j

derived

software.amazon.awssdk:auth

software.amazon.awssdk.auth

automatic

software.amazon.awssdk:aws-core

software.amazon.awssdk.awscore

automatic

software.amazon.awssdk:cloudwatchlogs

software.amazon.awssdk.services.cloudwatchlogs

automatic

software.amazon.awssdk:regions

software.amazon.awssdk.regions

automatic

org.springframework:spring-beans

spring.beans

automatic

A derived name is not declared by the jar at all: the JVM derives it from the file name, so jackson-dataformat-msgpack-0.9.11.jar becomes jackson.dataformat.msgpack and syslog4j-0.9.30.jar becomes syslog4j. Renaming either jar changes its module name; org.smallmind.scribe.pen then no longer reads it, and the appender that uses it fails on first use. Keep the Maven file names.

Packages this module opens. org.smallmind.scribe.pen, org.smallmind.scribe.pen.spring, and org.smallmind.scribe.pen.spring.plan are opened to spring.core and spring.beans, because appenders, formatters, and logging plans are configured from Spring XML.

Services. The descriptor declares uses org.smallmind.scribe.pen.adapter.LoggingBlueprint, so LoggingBlueprintFactory can discover backends on the module path.

Backends. Each scribe-ink-* module declares provides org.smallmind.scribe.pen.adapter.LoggingBlueprint with … next to its META-INF/services file, and re-exports org.smallmind.scribe.pen. Putting the backend jar on the module path is enough: because org.smallmind.scribe.pen uses the service, the JVM adds the backend module to the module graph without any requires. The one-backend rule applies on the module path as it does on the classpath. scribe-ink-jdk also re-exports java.logging, and scribe-ink-log4j re-exports org.apache.logging.log4j and org.apache.logging.log4j.core.

SLF4J bridge. org.smallmind.scribe.slf4j declares provides org.slf4j.spi.SLF4JServiceProvider with org.smallmind.scribe.slf4j.ScribeSLF4JServiceProvider and re-exports org.slf4j and org.smallmind.scribe.pen. SLF4J 2 finds providers on the module path only through provides, and the JVM binds this one as soon as org.slf4j is in the module graph; no requires is needed.

Commons Logging bridge. Commons Logging finds CommonsLogWrapper through the commons-logging.properties file at the root of scribe-apache, not through a service, so nothing pulls org.smallmind.scribe.apache into the module graph. Require it in your own descriptor, or add it with --add-modules org.smallmind.scribe.apache. Without it, Commons Logging silently falls back to its java.util.logging adapter (Jdk14Logger). As on the classpath, if org.slf4j is in the module graph, Commons Logging routes through SLF4J instead, which reaches Scribe when scribe-slf4j is present. The module re-exports org.apache.commons.logging.

Artifact Contents

scribe-pen

Core API: Logger, Level, Record, Parameter, Template, Appender, Filter, Formatter, Enhancer, Rollover, Cleanup, Timestamp, adapter SPI, Spring beans and plans. All other artifacts depend on this.

scribe-ink-indigenous

IndigenousLoggingBlueprint — Scribe’s own backend. Zero runtime coupling to any external logging framework.

scribe-ink-jdk

JDKLoggingBlueprint — routes every Scribe record through java.util.logging. Use when operating environment expects JUL-shaped output.

scribe-ink-log4j

Log4JLoggingBlueprint — routes every Scribe record through Log4J 2 directly (additivity disabled). Use when the deployment standardizes on Log4J.

scribe-slf4j

ScribeSLF4JServiceProvider, ScribeLoggerFactory, ScribeLoggerAdapter, ScribeMDCAdapter — registers Scribe as SLF4J’s backend so org.slf4j.Logger calls flow into the Scribe pipeline.

scribe-apache

CommonsLogWrapper — a Commons Logging Log implementation that delegates to Scribe.

A small number of terms carry most of the framework’s behavior.

Logger

The caller-facing object obtained from LoggerManager.getLogger(name) or LoggerManager.getLogger(Class). Holds a LoggerAdapter that the active LoggingBlueprint produced. Methods like info(message) delegate to the adapter, which constructs a Record, runs enhancers, evaluates filters, and fans the record out to appenders.

Level

An ordered enum — TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. A logger has an active level; records below it are dropped before appenders ever see them. OFF suppresses all output. Level comparisons use atLeast(Level) and noGreater(Level).

Record

An immutable-ish structured snapshot of a single log event: logger name, level, message, optional Throwable, Parameter[], LoggerContext, thread id, thread name, wall-clock millis, monotonic sequence number. Appenders and formatters operate on Record<?> instances; pattern conversions translate record fields into output text.

LoggerContext

A call-site snapshot — class name, method, file, line, native flag. Resolved by walking Thread.currentThread().getStackTrace() and skipping any frame whose class matches a registered logging package prefix. Capture is opt-in because a stack walk has a cost.

Template

A registered piece of configuration that claims jurisdiction over a set of loggers. Subclasses override matchLogger(String loggerName) to return a non-negative priority for logger names they claim, or Template.NO_MATCH (-1) for logger names they do not. When multiple registered templates match a logger, the one with the highest priority wins. Changes to the template’s level, appender list, filter list, or enhancer list propagate immediately to every governed logger.

LoggingBlueprint

A ServiceLoader-discovered class that produces LoggerAdapter instances. Exactly one implementation must be on the classpath; Scribe enforces this at class-load time. The blueprint decides the shape of records (Scribe-native, JUL, Log4J) and the dispatch mechanics.

Appender

A terminal sink for records. Implements publish(Record<?>). Concrete sinks include console, file (with rollover), async (a decorator), AWS CloudWatch, email, syslog, and Fluent Bit. Each appender may carry its own filter list and ErrorHandler.

Filter

A veto point with a single method — willLog(Record<?>). Applied in order; any filter returning false drops the record.

Enhancer

A mutation point. Runs against each record before appenders are invoked. Typical use: attach a hostname, a request id, or a derived field.

Formatter

A function Record<?> → String. PatternFormatter is the default; XMLFormatter and MessagePackFormatter are available. Appenders that write text (console, file, email, Fluent Bit) accept a Formatter.

Parameter

A (String key, Serializable value) pair attached to a logger. Appears on every record that logger emits. Rendered by the %p token in pattern output. Conceptually equivalent to MDC; the scribe-slf4j binding routes SLF4J’s MDC writes through the same machinery.

The smallest useful Scribe setup is: one template, one appender, one call.

import org.smallmind.scribe.pen.ConsoleAppender;
import org.smallmind.scribe.pen.DefaultTemplate;
import org.smallmind.scribe.pen.Level;
import org.smallmind.scribe.pen.Logger;
import org.smallmind.scribe.pen.LoggerManager;
import org.smallmind.scribe.pen.PatternFormatter;

public class Example {

  public static void main (String[] args) {

    ConsoleAppender console = new ConsoleAppender(
      new PatternFormatter("%d %+5l [%T] %n - %m")        (1)
    );

    new DefaultTemplate(Level.INFO, true, console).register();   (2)

    Logger logger = LoggerManager.getLogger(Example.class);       (3)
    logger.info("starting up");
    logger.debug("this line is suppressed at INFO");
    logger.error(new IllegalStateException("boom"), "shutting down with %s", "error");
  }
}
  1. Build a pattern formatter: ISO date, right-padded 5-char level, thread name, logger name, message.

  2. Build a DefaultTemplate at level INFO with context-capture enabled, attach the appender, register it. Any logger created after this point, whose name matches the DefaultTemplate (which matches everything at the lowest non-zero priority), inherits this configuration.

  3. Obtain a cached logger by class. Subsequent calls to LoggerManager.getLogger(Example.class) return the same instance.

The resulting output line shape (with the default pattern) is:

2026-04-22T09:17:42.103-0400 org.smallmind.Example   INFO [main] - starting up

A library should obtain a logger and log. It should not register templates, choose backends, or install appenders — those are the application’s job. The library simply depends on scribe-pen and writes this:

package com.example.mylib;

import org.smallmind.scribe.pen.Logger;
import org.smallmind.scribe.pen.LoggerManager;

public class MyService {

  private static final Logger LOGGER = LoggerManager.getLogger(MyService.class);

  public void doWork (String id) {

    LOGGER.debug("starting work for %s", id);
    try {
      // ...
    } catch (Exception ex) {
      LOGGER.error(ex, "failed to process %s", id);
    }
  }
}

A library whose callers may prefer SLF4J can write against org.slf4j.Logger normally. If the assembled application has scribe-slf4j on its classpath and a scribe-ink-* backend, those SLF4J calls route through the Scribe pipeline without any code change.

org.smallmind.scribe.pen.Logger is the primary user-facing class. It is normally obtained from LoggerManager.getLogger(…​), which caches one instance per name.

// Preferred: cached lookup by class
Logger logger = LoggerManager.getLogger(MyService.class);

// Cached lookup by arbitrary name
Logger logger = LoggerManager.getLogger("com.example.custom");

// Direct construction (rarely needed; bypasses caching and template matching)
Logger logger = new Logger(MyService.class);

The Logger exposes six convenience methods per level (trace, debug, info, warn, error, fatal). Each level supports the same six shapes:

logger.debug(throwable);                              // throwable only
logger.debug("items processed: %d", count);           // printf message
logger.debug(throwable, "failed at step %s", step);   // throwable + message
logger.debug(somePojo);                               // toString() of an object
logger.debug(() -> expensivelyBuiltString(state));    // lazy supplier
logger.debug(throwable, () -> explain(error));        // lazy supplier + throwable

Scribe deliberately places the Throwable first when both a throwable and a message are supplied — debug(Throwable, String, Object…​) — rather than last, as SLF4J, Log4J, JUL, and Commons Logging all do. This is a direct fix for a long-standing ergonomic failure in the other frameworks.

With a trailing Throwable, the compiler has no way to distinguish the trailing exception from a trailing varargs entry. In SLF4J the rule is "if the last argument is a Throwable and there is no placeholder for it, the framework uses it as the throwable" — a convention that depends on placeholder counting and routinely breaks when a developer adds one more {} to the message template. Log4J pre-2.x did not support varargs with a throwable at all; callers with an exception and a printf-formatted message had to pre-build the message string or pass a manually constructed Object[].

Scribe’s parameter order lets the Object…​ args trailing parameter stay natural varargs in every call shape:

// Clean varargs, throwable unambiguous:
logger.error(ex, "failed to process %s for tenant %s", id, tenantId);

// vs. what most frameworks force — either wrap the args in an array...
// or worse, rely on placeholder counting:
other.error("failed to process {} for tenant {}", id, tenantId, ex);   // SLF4J convention

The Scribe shape is also consistent with the generic log(Level, Throwable, …​) overloads: every method that takes a throwable takes it first, and every method that takes a message takes it after the throwable.

Scribe offers two ways to defer the cost of constructing a message until the framework has decided the record will actually be published. Neither requires guarding the call with if (logger.isDebugEnabled()).

Lambda / Supplier<String>. Every level method has an overload that accepts Supplier<String> (and a second that accepts Throwable + Supplier<String>). The supplier is invoked only if the record passes the level check.

// serializeForDebug is potentially expensive; never runs at INFO or above
logger.debug(() -> "state snapshot: " + serializeForDebug(largeObject));

Object overload with a custom toString(). Every level method also has an overload that accepts a plain Object. Scribe does not call toString() on the object unless the record will be published. That lets a caller pass a thin holder whose toString() performs the expensive work:

// A holder whose toString() is only executed if the record survives filtering
logger.debug(new Object() {
  @Override public String toString () {
    return serializeForDebug(largeObject);
  }
});

The practical upshot: code written against Scribe almost never needs the if (logger.isDebugEnabled()) { logger.debug(expensive()); } idiom that is pervasive in SLF4J / Log4J / JUL codebases. Wrap the expensive work in a lambda or a holder’s toString() and Scribe does the level check at the right moment — once, inside the framework, after any logger-level Filter has already vetoed the record.

Note

The Supplier and Object overloads perform the suppression check at the logger level before the supplier runs or toString() is invoked. They do not defer past appender-scoped filters — if an appender-attached Filter is the reason the record gets dropped, the message has already been materialized. In practice this matters only when an expensive construction is paired with an appender-scoped filter; the common case of "level too low" is fully lazy.

The same shapes also exist on a generic log(Level, …​). When level is null the logger’s own current level is used.

logger.log(Level.INFO, "raw log");
logger.log(null, ex, "logs at the logger's current level");

Logger.putParameter(key, value) stores a serializable value on the logger-scoped parameter adapter. Every subsequent record carries these parameters; the %p pattern token renders them.

logger.putParameter("requestId", requestId);
logger.putParameter("tenant", tenantId);
try {
  logger.info("handling request");
} finally {
  logger.clearParameters();
}
Note

The Parameter store semantics (per-thread versus per-logger) are defined by the active LoggingBlueprint’s `ParameterAdapter implementation. In typical usage under the indigenous backend, parameter lifetime matches the Logger instance rather than the calling thread — clearParameters() after a request is a standard pattern.

Method Meaning

getName()

Logger name (the class canonical name or the explicit string passed at construction).

getLevel() / setLevel(Level)

The logger’s level threshold. Records below this level are dropped before enhancers or appenders see them. setLevel(null) throws IllegalArgumentException.

getAutoFillLoggerContext() / setAutoFillLoggerContext(boolean)

Whether records produced by this logger automatically capture the call-site LoggerContext. Off by default — a stack walk is not free.

addAppender(Appender) / clearAppenders()

Manage appenders attached directly to this logger. Templates usually manage appenders instead; use direct installation only for one-off cases.

addFilter(Filter) / clearFilters()

Manage filters attached directly to this logger.

addEnhancer(Enhancer) / clearEnhancers()

Manage enhancers attached directly to this logger.

getTemplate()

The Template currently governing this logger, or null if none matches.

Level Ordinal Typical use

TRACE

0

Extremely verbose trace output; usually disabled in production.

DEBUG

1

Diagnostic output useful during development and targeted debugging.

INFO

2

Normal operational events — service startup, major state changes.

WARN

3

Events that are not errors but warrant attention — degraded responses, retries.

ERROR

4

Failures that prevented a specific operation from completing.

FATAL

5

Failures that compromise service viability.

OFF

6

Suppresses all output. Threshold check at this level rejects every record.

Two comparison methods:

Level.ERROR.atLeast(Level.INFO);      // true: ERROR is at or above INFO
Level.DEBUG.noGreater(Level.INFO);    // true: DEBUG is no more severe than INFO

Every published log event flows through an ordered pipeline:

Logger.info(...)
   -> LoggerAdapter.logMessage(level, throwable, message, args)
      -> threshold check: level.atLeast(logger.getLevel())?
         -> construct Record (from active blueprint)
            -> run Enhancer[] in order (mutation)
               -> evaluate Filter[] in order (veto)
                  -> for each Appender: Appender.publish(record)
                     -> per-appender Filter[]
                        -> AbstractFormattedAppender: format with Formatter
                           -> handleOutput(text)

The filter chain appears at two points: on the logger (checked once, before any appender is involved) and on each appender (checked per-appender, after logger-level filters pass). The enhancer chain mutates records once, before any appender runs.

Accessible through Record<?> accessors, and available to pattern tokens:

Field Pattern Meaning

loggerName

%n

Logger name; .precision trims to last N dot-segments.

level

%l

Level enum name.

message

%m

Fully formatted message text.

throwable

(part of %s)

Attached exception, if any.

parameters

%p

Parameter key/value pairs; multi-line; supports !prefix!.

loggerContext

%C, %M, %F, %L, %N

Call-site class, method, file, line, native flag.

threadName

%T

Thread name.

sequenceNumber

(none)

Monotonic sequence per process.

millis

%t

Wall-clock epoch millis.

millis (formatted)

%d

Formatted via the active Timestamp.

An Appender is the terminal sink for a record. The following ship in scribe-pen:

Writes formatted output to System.out, synchronized so concurrent callers never interleave characters.

ConsoleAppender console = new ConsoleAppender(
  new PatternFormatter("%d %+5l [%T] %n - %m")
);
console.setErrorHandler(new DefaultErrorHandler());

Writes formatted output to a file. Optionally rolls over and optionally cleans up old archives after each rollover. The path must be set before the first write (either via a constructor or setLogPath(Path) / setLogFile(String)).

Rollover rollover = new Rollover();
rollover.setRules(new RolloverRule[] {
  new FileSizeRolloverRule(100, FileSizeQuantifier.MEGABYTES),  (1)
  new TimestampRolloverRule(TimestampQuantifier.TOP_OF_HOUR)    (2)
});

Cleanup cleanup = new Cleanup();
cleanup.setRules(new CleanupRule[] {
  new FileCountCleanupRule(10),                                 (3)
  new LastModifiedCleanupRule(14)                               (4)
});

FileAppender file = new FileAppender(
  Paths.get("/var/log/myservice/app.log"),
  rollover,
  cleanup,
  new PatternFormatter(),
  new DefaultErrorHandler()
);
  1. Roll over when the active file exceeds 100 MB.

  2. Also roll over at the top of every hour.

  3. After rollover, keep at most the ten most recent archives.

  4. Also delete any archive older than fourteen days.

On rollover, the current file is closed, renamed to a unique archive path generated by FileNameUtility.calculateUniquePath(…​) (active base name + separator + timestamp suffix + disambiguating index), a fresh append-mode stream is opened, and the cleanup pass is invoked.

A decorator that wraps any other appender and drains records from a LinkedBlockingQueue on daemon worker threads. Use it to keep the calling thread out of I/O blocking.

Appender raw = new FileAppender(Paths.get("/var/log/app.log"), rollover);
AsynchronousAppender async = new AsynchronousAppender(raw, 2_000, 4);  (1)
  1. Buffer up to 2,000 records in the queue; drain with 4 worker threads.

The three-argument constructor’s buffer size and concurrency limit default to 1 each when not supplied. The wrapped appender receives close() only after the queue drains.

Sends records to AWS CloudWatch Logs. Requires the AWS SDK optional dependencies (auth, aws-core, cloudwatchlogs, regions). Credentials and region are resolved through the default AWS provider chain unless overridden via CloudWatchLogsClientFactory.

Buffers records and periodically dispatches them as email digests. Configured with SMTP host, from, to, subject.

Routes records to a syslog daemon over UDP or TCP. Requires org.syslog4j:syslog4j.

Sends records to a Fluent Bit collector in MessagePack format. Configured with host, port, and tag. Requires the msgpack jackson dataformat dependency.

Extend AbstractAppender (record-based output) or AbstractFormattedAppender (text output after formatting). Override handleOutput(Record<?>) or handleOutput(String) respectively.

public class CountingAppender extends AbstractFormattedAppender {

  private final AtomicLong count = new AtomicLong();

  @Override
  public void handleOutput (String formatted) {
    count.incrementAndGet();
    // ...dispatch...
  }
}

A Formatter converts a Record to a string. PatternFormatter is the default.

A pattern is a sequence of literal text and conversion tokens. A conversion token has the shape:

[{header}]%[<+|->width][.precision][!(+|-)prefix!]conversion[footer}]

{header} and footer} are literal text emitted only when the converted field is non-empty. width with ` right-pads, `-` left-pads. `.precision` trims dot-notation fields to the last N segments (logger name, class name) or limits multi-line fields to the first N lines (parameters). `!(|-)prefix! specifies a line-prefix used for multi-line fields; + includes the first line, - excludes it.

Token Field

%d

Date/time via the active Timestamp (default: yyyy-MM-dd’T’HH:mm:ss.SSSZ).

%t

Epoch milliseconds as a long.

%n

Logger name.

%l

Level name.

%m

Formatted message text.

%T

Thread name.

%C

Call-site class name (requires autoFillLoggerContext or explicit capture).

%M

Call-site method.

%N

true / false for whether the method is native.

%L

Call-site line number.

%F

Call-site file name.

%s

Stack trace of the attached throwable (multi-line).

%p

Attached Parameter[] (multi-line).

%%

A literal percent sign.

// Default compact pattern
new PatternFormatter();
// "%d %n %+5l [%T] - %m"

// Include file/method/line and render parameters as a comma-separated suffix
new PatternFormatter(
  "%d %+5l (%F.%M:%L) [%T] - %m%!+\n\t!p%!+\n\t!s"
);

// Trim the logger name to the last two segments
new PatternFormatter("%d %+5l %.2n - %m");
// For logger "com.example.mylib.service.Widget" renders "service.Widget"

The %d token is rendered through a Timestamp. Two implementations ship:

  • DateFormatTimestamp — java.time.DateTimeFormatter-based; construction accepts a pattern string (yyyy-MM-dd’T’HH:mm:ss.SSSZ by default).

  • NullTimestamp — renders an empty string.

  • XMLFormatter — emits a JAXB-serialized XML representation of each record.

  • org.smallmind.scribe.pen.fluentbit.MessagePackFormatter — emits MessagePack binary frames suitable for Fluent Bit ingestion.

A Template is a live configuration object. Registered templates match loggers and continuously project their level, filter list, appender list, and enhancer list onto every matched logger.

DefaultTemplate

Matches every logger name with the lowest non-zero priority (NO_MATCH + 1). Used as a catch-all. When no ClassNameTemplate matches, DefaultTemplate wins.

ClassNameTemplate

Matches logger names against a dot-notation pattern evaluated by org.smallmind.nutsnbolts.util.DotNotation. Patterns like com.example., com..service.*, or exact com.example.Widget are supported. More specific matches score higher.

RegExTemplate

Matches logger names against a Java regex.

PersonalizedTemplate

Allows callers to supply their own match logic.

ClassNameTemplate noisyThirdParty = new ClassNameTemplate(
  Level.WARN, false, "org.thirdparty.chatty.*", consoleAppender
);
noisyThirdParty.register();

Registration has two effects:

  1. All currently cached loggers re-run template matching. If noisyThirdParty has the highest priority for a logger, that logger is reconfigured in place.

  2. Any logger created later that matches this template inherits its configuration.

After register(), setter calls propagate:

noisyThirdParty.setLevel(Level.TRACE);                // all matched loggers now at TRACE
noisyThirdParty.addAppender(additionalAppender);      // all matched loggers gain appender
noisyThirdParty.removeAppender(consoleAppender);      // all matched loggers lose appender

When multiple registered templates match a logger, LoggerManager picks the one whose matchLogger(String) returns the highest value. DefaultTemplate always returns NO_MATCH + 1 (lowest non-zero priority), so any more specific template wins.

// Catch-all at INFO
new DefaultTemplate(Level.INFO, true, consoleAppender).register();

// Our own code at DEBUG
new ClassNameTemplate(
  Level.DEBUG, true, "com.example.*", consoleAppender, fileAppender
).register();

// One noisy dependency at WARN
new ClassNameTemplate(
  Level.WARN, false, "org.chattylib.*", consoleAppender
).register();

// A specific tracer at TRACE
new ClassNameTemplate(
  Level.TRACE, true, "com.example.debug.Tracer", consoleAppender, fileAppender
).register();

A filter vetoes records via boolean willLog(Record<?>). Filters attached to a logger are checked once; filters attached to an appender are checked again per appender. Any filter returning false drops the record at that scope.

Shipped filters:

  • LevelFilter — allows records at or above a threshold. Combines usefully with a lower-threshold logger plus a higher-threshold appender.

  • DotNotatedLoggerNameFilter — accepts or rejects records by dot-notation match against the logger name.

  • ExceptionSuppressingLogFilter — rejects records whose message or stack trace matches configured substrings. Useful to silence known-but-harmless exceptions from third-party libraries.

ExceptionSuppressingLogFilter suppress = new ExceptionSuppressingLogFilter();
suppress.setSuppressed(new String[] {
  "ClientAbortException",
  "java.io.IOException: Broken pipe"
});
logger.addFilter(suppress);

An enhancer mutates each record before appenders run. Typical use: attach an environmental field.

public class HostEnhancer implements Enhancer {
  private final String host = InetAddress.getLocalHost().getHostName();

  @Override
  public void enhance (Record<?> record) {
    // attach host as a parameter; the exact API depends on ParameterAwareRecord
    record.getParameterAdapter().put("host", host);
  }
}

File rollover is controlled by a Rollover which aggregates zero or more RolloverRule instances. Cleanup of old archives after rollover is controlled by a Cleanup which aggregates zero or more CleanupRule instances.

Rollover rollover = new Rollover();
rollover.setTimestamp(
  new DateFormatTimestamp(
    DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH.mm.ss")
  )
);
rollover.setSeparator('.');
rollover.setRules(new RolloverRule[] {
  new FileSizeRolloverRule(256, FileSizeQuantifier.MEGABYTES),
  new TimestampRolloverRule(TimestampQuantifier.TOP_OF_DAY)
});

On rollover, FileAppender renames the active file to <basename><separator><timestamp>.<index> where <index> disambiguates same-second rotations.

  • FileSizeRolloverRule(long size, FileSizeQuantifier) — fires when the next write would exceed the size threshold. Quantifier enum includes BYTES, KILOBYTES, MEGABYTES, GIGABYTES.

  • TimestampRolloverRule(TimestampQuantifier) — fires when the wall-clock crosses a timestamp boundary. Quantifier enum includes TOP_OF_MINUTE, TOP_OF_HOUR, TOP_OF_DAY, TOP_OF_WEEK, TOP_OF_MONTH, HALF_DAY.

  • FileCountCleanupRule(int max) — keeps the N most recent archives by modification time; deletes the rest.

  • LastModifiedCleanupRule(long days) — deletes archives older than the given age.

Important

FileCountCleanupRule is stateful (it tracks all seen archives so that it can delete only the oldest excess). Cleanup.vacuum(Path) invokes copy() on every rule before running a pass, so accumulated state never leaks across vacuum invocations.

Logger.putParameter(key, value) stores a (String, Serializable) pair on the logger-scoped parameter adapter. Every record published through that logger carries these parameters, and the %p pattern token renders them.

Typical shape — an enclosing request sets parameters, the leaf call logs, the outermost frame clears them:

public String handleRequest (HttpRequest request) {

  Logger logger = LoggerManager.getLogger(RequestHandler.class);

  logger.putParameter("requestId", request.getId());
  logger.putParameter("tenant", request.getTenant());

  try {
    logger.info("handling request");
    return process(request);
  } finally {
    logger.clearParameters();
  }
}

When scribe-slf4j is on the classpath, SLF4J MDC.put(key, value) calls flow through ScribeMDCAdapter to the same parameter store — so instrumenting a library that writes through SLF4J does not require a parallel MDC integration.

The %p token is multi-line by default. A custom line-prefix controls its shape:

Pattern: %d %+5l [%T] %n - %m%!+\n\t!p
Output:
  2026-04-22T09:17:42.103-0400  INFO [main] com.example.svc - handling request
          requestId=abc-123
          tenant=acme

Or a comma-separated inline form:

Pattern: %d %+5l %n - %m%!-, ! p
Output:
  2026-04-22T09:17:42.103-0400  INFO com.example.svc - handling request requestId=abc-123, tenant=acme

The adapter layer is the SPI boundary between the scribe-pen contract and the backend-specific machinery that actually publishes records.

An abstract class under org.smallmind.scribe.pen.adapter. Concrete implementations live in the scribe-ink-* modules. Two methods:

public abstract LoggerAdapter getLoggingAdapter (String name);
public abstract Record<N> errorRecord (
  String loggerName, Throwable throwable, String message, Object... args
);

getLoggingAdapter manufactures the per-logger adapter. errorRecord builds a FATAL record used for internal framework error reporting (the DefaultErrorHandler and kin emit through this path).

Discovers exactly one LoggingBlueprint via ServiceLoader.load(LoggingBlueprint.class) at class load time. If zero or multiple implementations are discovered, throws StaticInitializationError — an explicit, early failure rather than a silent fallback.

LoggerAdapter is the per-logger handle. It carries the level threshold, the auto-fill flag, the filter/appender/enhancer lists, and the three logMessage(…​) overloads (printf-style, toString, lazy Supplier). ParameterAdapter is the per-logger parameter store returned from LoggerAdapter.getParameterAdapter().

A custom blueprint is a new scribe-ink-* module. The minimum shape:

  1. Extend LoggingBlueprint<MyRecordType>.

  2. Implement getLoggingAdapter(String) to return a LoggerAdapter bound to the backend’s logger for that name.

  3. Implement errorRecord(…​) to construct a backend-appropriate record with populated LoggerContext.

  4. Register the implementation in META-INF/services/org.smallmind.scribe.pen.adapter.LoggingBlueprint.

  5. Publish as the sole blueprint on the application’s classpath.

Three backends ship. Each is a scribe-ink-* artifact; each provides exactly one LoggingBlueprint; an application chooses exactly one.

IndigenousLoggingBlueprint is Scribe’s own in-process backend. It has no runtime dependency on any external logging framework — records are published directly through the Scribe pipeline with no further translation.

Use it when you have no external constraint on record shape, and you want the simplest possible classpath.

JDKLoggingBlueprint routes every Scribe record through java.util.logging. Each Scribe appender is wrapped in a JDKAppenderWrapper (a JUL Handler), each filter in a JDKFilterWrapper, and each record in a JDKRecordSubverter — a JUL LogRecord subclass that simultaneously satisfies Scribe’s RecordWrapper contract so pattern formatters and Scribe-level code see the record as a Record<LogRecord>.

Use it when the runtime environment (Servlet container, JVM fleet, test harness) already captures JUL output.

Log4JLoggingBlueprint routes every Scribe record through Log4J 2 directly. Additivity is disabled on the underlying Logger so events do not propagate up the Log4J hierarchy; instead they fan out through Log4JAppenderWrapper into the configured Scribe appenders.

Use it when the deployment is standardized on Log4J and operators expect Log4J-shaped events.

Note

All three ink packages follow the same shape: *LoggingBlueprint, *LoggerAdapter, *RecordSubverter (or *Record), optional *AppenderWrapper / *FilterWrapper / *LevelTranslator classes. A new backend (Logback, custom aggregator) conforms to the same pattern.

The scribe-slf4j artifact installs Scribe as SLF4J’s provider. ScribeSLF4JServiceProvider implements the SLF4J 2.0 SLF4JServiceProvider contract and is discovered via META-INF/services; it wires together ScribeLoggerFactory, ScribeLoggerAdapter, ScribeMDCAdapter, and ScribeMarkerFactory for SLF4J’s LoggerFactory initialization.

With scribe-slf4j on the classpath, this code:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ThirdParty {
  private static final Logger LOGGER = LoggerFactory.getLogger(ThirdParty.class);

  public void work () {
    LOGGER.info("processing {} records", count);
  }
}

…​flows through ScribeLoggerFactory → ScribeLoggerAdapter → the Scribe Logger for ThirdParty.class → the active `LoggingBlueprint’s adapter → the same appender pipeline that handles direct Scribe users.

ScribeLoggerAdapter translates SLF4J’s {} placeholders to Scribe’s %s placeholders before delegating, and implements LocationAwareLogger so frameworks that supply caller information (e.g. logger wrappers) pass it through correctly.

ScribeMDCAdapter implements the SLF4J MDCAdapter contract by delegating every put/remove/clear to Scribe’s thread-local parameter store, making MDC writes visible to Scribe formatters under the %p token.

The scribe-apache artifact provides CommonsLogWrapper, an org.apache.commons.logging.Log implementation that lazily resolves the named Scribe logger and delegates each level method (trace/debug/info/warn/error/fatal, with and without throwable) to it. It also registers "org.apache.commons.logging." as a logging package prefix so call-site stack walks skip JCL frames.

If a Commons Logging-based library is on the classpath and the application wants those events in Scribe, adding scribe-apache is usually enough. The standard Commons Logging discovery shape (a commons-logging.properties or META-INF/services entry naming CommonsLogWrapper) still applies.

The scribe-pen artifact ships optional Spring beans under org.smallmind.scribe.pen.spring and org.smallmind.scribe.pen.spring.plan. All Spring support is optional — spring-beans is declared as an optional dependency.

DateTimeFormatterFactoryBean

Builds a java.time.DateTimeFormatter from a pattern property. Usually used as the nested bean inside a DateFormatTimestamp declaration.

TemplateInitializingBean

Accepts a List<Template> and calls register() on each in afterPropertiesSet().

DynamicClassNameTemplateInitializingBean

Installs ClassNameTemplate instances driven by Spring-configured pattern/level pairs, matching application-code dynamic configuration.

ExceptionSuppressingLogInitializingBean

Installs an ExceptionSuppressingLogFilter with a Spring-configured list of substrings to suppress.

The LoggingPlan family packages the common "wrap an appender asynchronously, install a default template, add per-class overrides" shape:

public abstract class LoggingPlan implements InitializingBean {
  public abstract Appender getAppender () throws IOException;
  // ...defaults: INFO level, 400-record buffer, 1 worker thread...
  public void afterPropertiesSet () {
    AsynchronousAppender async = new AsynchronousAppender(
      getAppender(), logRecordBufferSize, concurrencyLimit
    );
    new DefaultTemplate(defaultLogLevel, true, async).register();
    for (Log log : logs) {
      new ClassNameTemplate(log.getLevel(), true, log.getPattern(), async).register();
    }
  }
}

Three concrete plans: ConsoleLoggingPlan, FileLoggingPlan, FluentBitLoggingPlan. Each returns the appropriate concrete appender from getAppender().

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="fullTimestamp" class="org.smallmind.scribe.pen.DateFormatTimestamp">
    <property name="dateTimeFormatter">
      <bean class="org.smallmind.scribe.pen.spring.DateTimeFormatterFactoryBean">
        <property name="pattern" value="yyyy-MM-dd'T'HH:mm:ss.SSSZ"/>
      </bean>
    </property>
  </bean>

  <bean id="patternFormatter" class="org.smallmind.scribe.pen.PatternFormatter">
    <property name="timestamp" ref="fullTimestamp"/>
    <property name="format" value="%d %n %+5l (%F.%M:%L) [%T] - %m%!+\n\t!p%!+\n\t!s"/>
  </bean>

  <bean id="consoleAppender" class="org.smallmind.scribe.pen.ConsoleAppender">
    <property name="formatter" ref="patternFormatter"/>
  </bean>

  <bean id="defaultTemplate"
        class="org.smallmind.scribe.pen.DefaultTemplate"
        init-method="register">
    <property name="autoFillLoggerContext" value="true"/>
    <property name="level" value="${log.default.level}"/>
    <property name="appenders">
      <list><ref bean="consoleAppender"/></list>
    </property>
  </bean>

</beans>
<bean id="loggingPlan" class="org.smallmind.scribe.pen.spring.plan.ConsoleLoggingPlan">
  <property name="defaultLogLevel" value="INFO"/>
  <property name="logRecordBufferSize" value="2000"/>
  <property name="concurrencyLimit" value="2"/>
  <property name="logs">
    <list>
      <bean class="org.smallmind.scribe.pen.spring.plan.Log">
        <property name="level" value="DEBUG"/>
        <property name="pattern" value="com.example.*"/>
      </bean>
      <bean class="org.smallmind.scribe.pen.spring.plan.Log">
        <property name="level" value="WARN"/>
        <property name="pattern" value="org.chattylib.*"/>
      </bean>
    </list>
  </property>
</bean>

The plan wraps the ConsoleAppender in an AsynchronousAppender with a 2,000-record buffer and two workers, registers a DefaultTemplate at INFO, and registers per-pattern ClassNameTemplate instances for com.example. (at DEBUG) and org.chattylib. (at WARN).

LoggingBlueprintFactory runs its ServiceLoader lookup during class load. A missing or duplicate blueprint throws StaticInitializationError at the first Scribe-touching class load — typically during startup, not at the first log call. Failures are deterministic and early.

autoFillLoggerContext = true performs a stack walk on every record. This is cheap in absolute terms but not free; high-volume loggers with no intent of rendering %C/%M/%F/%L should leave it off. The stack walk skips frames whose class is registered via LoggerManager.addLoggingPackagePrefix(…​) — Scribe’s own framework frames are pre-registered with prefix "org.smallmind.scribe."; the JDK, Log4J, Commons Logging, and SLF4J bridge modules register their respective prefixes when their blueprints load.

AsynchronousAppender.close() signals the worker threads, waits on a CountDownLatch until the queue drains, and then closes the wrapped appender. A premature System.exit(0) bypasses this — if the queue is non-empty, records are lost.

FileAppender.handleOutput(String) is synchronized. Rollover occurs under the same lock, so concurrent logging cannot interleave bytes across a rotation boundary. Under heavy load, prefer wrapping with AsynchronousAppender so logging threads do not contend for the file lock.

Template mutators (setLevel, addAppender, etc.) are synchronized on the template, and LoggerManager is synchronized on its class when re-associating loggers. Template changes become visible to subsequent log calls on all matched loggers immediately after the mutator returns, but records already in flight through the pipeline may still observe the pre-change configuration.

If scribe-slf4j is not on the classpath, libraries that log through org.slf4j.Logger do not flow through Scribe — they emit through whatever other SLF4J provider is discovered (or nowhere, if none is present). Bridging is opt-in per classpath.

No backend discovered

LoggingBlueprintFactory throws StaticInitializationError: Unable to load a LoggingBlueprint. Fix: add exactly one scribe-ink-* artifact to the application. A library-only classpath (only scribe-pen) is expected to fail this check; the application is expected to supply the backend.

Multiple backends discovered

LoggingBlueprintFactory throws StaticInitializationError: Found more than one LoggingBlueprint. Fix: remove all but one scribe-ink- dependency. Check transitive dependencies — a library pulling its own scribe-ink- in by mistake is the common culprit. Run mvn dependency:tree.

Commons Logging output bypasses Scribe on the module path

LogFactory.getLog returns org.apache.commons.logging.impl.Jdk14Logger instead of CommonsLogWrapper. org.smallmind.scribe.apache is on the module path but not in the module graph. Require it, or add --add-modules org.smallmind.scribe.apache. See Module Path.

Records silently dropped

Several likely causes:

  • The logger’s level is above the record level. Check logger.getLevel() and the governing template.getLevel().

  • A logger-level Filter vetoed the record before appenders ran. Check Filter#willLog implementations.

  • An ExceptionSuppressingLogFilter matched a substring of the message or stack trace.

  • An AsynchronousAppender was close()`d or its queue rejected the record under load. `close() throws LoggerException on subsequent publish calls.

FileAppender throws "Appender to file(…​) has been previously closed"

The appender was explicitly closed (directly or through AsynchronousAppender.close()) and then used again. FileAppender does not re-open on its own — build a new instance.

No caller context in output

%C/%M/%F/%L render empty. Either autoFillLoggerContext is off on the logger (check logger.getAutoFillLoggerContext() and the governing template’s isAutoFillLoggerContext()), or the record was created without context capture. Custom blueprints must call LoggerContext.fillIn() on records they construct directly.

Log output appears duplicated

Most common under a bridge: a logger writes through SLF4J, SLF4J routes to Scribe via scribe-slf4j, and the application also attached the same appender to the Scribe logger directly. Remove one of the paths.

Wrong class/method/line in output

The caller-context stack walk skipped too few frames. Call LoggerManager.addLoggingPackagePrefix("your.wrapper.package.") from your own logging wrapper’s static initializer so Scribe treats it as infrastructure.

Pattern produces empty output

PatternFormatter constructed with null as the format string installs zero rules, so every record renders as just a line separator. Pass a non-null format.

Before deploying a Scribe-enabled service, verify:

  • Exactly one scribe-ink-* artifact resolved in mvn dependency:tree.

  • At least one Template registered before any logger call that should be captured.

  • AsynchronousAppender wrapping any I/O-bound appender if the application is latency-sensitive.

  • autoFillLoggerContext set to the intended value (on for readable logs, off for very high volume).

  • File paths used by FileAppender are writable and their parent directories exist or can be created.

  • If scribe-slf4j is present, confirm it is the only SLF4J provider — running alongside slf4j-simple, Logback, or another provider makes the discovered backend undefined.

  • If using Spring LoggingPlan, verify spring-beans is a non-optional compile dependency at the application level.

  • PERSISTENCE.adoc — persistence integration concepts that pair cleanly with parameter-scoped per-request logging.

  • SCHEDULE.adoc — Quartz-on-Spring scheduling; its QuartzProxyJob emits structured firing records through whatever logging framework is installed, which with Scribe on the classpath means the Scribe pipeline.

  • KAFKA.adoc and MONGODB.adoc — other infrastructure integrations with similar library-versus-application artifact boundaries.