Add log4j2-levels module: threshold rule, inheritance, additivity, custom levels, Actuator runtime changes and argument evaluation on Spring Boot 4.1.2 / Log4j2 2.25.5, with real transcripts
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5SFkZoaMCukJNvZCV
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
fe3fc689a6
commit
c9a2b766bb
@@ -0,0 +1,21 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import org.apache.logging.log4j.Level;
|
||||
|
||||
/**
|
||||
* Custom levels. {@code Level.forName} registers the level the first time it runs and returns the
|
||||
* existing one afterwards, so it is safe whether or not log4j2-spring.xml (which declares the same
|
||||
* two levels in {@code <CustomLevels>}) has loaded yet. {@code Level.getLevel("DIAG")} is not: it
|
||||
* returns null until somebody has registered the name.
|
||||
*/
|
||||
public final class Levels {
|
||||
|
||||
/** Sits between WARN (300) and INFO (400): shown whenever INFO is shown. */
|
||||
public static final Level DIAG = Level.forName("DIAG", 350);
|
||||
|
||||
/** Sits between INFO (400) and DEBUG (500): hidden at INFO, shown at DEBUG. */
|
||||
public static final Level PERF = Level.forName("PERF", 450);
|
||||
|
||||
private Levels() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Log4j2LevelsApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Log4j2LevelsApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ankurm.log4j2levels.billing;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** Has no entry of its own in log4j2-spring.xml, so it inherits from the root logger. */
|
||||
@Service
|
||||
public class InvoiceService {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(InvoiceService.class);
|
||||
|
||||
public void bill(String customer) {
|
||||
logger.trace("tax table loaded");
|
||||
logger.debug("billing {}", customer);
|
||||
logger.info("invoice issued for {}", customer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.ankurm.log4j2levels.db;
|
||||
|
||||
public class DatabaseException extends RuntimeException {
|
||||
public DatabaseException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.ankurm.log4j2levels.db;
|
||||
|
||||
public record User(Long id, String username) {
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ankurm.log4j2levels.db;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/** In-memory stand-in for a database. A negative id simulates a lost connection. */
|
||||
@Repository
|
||||
public class UserRepository {
|
||||
|
||||
// log4j2-spring.xml sets this package to ERROR, so the DEBUG line never appears.
|
||||
private static final Logger logger = LogManager.getLogger(UserRepository.class);
|
||||
|
||||
private final Map<Long, User> users = Map.of(
|
||||
1L, new User(1L, "asha"),
|
||||
2L, new User(2L, "ravi"));
|
||||
|
||||
public User findById(Long id) {
|
||||
logger.debug("SELECT id, username FROM users WHERE id = {}", id);
|
||||
if (id < 0) {
|
||||
logger.error("connection reset while loading user {}", id);
|
||||
throw new DatabaseException("connection reset");
|
||||
}
|
||||
return users.get(id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.ankurm.log4j2levels.service;
|
||||
|
||||
public class ServiceException extends RuntimeException {
|
||||
public ServiceException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.ankurm.log4j2levels.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.log4j2levels.db.DatabaseException;
|
||||
import com.ankurm.log4j2levels.db.User;
|
||||
import com.ankurm.log4j2levels.db.UserRepository;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/** The post's UserService, made compilable: one real call per level. */
|
||||
@Service
|
||||
public class UserService {
|
||||
|
||||
private static final Logger logger = LogManager.getLogger(UserService.class);
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
public UserService(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
public User getUserById(Long userId) {
|
||||
logger.debug("Entering getUserById with userId: {}", userId);
|
||||
if (userId == null) {
|
||||
logger.warn("getUserById called with null userId");
|
||||
throw new IllegalArgumentException("User ID cannot be null");
|
||||
}
|
||||
try {
|
||||
logger.info("Fetching user with ID: {}", userId);
|
||||
User user = userRepository.findById(userId);
|
||||
if (user == null) {
|
||||
logger.info("User not found for ID: {}", userId);
|
||||
return null;
|
||||
}
|
||||
logger.debug("Successfully retrieved user: {}", user.username());
|
||||
return user;
|
||||
} catch (DatabaseException e) {
|
||||
logger.error("Database error while fetching user with ID: {}", userId, e);
|
||||
throw new ServiceException("Failed to retrieve user", e);
|
||||
}
|
||||
}
|
||||
|
||||
public int processBatchUsers(List<Long> ids) {
|
||||
logger.info("Starting batch user processing");
|
||||
long startTime = System.nanoTime();
|
||||
int processed = 0;
|
||||
try {
|
||||
for (Long id : ids) {
|
||||
if (userRepository.findById(id) != null) {
|
||||
processed++;
|
||||
}
|
||||
}
|
||||
logger.debug("Processed {} users in batch", processed);
|
||||
} catch (DatabaseException e) {
|
||||
logger.fatal("Critical failure in batch processing, giving up.", e);
|
||||
throw new ServiceException("Batch failed", e);
|
||||
} finally {
|
||||
logger.info("Batch processing completed, {} processed", processed);
|
||||
}
|
||||
return processed;
|
||||
}
|
||||
|
||||
public void diagnose() {
|
||||
// Custom levels, see Levels.java
|
||||
logger.log(com.ankurm.log4j2levels.Levels.DIAG, "cache size = 42");
|
||||
logger.log(com.ankurm.log4j2levels.Levels.PERF, "lookup took 3 ms");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.ankurm.log4j2levels.web;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.ankurm.log4j2levels.Levels;
|
||||
import org.apache.logging.log4j.Level;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/** Logs one line per level through the logger with the given name and reports which were enabled. */
|
||||
@RestController
|
||||
public class LogController {
|
||||
|
||||
@GetMapping("/demo/log")
|
||||
public Map<String, Boolean> log(@RequestParam String name) {
|
||||
Logger logger = LogManager.getLogger(name);
|
||||
Map<String, Boolean> enabled = new LinkedHashMap<>();
|
||||
for (Level level : new Level[] {Level.FATAL, Level.ERROR, Level.WARN, Levels.DIAG, Level.INFO,
|
||||
Levels.PERF, Level.DEBUG, Level.TRACE}) {
|
||||
enabled.put(level.name(), logger.isEnabled(level));
|
||||
logger.log(level, "demo line at {}", level.name());
|
||||
}
|
||||
return enabled;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
spring:
|
||||
application:
|
||||
name: log4j2-levels
|
||||
main:
|
||||
banner-mode: "off"
|
||||
|
||||
management:
|
||||
endpoints:
|
||||
web:
|
||||
exposure:
|
||||
include: loggers,health
|
||||
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<CustomLevels>
|
||||
<CustomLevel name="DIAG" intLevel="350"/>
|
||||
<CustomLevel name="PERF" intLevel="450"/>
|
||||
</CustomLevels>
|
||||
|
||||
<Appenders>
|
||||
<!-- follow="true" makes the appender look up System.out on every write, which is what lets
|
||||
the tests swap System.out and read exactly what the real appender printed. -->
|
||||
<Console name="Console" target="SYSTEM_OUT" follow="true">
|
||||
<PatternLayout pattern="%-5level %logger{1.} - %msg%n%throwable{short}"/>
|
||||
</Console>
|
||||
</Appenders>
|
||||
|
||||
<Loggers>
|
||||
<Root level="info">
|
||||
<AppenderRef ref="Console"/>
|
||||
</Root>
|
||||
|
||||
<!-- additivity="false" plus its own appender: lines are printed once. -->
|
||||
<Logger name="com.ankurm.log4j2levels.service" level="debug" additivity="false">
|
||||
<AppenderRef ref="Console"/>
|
||||
</Logger>
|
||||
|
||||
<!-- No appender of its own: it uses the root's through additivity. -->
|
||||
<Logger name="com.ankurm.log4j2levels.db" level="error"/>
|
||||
|
||||
<!-- The trap: an appender of its own AND additivity left at its default (true). -->
|
||||
<Logger name="com.ankurm.log4j2levels.dup" level="info">
|
||||
<AppenderRef ref="Console"/>
|
||||
</Logger>
|
||||
|
||||
<!-- Level written in lower case, as in the original article. -->
|
||||
<Logger name="com.ankurm.log4j2levels.diag" level="diag"/>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.MvcResult;
|
||||
|
||||
/** Transcript 08: changing levels at runtime through /actuator/loggers. */
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
class ActuatorLoggersTest {
|
||||
|
||||
private static final String BASE = "com.ankurm.log4j2levels.";
|
||||
|
||||
@Autowired
|
||||
MockMvc mvc;
|
||||
|
||||
private Transcript t;
|
||||
|
||||
private String show(String logger) throws Exception {
|
||||
MvcResult r = mvc.perform(get("/actuator/loggers/" + logger)).andReturn();
|
||||
String body = r.getResponse().getContentAsString();
|
||||
t.line("GET /actuator/loggers/%s -> %d %s", logger, r.getResponse().getStatus(), body);
|
||||
return body;
|
||||
}
|
||||
|
||||
private int send(String logger, String body) throws Exception {
|
||||
MvcResult r = mvc.perform(post("/actuator/loggers/" + logger).contentType(MediaType.APPLICATION_JSON).content(body)).andReturn();
|
||||
t.line("POST /actuator/loggers/%s %s -> %d %s", logger, body, r.getResponse().getStatus(), r.getResponse().getContentAsString());
|
||||
return r.getResponse().getStatus();
|
||||
}
|
||||
|
||||
@Test
|
||||
void changeAndResetLevelsWhileRunning() throws Exception {
|
||||
try (Transcript transcript = Transcript.open("08-actuator-loggers.txt")) {
|
||||
this.t = transcript;
|
||||
t.line("# 1. a logger the XML configures, and one that only inherits from it");
|
||||
show(BASE + "service");
|
||||
show(BASE + "service.UserService");
|
||||
t.line("");
|
||||
t.line("# 2. raise the service package to TRACE and log a trace line through UserService's logger");
|
||||
assertThat(send(BASE + "service", "{\"configuredLevel\":\"TRACE\"}")).isEqualTo(204);
|
||||
show(BASE + "service.UserService");
|
||||
String traced = Captured.run(() -> LogManager.getLogger(BASE + "service.UserService").trace("probe"));
|
||||
t.line("printed: %s", traced.strip());
|
||||
t.line("");
|
||||
t.line("# 3. reset it with configuredLevel null");
|
||||
assertThat(send(BASE + "service", "{\"configuredLevel\":null}")).isEqualTo(204);
|
||||
show(BASE + "service");
|
||||
show(BASE + "service.UserService");
|
||||
String afterReset = Captured.run(() -> LogManager.getLogger(BASE + "service.UserService").debug("probe"));
|
||||
t.line("a debug line after the reset printed: %s", afterReset.isBlank() ? "nothing" : afterReset.strip());
|
||||
send(BASE + "service", "{\"configuredLevel\":\"DEBUG\"}");
|
||||
t.line("");
|
||||
t.line("# 4. a logger with no entry in the XML: set, then reset");
|
||||
show(BASE + "billing.InvoiceService");
|
||||
send(BASE + "billing", "{\"configuredLevel\":\"TRACE\"}");
|
||||
show(BASE + "billing.InvoiceService");
|
||||
send(BASE + "billing", "{\"configuredLevel\":null}");
|
||||
show(BASE + "billing.InvoiceService");
|
||||
t.line("");
|
||||
t.line("# 5. what the endpoint will not take");
|
||||
send(BASE + "service", "{\"configuredLevel\":\"DIAG\"}");
|
||||
send(BASE + "service", "{\"configuredLevel\":\"debug\"}");
|
||||
send(BASE + "service", "{\"configuredLevel\":\"LOUD\"}");
|
||||
send(BASE + "service", "{\"configuredLevel\":\"DEBUG\"}");
|
||||
t.line("");
|
||||
t.line("# 6. the root logger");
|
||||
show("ROOT");
|
||||
send("ROOT", "{\"configuredLevel\":\"WARN\"}");
|
||||
show(BASE + "billing.InvoiceService");
|
||||
send("ROOT", "{\"configuredLevel\":\"INFO\"}");
|
||||
show("ROOT");
|
||||
t.line("");
|
||||
t.line("# 7. the full listing: the levels it offers, and how the root logger is named");
|
||||
String all = mvc.perform(get("/actuator/loggers")).andReturn().getResponse().getContentAsString();
|
||||
java.util.regex.Matcher levels = java.util.regex.Pattern.compile("\"levels\":\\[[^\\]]*\\]").matcher(all);
|
||||
t.line("GET /actuator/loggers -> %s", levels.find() ? levels.group() : "no levels array");
|
||||
java.util.regex.Matcher root = java.util.regex.Pattern.compile("\"(ROOT|)\":\\{[^}]*\\}").matcher(all);
|
||||
while (root.find()) {
|
||||
t.line(" entry: %s", root.group());
|
||||
}
|
||||
t.line(" lists com.ankurm.log4j2levels.service: %s", all.contains("\"" + BASE + "service\""));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.function.IntSupplier;
|
||||
|
||||
import org.apache.logging.log4j.Level;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.core.config.Configurator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/** Transcript 07: how many times an argument's toString() runs when the call is, and is not, enabled. */
|
||||
@SpringBootTest
|
||||
class ArgumentEvaluationTest {
|
||||
|
||||
static final class Probe {
|
||||
int calls;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
calls++;
|
||||
return "asha";
|
||||
}
|
||||
}
|
||||
|
||||
private static int measure(Logger logger, java.util.function.Consumer<Probe> call) {
|
||||
Probe probe = new Probe();
|
||||
Captured.run(() -> call.accept(probe));
|
||||
return probe.calls;
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledDebugStillRunsEagerArguments() {
|
||||
Logger logger = LogManager.getLogger("args.demo");
|
||||
String[] names = {
|
||||
"debug(\"User: \" + user)",
|
||||
"debug(\"User: {}\", user)",
|
||||
"debug(\"User: {}\", user.toString())",
|
||||
"debug(() -> \"User: \" + user)",
|
||||
"debug(\"User: {}\", () -> user.toString())",
|
||||
"if (isDebugEnabled()) debug(\"User: \" + user)"
|
||||
};
|
||||
int[] disabled = new int[names.length];
|
||||
int[] enabled = new int[names.length];
|
||||
for (int round = 0; round < 2; round++) {
|
||||
Configurator.setLevel("args.demo", round == 0 ? Level.INFO : Level.DEBUG);
|
||||
int[] target = round == 0 ? disabled : enabled;
|
||||
target[0] = measure(logger, user -> logger.debug("User: " + user));
|
||||
target[1] = measure(logger, user -> logger.debug("User: {}", user));
|
||||
target[2] = measure(logger, user -> logger.debug("User: {}", user.toString()));
|
||||
target[3] = measure(logger, user -> logger.debug(() -> "User: " + user));
|
||||
target[4] = measure(logger, user -> logger.debug("User: {}", () -> user.toString()));
|
||||
target[5] = measure(logger, user -> {
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("User: " + user);
|
||||
}
|
||||
});
|
||||
}
|
||||
Configurator.setLevel("args.demo", (Level) null);
|
||||
try (Transcript t = Transcript.open("07-argument-evaluation.txt")) {
|
||||
t.line("# times user.toString() ran for one call, threshold INFO (debug off) vs DEBUG (debug on)");
|
||||
t.line("%-48s %-10s %s", "call", "debug off", "debug on");
|
||||
for (int i = 0; i < names.length; i++) {
|
||||
t.line("%-48s %-10d %d", names[i], disabled[i], enabled[i]);
|
||||
}
|
||||
}
|
||||
assertThat(disabled).containsExactly(1, 0, 1, 0, 0, 0);
|
||||
assertThat(enabled).containsExactly(1, 1, 1, 1, 1, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.PrintStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/** Runs a block and returns exactly what the real Console appender printed meanwhile. */
|
||||
public final class Captured {
|
||||
|
||||
private Captured() {
|
||||
}
|
||||
|
||||
public static synchronized String run(Runnable block) {
|
||||
PrintStream original = System.out;
|
||||
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
|
||||
System.setOut(new PrintStream(buffer, true, StandardCharsets.UTF_8));
|
||||
try {
|
||||
block.run();
|
||||
} finally {
|
||||
System.setOut(original);
|
||||
}
|
||||
return buffer.toString(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public static long lines(String text) {
|
||||
return text.isEmpty() ? 0 : text.lines().count();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.core.LoggerContext;
|
||||
import org.apache.logging.log4j.core.config.LoggerConfig;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/** Transcripts 03 and 04: which level a logger really gets, and why a line can print twice. */
|
||||
@SpringBootTest
|
||||
class ConfigTest {
|
||||
|
||||
private static final String BASE = "com.ankurm.log4j2levels.";
|
||||
|
||||
@Test
|
||||
void effectiveLevelComesFromTheNearestConfiguredAncestor() {
|
||||
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
|
||||
try (Transcript t = Transcript.open("03-effective-levels.txt")) {
|
||||
String location = String.valueOf(ctx.getConfiguration().getConfigurationSource().getLocation());
|
||||
t.line("# configuration file Spring Boot handed to Log4j2: %s", location.substring(location.lastIndexOf('/') + 1));
|
||||
t.line("");
|
||||
t.line("%-48s %-9s %s", "logger", "effective", "level comes from");
|
||||
for (String name : new String[] {BASE + "service.UserService", BASE + "service.sub.Deeper",
|
||||
BASE + "db.UserRepository", BASE + "billing.InvoiceService", "org.example.Unrelated",
|
||||
BASE + "diag.Whatever"}) {
|
||||
LoggerConfig config = ctx.getConfiguration().getLoggerConfig(name);
|
||||
String source = config.getName().isEmpty() ? "root" : config.getName();
|
||||
t.line("%-48s %-9s %s", name, ctx.getLogger(name).getLevel(), source);
|
||||
}
|
||||
}
|
||||
assertThat(ctx.getLogger(BASE + "service.UserService").getLevel().name()).isEqualTo("DEBUG");
|
||||
assertThat(ctx.getLogger(BASE + "service.sub.Deeper").getLevel().name()).isEqualTo("DEBUG");
|
||||
assertThat(ctx.getLogger(BASE + "db.UserRepository").getLevel().name()).isEqualTo("ERROR");
|
||||
assertThat(ctx.getLogger(BASE + "billing.InvoiceService").getLevel().name()).isEqualTo("INFO");
|
||||
assertThat(ctx.getLogger("org.example.Unrelated").getLevel().name()).isEqualTo("INFO");
|
||||
assertThat(ctx.getLogger(BASE + "diag.Whatever").getLevel().name()).isEqualTo("DIAG");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAppenderOnTheLoggerPlusDefaultAdditivityPrintsEveryLineTwice() {
|
||||
try (Transcript t = Transcript.open("04-additivity.txt")) {
|
||||
String dup = Captured.run(() -> LogManager.getLogger(BASE + "dup").info("order 7 shipped"));
|
||||
String once = Captured.run(() -> LogManager.getLogger(BASE + "service").info("order 7 shipped"));
|
||||
String viaRoot = Captured.run(() -> LogManager.getLogger(BASE + "db").error("order 7 failed"));
|
||||
t.line("# logger 'dup': <AppenderRef ref=\"Console\"/> and additivity left at its default (true)");
|
||||
dup.lines().forEach(t::line);
|
||||
t.line("lines printed: %d", Captured.lines(dup));
|
||||
t.line("");
|
||||
t.line("# logger 'service': <AppenderRef ref=\"Console\"/> and additivity=\"false\"");
|
||||
once.lines().forEach(t::line);
|
||||
t.line("lines printed: %d", Captured.lines(once));
|
||||
t.line("");
|
||||
t.line("# logger 'db': no appender of its own, so it uses the root's through additivity");
|
||||
viaRoot.lines().forEach(t::line);
|
||||
t.line("lines printed: %d", Captured.lines(viaRoot));
|
||||
assertThat(Captured.lines(dup)).isEqualTo(2);
|
||||
assertThat(Captured.lines(once)).isEqualTo(1);
|
||||
assertThat(Captured.lines(viaRoot)).isEqualTo(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
import com.ankurm.log4j2levels.service.UserService;
|
||||
import org.apache.logging.log4j.Level;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.core.config.Configurator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/** Transcript 06: where DIAG and PERF land and what they do at each threshold. */
|
||||
@SpringBootTest
|
||||
class CustomLevelsTest {
|
||||
|
||||
@Autowired
|
||||
UserService service;
|
||||
|
||||
@Test
|
||||
void customLevelsSlotIntoTheHierarchyByTheirIntLevel() {
|
||||
Logger logger = LogManager.getLogger("custom.demo");
|
||||
try (Transcript t = Transcript.open("06-custom-levels.txt")) {
|
||||
t.line("# every registered level, most severe first (OFF and ALL left out)");
|
||||
Arrays.stream(Level.values())
|
||||
.filter(l -> l != Level.OFF && l != Level.ALL)
|
||||
.sorted(Comparator.comparingInt(Level::intLevel))
|
||||
.forEach(l -> t.line("%-5s %d", l.name(), l.intLevel()));
|
||||
t.line("");
|
||||
t.line("# lookups");
|
||||
t.line("Level.getLevel(\"DIAG\") = %s", Level.getLevel("DIAG"));
|
||||
t.line("Level.getLevel(\"NOPE\") = %s", Level.getLevel("NOPE"));
|
||||
t.line("Level.forName(\"DIAG\", 999) = %s (intLevel %d)", Level.forName("DIAG", 999),
|
||||
Level.forName("DIAG", 999).intLevel());
|
||||
t.line("");
|
||||
t.line("# which of DIAG and PERF are enabled at each threshold");
|
||||
t.line("%-10s %-5s %-5s", "threshold", "DIAG", "PERF");
|
||||
for (Level threshold : new Level[] {Level.WARN, Levels.DIAG, Level.INFO, Levels.PERF, Level.DEBUG}) {
|
||||
Configurator.setLevel("custom.demo", threshold);
|
||||
t.line("%-10s %-5s %-5s", threshold.name(), logger.isEnabled(Levels.DIAG) ? "yes" : "-",
|
||||
logger.isEnabled(Levels.PERF) ? "yes" : "-");
|
||||
}
|
||||
Configurator.setLevel("custom.demo", (Level) null);
|
||||
t.line("");
|
||||
Logger xml = LogManager.getLogger("com.ankurm.log4j2levels.diag.Probe");
|
||||
t.line("# logger configured in XML with level=\"diag\" (lower case)");
|
||||
for (Level event : new Level[] {Level.ERROR, Level.WARN, Levels.DIAG, Level.INFO, Levels.PERF, Level.DEBUG}) {
|
||||
t.line("%-5s %s", event.name(), xml.isEnabled(event) ? "yes" : "-");
|
||||
}
|
||||
t.line("");
|
||||
t.line("# UserService.diagnose() with the service package at DEBUG: both custom lines print");
|
||||
String out = Captured.run(service::diagnose);
|
||||
out.lines().forEach(t::line);
|
||||
Configurator.setLevel("com.ankurm.log4j2levels.service", Level.INFO);
|
||||
String atInfo = Captured.run(service::diagnose);
|
||||
Configurator.setLevel("com.ankurm.log4j2levels.service", Level.DEBUG);
|
||||
t.line("# and with it at INFO: only DIAG prints");
|
||||
atInfo.lines().forEach(t::line);
|
||||
assertThat(out).contains("DIAG").contains("PERF");
|
||||
assertThat(atInfo).contains("DIAG").doesNotContain("PERF");
|
||||
}
|
||||
assertThat(Level.getLevel("DIAG")).isNotNull();
|
||||
assertThat(Level.getLevel("NOPE")).isNull();
|
||||
assertThat(Level.forName("DIAG", 999).intLevel()).isEqualTo(350);
|
||||
assertThat(Levels.PERF.intLevel()).isEqualTo(450);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.logging.log4j.Level;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.core.config.Configurator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/** Transcripts 01 and 02: the numbers behind the threshold rule. */
|
||||
@SpringBootTest
|
||||
class LevelsTest {
|
||||
|
||||
private static final Level[] EVENTS = {Level.FATAL, Level.ERROR, Level.WARN, Level.INFO, Level.DEBUG, Level.TRACE};
|
||||
private static final Level[] THRESHOLDS = {Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL, Level.OFF};
|
||||
|
||||
@Test
|
||||
void standardLevelsAndTheirIntValues() {
|
||||
try (Transcript t = Transcript.open("01-standard-levels.txt")) {
|
||||
t.line("# Level.intLevel() for the eight built-in levels, from the log4j-api on the classpath");
|
||||
for (Level level : new Level[] {Level.OFF, Level.FATAL, Level.ERROR, Level.WARN, Level.INFO,
|
||||
Level.DEBUG, Level.TRACE, Level.ALL}) {
|
||||
t.line("%-5s intLevel=%d", level.name(), level.intLevel());
|
||||
}
|
||||
t.line("");
|
||||
t.line("# the rule: an event is enabled when event.isMoreSpecificThan(threshold), i.e. its int is <= the threshold's");
|
||||
t.line("INFO.isMoreSpecificThan(DEBUG) = %s", Level.INFO.isMoreSpecificThan(Level.DEBUG));
|
||||
t.line("DEBUG.isMoreSpecificThan(INFO) = %s", Level.DEBUG.isMoreSpecificThan(Level.INFO));
|
||||
t.line("INFO.isMoreSpecificThan(INFO) = %s", Level.INFO.isMoreSpecificThan(Level.INFO));
|
||||
t.line("FATAL.isMoreSpecificThan(OFF) = %s", Level.FATAL.isMoreSpecificThan(Level.OFF));
|
||||
t.line("TRACE.isMoreSpecificThan(ALL) = %s", Level.TRACE.isMoreSpecificThan(Level.ALL));
|
||||
}
|
||||
assertThat(Level.OFF.intLevel()).isZero();
|
||||
assertThat(Level.FATAL.intLevel()).isEqualTo(100);
|
||||
assertThat(Level.ERROR.intLevel()).isEqualTo(200);
|
||||
assertThat(Level.WARN.intLevel()).isEqualTo(300);
|
||||
assertThat(Level.INFO.intLevel()).isEqualTo(400);
|
||||
assertThat(Level.DEBUG.intLevel()).isEqualTo(500);
|
||||
assertThat(Level.TRACE.intLevel()).isEqualTo(600);
|
||||
assertThat(Level.ALL.intLevel()).isEqualTo(Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void thresholdMatrixAndLinesReallyPrinted() {
|
||||
Logger logger = LogManager.getLogger("matrix.demo");
|
||||
try (Transcript t = Transcript.open("02-threshold-matrix.txt")) {
|
||||
t.line("# rows: the logger's threshold. columns: the event's level. 'yes' = isEnabled(level).");
|
||||
t.line("# last column: lines the real Console appender printed when one event of each level was logged");
|
||||
t.line("%-10s %-5s %-5s %-5s %-5s %-5s %-5s printed", "threshold", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE");
|
||||
for (Level threshold : THRESHOLDS) {
|
||||
Configurator.setLevel("matrix.demo", threshold);
|
||||
StringBuilder row = new StringBuilder(String.format("%-10s", threshold.name()));
|
||||
int enabled = 0;
|
||||
for (Level event : EVENTS) {
|
||||
boolean on = logger.isEnabled(event);
|
||||
if (on) {
|
||||
enabled++;
|
||||
}
|
||||
row.append(String.format(" %-5s", on ? "yes" : "-"));
|
||||
}
|
||||
String out = Captured.run(() -> {
|
||||
for (Level event : EVENTS) {
|
||||
logger.log(event, "one event");
|
||||
}
|
||||
});
|
||||
row.append(String.format(" %d", Captured.lines(out)));
|
||||
t.line(row.toString());
|
||||
assertThat(Captured.lines(out)).isEqualTo(enabled);
|
||||
}
|
||||
} finally {
|
||||
Configurator.setLevel("matrix.demo", (Level) null);
|
||||
}
|
||||
Configurator.setLevel("matrix.demo", Level.INFO);
|
||||
assertThat(logger.isInfoEnabled()).isTrue();
|
||||
assertThat(logger.isDebugEnabled()).isFalse();
|
||||
Configurator.setLevel("matrix.demo", Level.OFF);
|
||||
assertThat(logger.isFatalEnabled()).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.apache.logging.log4j.core.LoggerContext;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Transcript 13: the .properties format, loaded into its own LoggerContext so the application's
|
||||
* configuration is left alone. Plain JUnit on purpose: no Spring, no log4j2-spring.xml.
|
||||
*/
|
||||
class PropertiesConfigTest {
|
||||
|
||||
private static final String BASE = "com.ankurm.log4j2levels.";
|
||||
|
||||
@Test
|
||||
void propertiesFileGivesTheSameLevelsAsTheXml() throws Exception {
|
||||
// new LoggerContext(...) is independent of the one the application uses;
|
||||
// Configurator.initialize(...) with the same class loader would hand back the application's.
|
||||
java.net.URI file = PropertiesConfigTest.class.getResource("/props/log4j2-example.properties").toURI();
|
||||
LoggerContext ctx = new LoggerContext("props-demo", null, file);
|
||||
ctx.start();
|
||||
try (Transcript t = Transcript.open("13-properties-config.txt")) {
|
||||
String location = String.valueOf(ctx.getConfiguration().getConfigurationSource().getLocation());
|
||||
t.line("# loaded from %s", location.substring(location.lastIndexOf('/') + 1));
|
||||
t.line("%-48s %s", "logger", "effective");
|
||||
for (String name : new String[] {BASE + "service.UserService", BASE + "db.UserRepository",
|
||||
BASE + "billing.InvoiceService", "org.example.Unrelated"}) {
|
||||
t.line("%-48s %s", name, ctx.getLogger(name).getLevel());
|
||||
}
|
||||
t.line("service additivity = %s", ctx.getConfiguration().getLoggerConfig(BASE + "service").isAdditive());
|
||||
t.line("db additivity = %s", ctx.getConfiguration().getLoggerConfig(BASE + "db").isAdditive());
|
||||
t.line("appenders: %s", ctx.getConfiguration().getAppenders().keySet());
|
||||
}
|
||||
assertThat(ctx.getLogger(BASE + "service.UserService").getLevel().name()).isEqualTo("DEBUG");
|
||||
assertThat(ctx.getLogger(BASE + "db.UserRepository").getLevel().name()).isEqualTo("ERROR");
|
||||
assertThat(ctx.getLogger("org.example.Unrelated").getLevel().name()).isEqualTo("INFO");
|
||||
assertThat(ctx.getConfiguration().getLoggerConfig(BASE + "service").isAdditive()).isFalse();
|
||||
assertThat(file.toString()).endsWith("log4j2-example.properties");
|
||||
ctx.stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Collects the lines a test prints and writes them to {@code output/NN-name.txt}. The same test
|
||||
* asserts the same numbers, so a line in a transcript is something the build checks.
|
||||
*/
|
||||
public final class Transcript implements AutoCloseable {
|
||||
|
||||
private final Path file;
|
||||
private final List<String> lines = new ArrayList<>();
|
||||
|
||||
private Transcript(Path file) {
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
public static Transcript open(String name) {
|
||||
return new Transcript(Path.of("output", name));
|
||||
}
|
||||
|
||||
public synchronized Transcript line(String format, Object... args) {
|
||||
String text = args.length == 0 ? format : String.format(format, args);
|
||||
lines.add(text);
|
||||
System.out.println(text);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized void close() {
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, lines);
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.ankurm.log4j2levels;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.ankurm.log4j2levels.service.ServiceException;
|
||||
import com.ankurm.log4j2levels.service.UserService;
|
||||
import org.apache.logging.log4j.Level;
|
||||
import org.apache.logging.log4j.core.config.Configurator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/** Transcript 05: the article's UserService, run for real at DEBUG and then at INFO. */
|
||||
@SpringBootTest
|
||||
class UserServiceTest {
|
||||
|
||||
private static final String SERVICE = "com.ankurm.log4j2levels.service";
|
||||
|
||||
@Autowired
|
||||
UserService service;
|
||||
|
||||
private String scenario() {
|
||||
return Captured.run(() -> {
|
||||
service.getUserById(1L);
|
||||
service.getUserById(99L);
|
||||
assertThatThrownBy(() -> service.getUserById(null)).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> service.getUserById(-1L)).isInstanceOf(ServiceException.class);
|
||||
service.processBatchUsers(List.of(1L, 2L));
|
||||
assertThatThrownBy(() -> service.processBatchUsers(List.of(1L, -1L))).isInstanceOf(ServiceException.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameCodeAtDebugAndAtInfo() {
|
||||
String atDebug = scenario();
|
||||
Configurator.setLevel(SERVICE, Level.INFO);
|
||||
String atInfo;
|
||||
try {
|
||||
atInfo = scenario();
|
||||
} finally {
|
||||
Configurator.setLevel(SERVICE, Level.DEBUG);
|
||||
}
|
||||
try (Transcript t = Transcript.open("05-user-service.txt")) {
|
||||
t.line("# service package at DEBUG (what log4j2-spring.xml configures); db package stays at ERROR");
|
||||
atDebug.lines().forEach(t::line);
|
||||
t.line("lines: %d", Captured.lines(atDebug));
|
||||
t.line("");
|
||||
t.line("# the same calls with the service package raised to INFO");
|
||||
atInfo.lines().forEach(t::line);
|
||||
t.line("lines: %d", Captured.lines(atInfo));
|
||||
}
|
||||
assertThat(atDebug).contains("DEBUG c.a.l.s.UserService - Entering getUserById with userId: 1");
|
||||
assertThat(atInfo).doesNotContain("DEBUG");
|
||||
assertThat(atDebug).doesNotContain("SELECT");
|
||||
assertThat(atInfo).contains("FATAL c.a.l.s.UserService");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
# The properties-format equivalent of log4j2-spring.xml (without the custom levels).
|
||||
# Unlike the snippet in the original article, this one declares the Console appender it refers to.
|
||||
status = warn
|
||||
|
||||
appender.console.type = Console
|
||||
appender.console.name = Console
|
||||
appender.console.target = SYSTEM_OUT
|
||||
appender.console.layout.type = PatternLayout
|
||||
appender.console.layout.pattern = %-5level %logger{1.} - %msg%n
|
||||
|
||||
rootLogger.level = info
|
||||
rootLogger.appenderRef.stdout.ref = Console
|
||||
|
||||
# one appender, additivity off: printed once
|
||||
logger.service.name = com.ankurm.log4j2levels.service
|
||||
logger.service.level = debug
|
||||
logger.service.additivity = false
|
||||
logger.service.appenderRef.stdout.ref = Console
|
||||
|
||||
# no appender of its own: uses the root's
|
||||
logger.db.name = com.ankurm.log4j2levels.db
|
||||
logger.db.level = error
|
||||
Reference in New Issue
Block a user