Set up SLF4J logging with Logback #22

Closed
opened 2026-10-04 19:28:27 +00:00 by daniel · 1 comment
Owner

Imported from GitHub samson-media/barn#22 — opened by @daniel-samson on 2026-01-21 12:43:20 UTC

Overview

Set up SLF4J logging with Logback, including structured logging and log rotation.

Context

  • Read first: docs/config.md (log_level setting), docs/jobs.md (logs directory)
  • Depends on: #1 (project structure)

Requirements

1. Logback Configuration

src/main/resources/logback.xml:

<configuration>
    <!-- Console appender for development/foreground -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- File appender for daemon mode -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${BARN_LOG_DIR:-/tmp/barn/logs}/barn.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${BARN_LOG_DIR:-/tmp/barn/logs}/barn.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>7</maxHistory>
            <totalSizeCap>100MB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>%d{ISO8601} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- JSON appender for structured logging -->
    <appender name="JSON" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${BARN_LOG_DIR:-/tmp/barn/logs}/barn.json.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${BARN_LOG_DIR:-/tmp/barn/logs}/barn.json.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <maxFileSize>10MB</maxFileSize>
            <maxHistory>7</maxHistory>
        </rollingPolicy>
        <encoder class="net.logstash.logback.encoder.LogstashEncoder"/>
    </appender>

    <root level="${BARN_LOG_LEVEL:-INFO}">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </root>
</configuration>

2. Runtime Log Level Configuration

public class LoggingConfig {
    public static void setLogLevel(LogLevel level) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
        rootLogger.setLevel(Level.valueOf(level.name()));
    }

    public static LogLevel getLogLevel() {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
        return LogLevel.valueOf(rootLogger.getLevel().toString());
    }
}

3. Structured Log Events

public class JobLogEvents {
    private static final Logger LOG = LoggerFactory.getLogger(JobLogEvents.class);

    public static void jobCreated(Job job) {
        LOG.info("Job created: id={} command={} tag={}",
            job.id(), job.command(), job.tag());
    }

    public static void jobStarted(Job job) {
        LOG.info("Job started: id={} pid={}",
            job.id(), job.pid());
    }

    public static void jobCompleted(Job job, Duration duration) {
        if (job.exitCode() == 0) {
            LOG.info("Job succeeded: id={} duration={}ms",
                job.id(), duration.toMillis());
        } else {
            LOG.warn("Job failed: id={} exitCode={} error={}",
                job.id(), job.exitCode(), job.error());
        }
    }

    public static void jobRetryScheduled(Job job, Instant retryAt) {
        LOG.info("Job retry scheduled: id={} attempt={} retryAt={}",
            job.id(), job.retryCount() + 1, retryAt);
    }
}

4. MDC (Mapped Diagnostic Context)

Add context to all log messages within a job:

public class JobContext implements AutoCloseable {
    public static JobContext forJob(Job job) {
        MDC.put("jobId", job.id());
        MDC.put("jobTag", job.tag());
        return new JobContext();
    }

    @Override
    public void close() {
        MDC.remove("jobId");
        MDC.remove("jobTag");
    }
}

// Usage
try (var ctx = JobContext.forJob(job)) {
    LOG.info("Processing started");  // Automatically includes jobId
}

5. Log File Locations

Log Type Location Purpose
Daemon log /tmp/barn/logs/barn.log Service events
Job stdout /tmp/barn/jobs/<id>/logs/stdout.log Process output
Job stderr /tmp/barn/jobs/<id>/logs/stderr.log Process errors

6. Tests Required

  • LoggingConfigTest.java: Test level changes
  • JobLogEventsTest.java: Test structured events

Acceptance Criteria

  • Logs go to console and file
  • Log rotation works (size and time based)
  • Log level configurable at runtime
  • MDC context works for job-scoped logs
  • JSON structured logging available
  • Environment variable override works (BARN_LOG_LEVEL)
  • mvn verify passes
  • Tests have 80%+ coverage

Implementation Notes

Add logstash-logback-encoder for JSON logging:

<dependency>
    <groupId>net.logstash.logback</groupId>
    <artifactId>logstash-logback-encoder</artifactId>
    <version>8.0</version>
</dependency>

Ensure log directory exists on startup:

Files.createDirectories(Path.of(System.getProperty("BARN_LOG_DIR", "/tmp/barn/logs")));

Definition of Done

  • Logging configured correctly
  • Log rotation works
  • Runtime level changes work
  • All tests pass
<!-- github-import:issue:22 --> _Imported from GitHub samson-media/barn#22 — opened by **@daniel-samson** on 2026-01-21 12:43:20 UTC_ ## Overview Set up SLF4J logging with Logback, including structured logging and log rotation. ## Context - **Read first**: `docs/config.md` (log_level setting), `docs/jobs.md` (logs directory) - **Depends on**: #1 (project structure) ## Requirements ### 1. Logback Configuration `src/main/resources/logback.xml`: ```xml <configuration> <!-- Console appender for development/foreground --> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- File appender for daemon mode --> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${BARN_LOG_DIR:-/tmp/barn/logs}/barn.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <fileNamePattern>${BARN_LOG_DIR:-/tmp/barn/logs}/barn.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern> <maxFileSize>10MB</maxFileSize> <maxHistory>7</maxHistory> <totalSizeCap>100MB</totalSizeCap> </rollingPolicy> <encoder> <pattern>%d{ISO8601} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- JSON appender for structured logging --> <appender name="JSON" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${BARN_LOG_DIR:-/tmp/barn/logs}/barn.json.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <fileNamePattern>${BARN_LOG_DIR:-/tmp/barn/logs}/barn.json.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern> <maxFileSize>10MB</maxFileSize> <maxHistory>7</maxHistory> </rollingPolicy> <encoder class="net.logstash.logback.encoder.LogstashEncoder"/> </appender> <root level="${BARN_LOG_LEVEL:-INFO}"> <appender-ref ref="CONSOLE"/> <appender-ref ref="FILE"/> </root> </configuration> ``` ### 2. Runtime Log Level Configuration ```java public class LoggingConfig { public static void setLogLevel(LogLevel level) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME); rootLogger.setLevel(Level.valueOf(level.name())); } public static LogLevel getLogLevel() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME); return LogLevel.valueOf(rootLogger.getLevel().toString()); } } ``` ### 3. Structured Log Events ```java public class JobLogEvents { private static final Logger LOG = LoggerFactory.getLogger(JobLogEvents.class); public static void jobCreated(Job job) { LOG.info("Job created: id={} command={} tag={}", job.id(), job.command(), job.tag()); } public static void jobStarted(Job job) { LOG.info("Job started: id={} pid={}", job.id(), job.pid()); } public static void jobCompleted(Job job, Duration duration) { if (job.exitCode() == 0) { LOG.info("Job succeeded: id={} duration={}ms", job.id(), duration.toMillis()); } else { LOG.warn("Job failed: id={} exitCode={} error={}", job.id(), job.exitCode(), job.error()); } } public static void jobRetryScheduled(Job job, Instant retryAt) { LOG.info("Job retry scheduled: id={} attempt={} retryAt={}", job.id(), job.retryCount() + 1, retryAt); } } ``` ### 4. MDC (Mapped Diagnostic Context) Add context to all log messages within a job: ```java public class JobContext implements AutoCloseable { public static JobContext forJob(Job job) { MDC.put("jobId", job.id()); MDC.put("jobTag", job.tag()); return new JobContext(); } @Override public void close() { MDC.remove("jobId"); MDC.remove("jobTag"); } } // Usage try (var ctx = JobContext.forJob(job)) { LOG.info("Processing started"); // Automatically includes jobId } ``` ### 5. Log File Locations | Log Type | Location | Purpose | |----------|----------|---------| | Daemon log | `/tmp/barn/logs/barn.log` | Service events | | Job stdout | `/tmp/barn/jobs/<id>/logs/stdout.log` | Process output | | Job stderr | `/tmp/barn/jobs/<id>/logs/stderr.log` | Process errors | ### 6. Tests Required - `LoggingConfigTest.java`: Test level changes - `JobLogEventsTest.java`: Test structured events ## Acceptance Criteria - [ ] Logs go to console and file - [ ] Log rotation works (size and time based) - [ ] Log level configurable at runtime - [ ] MDC context works for job-scoped logs - [ ] JSON structured logging available - [ ] Environment variable override works (BARN_LOG_LEVEL) - [ ] `mvn verify` passes - [ ] Tests have 80%+ coverage ## Implementation Notes Add logstash-logback-encoder for JSON logging: ```xml <dependency> <groupId>net.logstash.logback</groupId> <artifactId>logstash-logback-encoder</artifactId> <version>8.0</version> </dependency> ``` Ensure log directory exists on startup: ```java Files.createDirectories(Path.of(System.getProperty("BARN_LOG_DIR", "/tmp/barn/logs"))); ``` ## Definition of Done - Logging configured correctly - Log rotation works - Runtime level changes work - All tests pass
daniel added this to the M1: Foundation milestone 2026-10-04 19:28:27 +00:00
daniel added the foundation label 2026-10-04 19:28:27 +00:00
Author
Owner

@daniel-samson commented on 2026-01-21 15:34:30 UTC:

Completed SLF4J logging with Logback implementation:

Changes

Configuration

  • logback.xml: Added complete configuration with:
    • Console appender for development/foreground mode
    • Rolling file appender with size and time-based rotation
    • JSON structured logging appender using logstash-logback-encoder
    • Environment variable support (BARN_LOG_DIR, BARN_LOG_LEVEL)
    • MDC key inclusion for job context

New Files

  • LoggingConfig.java: Runtime log level configuration

    • setLogLevel() / getLogLevel() for dynamic level changes
    • ensureLogDirectory() for directory setup
    • getDefaultLogDirectory() with env var support
  • JobLogEvents.java: Structured logging for job lifecycle

    • jobCreated(), jobStarted(), jobCompleted()
    • jobRetryScheduled(), jobCancelled(), jobTimedOut()
    • jobCleaned()
  • JobContext.java: MDC wrapper for job-scoped logging

    • Auto-closeable for try-with-resources pattern
    • Sets jobId and jobTag in MDC automatically

Dependencies

  • Added logstash-logback-encoder 8.0 for JSON structured logging

Tests

  • 43 new tests covering:
    • LoggingConfigTest: Level changes, directory creation
    • JobLogEventsTest: All event types
    • JobContextTest: MDC management

Test Results

  • All 836 tests pass
  • Coverage thresholds met
<!-- github-import:comment:3778899959 --> _**@daniel-samson** commented on 2026-01-21 15:34:30 UTC:_ Completed SLF4J logging with Logback implementation: ## Changes ### Configuration - **logback.xml**: Added complete configuration with: - Console appender for development/foreground mode - Rolling file appender with size and time-based rotation - JSON structured logging appender using logstash-logback-encoder - Environment variable support (BARN_LOG_DIR, BARN_LOG_LEVEL) - MDC key inclusion for job context ### New Files - **LoggingConfig.java**: Runtime log level configuration - `setLogLevel()` / `getLogLevel()` for dynamic level changes - `ensureLogDirectory()` for directory setup - `getDefaultLogDirectory()` with env var support - **JobLogEvents.java**: Structured logging for job lifecycle - `jobCreated()`, `jobStarted()`, `jobCompleted()` - `jobRetryScheduled()`, `jobCancelled()`, `jobTimedOut()` - `jobCleaned()` - **JobContext.java**: MDC wrapper for job-scoped logging - Auto-closeable for try-with-resources pattern - Sets jobId and jobTag in MDC automatically ### Dependencies - Added logstash-logback-encoder 8.0 for JSON structured logging ### Tests - 43 new tests covering: - LoggingConfigTest: Level changes, directory creation - JobLogEventsTest: All event types - JobContextTest: MDC management ## Test Results - All 836 tests pass - Coverage thresholds met
This repo is archived. You cannot comment on issues.