diff --git a/README.md b/README.md index e93af34..1e086b4 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ files. | Directory | Article | What it demonstrates | |---|---|---| +| [`log4j2-levels/`](log4j2-levels) | [Log4j2 Logging Levels Explained: Configuration, Custom Levels and Changing Levels at Runtime](https://ankurm.com/log4j2-logging-levels-complete-guide/) | the threshold rule printed as a matrix, a level inherited from the nearest configured ancestor, a logger with its own appender and default additivity printing every line twice, custom `DIAG`/`PERF` levels between the standard ones, `/actuator/loggers` rejecting a custom level and a `null` reset landing on the root's level instead of the XML's, `logging.level.*` beating the XML and a custom level in that property stopping the app at startup, argument `toString()` counts for six call shapes, and Logback plus Log4j2 on one classpath silently handing everything to Logback | | [`idempotency/`](idempotency) | [Idempotency Keys for POST APIs in Spring Boot (Stripe-Style) with Redis and Postgres](https://ankurm.com/idempotency-keys-spring-boot-redis-postgres/) | one servlet filter and two interchangeable stores: a retried POST after a client timeout creating two payments without a key and one with; 400 / 422 / 409 and replay with `Idempotent-Replayed`; ten simultaneous duplicates (nine `409` on Redis, nine replays on Postgres because the second `INSERT` waits on the first's uncommitted row); a crash after the payment commits leaving Redis with a stuck lock and then a duplicate payment, and Postgres with neither; a handler slower than the Redis lock finishing with nothing stored; the legacy `Asia/Calcutta` zone id that PostgreSQL 16 refuses at connect time | | [`http-service-clients/`](http-service-clients) | [Spring Boot 4 HTTP Service Clients: @HttpExchange Interfaces with RestClient (Complete Guide)](https://ankurm.com/spring-boot-4-http-service-clients/) | `@HttpExchange` interfaces registered with `@ImportHttpServices` and configured under `spring.http.serviceclient..*` (the keys the first version of the post gave are silently ignored), run against a local stub upstream: `defaultStatusHandler` with ProblemDetail decoding, `NotFoundRestClientAdapterDecorator` for `Optional` on a 404, Framework 7 `@Retryable` on the interface vs `RetryTemplate` vs an interceptor vs Resilience4j (call counts side by side, and a retried POST created twice), bearer, API-key and OAuth2 client-credentials auth (`@ClientRegistrationId` ignored without its group configurer), `MockRestServiceServer`, and the `@RestClientTest` slice where a group client is not bound to the mock | | [`pdf-invoice/`](pdf-invoice) | [Generate PDF Invoices in Spring Boot: OpenPDF vs iText vs Flying Saucer (HTML to PDF)](https://ankurm.com/spring-boot-generate-pdf-invoice-openpdf-itext-flying-saucer/) | one invoice rendered by OpenPDF 3.0.5, iText Core 9.8.0 (AGPL 3 or commercial) and Flying Saucer 10.7.0 from a Thymeleaf template, with embedded Noto Sans Devanagari: none of the three shapes Marathi/Hindi conjuncts by default (checked by rendering to PNG against a libraqm reference), OpenPDF's `GlyphLayoutManager` does but breaks text extraction until `ActualText` is on, OpenPDF's static `LayoutProcessor` is JVM-global and breaks other writers, Apache FOP on the classpath did not help, streamed vs buffered failure (`200` + curl exit 18 vs `500`), font subsetting, indicative per-invoice timings | diff --git a/log4j2-levels/.gitignore b/log4j2-levels/.gitignore new file mode 100644 index 0000000..c3ec762 --- /dev/null +++ b/log4j2-levels/.gitignore @@ -0,0 +1,2 @@ +target/ +broken/target/ diff --git a/log4j2-levels/README.md b/log4j2-levels/README.md new file mode 100644 index 0000000..aeae06f --- /dev/null +++ b/log4j2-levels/README.md @@ -0,0 +1,61 @@ +# log4j2-levels + +Companion code for **Log4j2 Logging Levels Explained: Configuration, Custom Levels and Changing +Levels at Runtime** on [ankurm.com](https://ankurm.com/log4j2-logging-levels-complete-guide/). + +A small Spring Boot 4.1 application that uses Log4j2 instead of Logback and shows, with real +output, how the level threshold works, how a level is inherited, why a line can print twice, where +custom levels fit, what `/actuator/loggers` can and cannot change, and what a disabled log call +still costs. There is no `docs/` folder: the explanations live in the article, and every number in +it comes from a file in `output/`. + +| Piece | Version | Checked against | +|---|---|---| +| Spring Boot | 4.1.2 | `maven-metadata.xml` for `org.springframework.boot:spring-boot` | +| Log4j2 | 2.25.5 | what Spring Boot 4.1.2 manages (`log4j2.version` in `spring-boot-dependencies`); `maven-metadata.xml` lists 2.26.1 as newer | +| Logback (only in `broken/`) | 1.5.38 | what Spring Boot 4.1.2 manages | +| JDK | 25 | Temurin 25.0.5 | + +## Run it + +```bash +export JAVA_HOME=/path/to/jdk-25 +mvn -B test # 9 tests, transcripts 01-08 and 13 written to output/ +./scripts/run-all.sh # tests, then the packaged jar under real JVMs (transcripts 09-12) +``` + +## What is where + +| File | What it is | +|---|---| +| `src/main/resources/log4j2-spring.xml` | the configuration: two custom levels, a Console appender, five loggers (one per behaviour) | +| `src/main/java/.../Levels.java` | `DIAG` (350) and `PERF` (450) registered with `Level.forName` | +| `src/main/java/.../service/UserService.java` | the article's `UserService`, compilable, one real call per level | +| `src/main/java/.../db/UserRepository.java` | in-memory repository whose package is configured at `ERROR` | +| `src/main/java/.../billing/InvoiceService.java` | a package with no entry of its own in the XML | +| `src/main/java/.../web/LogController.java` | `GET /demo/log?name=...` logs one line per level and reports which were enabled | +| `src/test/java/.../` | one test class per transcript; each asserts the numbers it prints | +| `src/test/resources/props/log4j2-example.properties` | the properties-format version of the configuration, loaded by `PropertiesConfigTest` into its own `LoggerContext` | +| `scripts/` | `run-all.sh`, `live-run.sh` (jar plus curl), `both-logging.sh` (the broken classpath), `lib.sh` | +| `broken/pom.xml` | the same sources with the Logback exclusion removed | + +## Captured output + +| File | Shows | +|---|---| +| `00-test-summary.txt` | test counts | +| `01-standard-levels.txt` | `intLevel` of the eight built-in levels and the `isMoreSpecificThan` rule | +| `02-threshold-matrix.txt` | every threshold against every event level, with the lines the real appender printed | +| `03-effective-levels.txt` | which configured logger each name inherits its level from | +| `04-additivity.txt` | one line printed twice (appender on the logger plus default additivity) | +| `05-user-service.txt` | `UserService` at DEBUG and at INFO | +| `06-custom-levels.txt` | where `DIAG` and `PERF` sit and what each threshold lets through | +| `07-argument-evaluation.txt` | how often `toString()` ran for six call shapes, with the level off and on | +| `08-actuator-loggers.txt` | `/actuator/loggers` GET and POST, reset, rejected values, the listing | +| `09-live-run.txt` | the same behaviour from the packaged jar under Tomcat | +| `10-property-overrides.txt` | `logging.level.*` against `log4j2-spring.xml`, and a custom level in a property | +| `11-both-logging.txt` | Logback and Log4j2 both on the classpath | +| `12-dependency-tree.txt` | `mvn dependency:tree` for both builds | +| `13-properties-config.txt` | the `.properties` format giving the same levels and additivity as the XML | + +`11-both-logging.txt` contains timestamps, a PID and a thread name; those differ on every run. diff --git a/log4j2-levels/broken/pom.xml b/log4j2-levels/broken/pom.xml new file mode 100644 index 0000000..a3a9f7a --- /dev/null +++ b/log4j2-levels/broken/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.2 + + + + com.ankurm + log4j2-levels-both-logging + 1.0.0 + log4j2-levels + Log4j2 logging levels on Spring Boot 4.1: the threshold rule, per-package config, additivity, custom levels, Actuator runtime changes, and what a disabled log call still costs + + + 25 + + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-log4j2 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + ../src/main/java + ../src/main/resources + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/log4j2-levels/output/00-test-summary.txt b/log4j2-levels/output/00-test-summary.txt new file mode 100644 index 0000000..0a380ea --- /dev/null +++ b/log4j2-levels/output/00-test-summary.txt @@ -0,0 +1,8 @@ +Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 3.511 s -- in com.ankurm.log4j2levels.LevelsTest +Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.021 s -- in com.ankurm.log4j2levels.ArgumentEvaluationTest +Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.042 s -- in com.ankurm.log4j2levels.ConfigTest +Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.862 s -- in com.ankurm.log4j2levels.ActuatorLoggersTest +Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 s -- in com.ankurm.log4j2levels.UserServiceTest +Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.025 s -- in com.ankurm.log4j2levels.PropertiesConfigTest +Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 s -- in com.ankurm.log4j2levels.CustomLevelsTest +Tests run: 9, Failures: 0, Errors: 0, Skipped: 0 diff --git a/log4j2-levels/output/01-standard-levels.txt b/log4j2-levels/output/01-standard-levels.txt new file mode 100644 index 0000000..0152480 --- /dev/null +++ b/log4j2-levels/output/01-standard-levels.txt @@ -0,0 +1,16 @@ +# Level.intLevel() for the eight built-in levels, from the log4j-api on the classpath +OFF intLevel=0 +FATAL intLevel=100 +ERROR intLevel=200 +WARN intLevel=300 +INFO intLevel=400 +DEBUG intLevel=500 +TRACE intLevel=600 +ALL intLevel=2147483647 + +# the rule: an event is enabled when event.isMoreSpecificThan(threshold), i.e. its int is <= the threshold's +INFO.isMoreSpecificThan(DEBUG) = true +DEBUG.isMoreSpecificThan(INFO) = false +INFO.isMoreSpecificThan(INFO) = true +FATAL.isMoreSpecificThan(OFF) = false +TRACE.isMoreSpecificThan(ALL) = true diff --git a/log4j2-levels/output/02-threshold-matrix.txt b/log4j2-levels/output/02-threshold-matrix.txt new file mode 100644 index 0000000..479dbec --- /dev/null +++ b/log4j2-levels/output/02-threshold-matrix.txt @@ -0,0 +1,10 @@ +# rows: the logger's threshold. columns: the event's level. 'yes' = isEnabled(level). +# last column: lines the real Console appender printed when one event of each level was logged +threshold FATAL ERROR WARN INFO DEBUG TRACE printed +TRACE yes yes yes yes yes yes 6 +DEBUG yes yes yes yes yes - 5 +INFO yes yes yes yes - - 4 +WARN yes yes yes - - - 3 +ERROR yes yes - - - - 2 +FATAL yes - - - - - 1 +OFF - - - - - - 0 diff --git a/log4j2-levels/output/03-effective-levels.txt b/log4j2-levels/output/03-effective-levels.txt new file mode 100644 index 0000000..cc0c0b0 --- /dev/null +++ b/log4j2-levels/output/03-effective-levels.txt @@ -0,0 +1,9 @@ +# configuration file Spring Boot handed to Log4j2: log4j2-spring.xml + +logger effective level comes from +com.ankurm.log4j2levels.service.UserService DEBUG com.ankurm.log4j2levels.service +com.ankurm.log4j2levels.service.sub.Deeper DEBUG com.ankurm.log4j2levels.service +com.ankurm.log4j2levels.db.UserRepository ERROR com.ankurm.log4j2levels.db +com.ankurm.log4j2levels.billing.InvoiceService INFO root +org.example.Unrelated INFO root +com.ankurm.log4j2levels.diag.Whatever DIAG com.ankurm.log4j2levels.diag diff --git a/log4j2-levels/output/04-additivity.txt b/log4j2-levels/output/04-additivity.txt new file mode 100644 index 0000000..a9a4b84 --- /dev/null +++ b/log4j2-levels/output/04-additivity.txt @@ -0,0 +1,12 @@ +# logger 'dup': and additivity left at its default (true) +INFO c.a.l.dup - order 7 shipped +INFO c.a.l.dup - order 7 shipped +lines printed: 2 + +# logger 'service': and additivity="false" +INFO c.a.l.service - order 7 shipped +lines printed: 1 + +# logger 'db': no appender of its own, so it uses the root's through additivity +ERROR c.a.l.db - order 7 failed +lines printed: 1 diff --git a/log4j2-levels/output/05-user-service.txt b/log4j2-levels/output/05-user-service.txt new file mode 100644 index 0000000..5a62ddc --- /dev/null +++ b/log4j2-levels/output/05-user-service.txt @@ -0,0 +1,45 @@ +# service package at DEBUG (what log4j2-spring.xml configures); db package stays at ERROR +DEBUG c.a.l.s.UserService - Entering getUserById with userId: 1 +INFO c.a.l.s.UserService - Fetching user with ID: 1 +DEBUG c.a.l.s.UserService - Successfully retrieved user: asha +DEBUG c.a.l.s.UserService - Entering getUserById with userId: 99 +INFO c.a.l.s.UserService - Fetching user with ID: 99 +INFO c.a.l.s.UserService - User not found for ID: 99 +DEBUG c.a.l.s.UserService - Entering getUserById with userId: null +WARN c.a.l.s.UserService - getUserById called with null userId +DEBUG c.a.l.s.UserService - Entering getUserById with userId: -1 +INFO c.a.l.s.UserService - Fetching user with ID: -1 +ERROR c.a.l.d.UserRepository - connection reset while loading user -1 +ERROR c.a.l.s.UserService - Database error while fetching user with ID: -1 +com.ankurm.log4j2levels.db.DatabaseException: connection reset + at com.ankurm.log4j2levels.db.UserRepository.findById(UserRepository.java:24) +INFO c.a.l.s.UserService - Starting batch user processing +DEBUG c.a.l.s.UserService - Processed 2 users in batch +INFO c.a.l.s.UserService - Batch processing completed, 2 processed +INFO c.a.l.s.UserService - Starting batch user processing +ERROR c.a.l.d.UserRepository - connection reset while loading user -1 +FATAL c.a.l.s.UserService - Critical failure in batch processing, giving up. +com.ankurm.log4j2levels.db.DatabaseException: connection reset + at com.ankurm.log4j2levels.db.UserRepository.findById(UserRepository.java:24) +INFO c.a.l.s.UserService - Batch processing completed, 1 processed +lines: 23 + +# the same calls with the service package raised to INFO +INFO c.a.l.s.UserService - Fetching user with ID: 1 +INFO c.a.l.s.UserService - Fetching user with ID: 99 +INFO c.a.l.s.UserService - User not found for ID: 99 +WARN c.a.l.s.UserService - getUserById called with null userId +INFO c.a.l.s.UserService - Fetching user with ID: -1 +ERROR c.a.l.d.UserRepository - connection reset while loading user -1 +ERROR c.a.l.s.UserService - Database error while fetching user with ID: -1 +com.ankurm.log4j2levels.db.DatabaseException: connection reset + at com.ankurm.log4j2levels.db.UserRepository.findById(UserRepository.java:24) +INFO c.a.l.s.UserService - Starting batch user processing +INFO c.a.l.s.UserService - Batch processing completed, 2 processed +INFO c.a.l.s.UserService - Starting batch user processing +ERROR c.a.l.d.UserRepository - connection reset while loading user -1 +FATAL c.a.l.s.UserService - Critical failure in batch processing, giving up. +com.ankurm.log4j2levels.db.DatabaseException: connection reset + at com.ankurm.log4j2levels.db.UserRepository.findById(UserRepository.java:24) +INFO c.a.l.s.UserService - Batch processing completed, 1 processed +lines: 17 diff --git a/log4j2-levels/output/06-custom-levels.txt b/log4j2-levels/output/06-custom-levels.txt new file mode 100644 index 0000000..4d7270e --- /dev/null +++ b/log4j2-levels/output/06-custom-levels.txt @@ -0,0 +1,36 @@ +# every registered level, most severe first (OFF and ALL left out) +FATAL 100 +ERROR 200 +WARN 300 +DIAG 350 +INFO 400 +PERF 450 +DEBUG 500 +TRACE 600 + +# lookups +Level.getLevel("DIAG") = DIAG +Level.getLevel("NOPE") = null +Level.forName("DIAG", 999) = DIAG (intLevel 350) + +# which of DIAG and PERF are enabled at each threshold +threshold DIAG PERF +WARN - - +DIAG yes - +INFO yes - +PERF yes yes +DEBUG yes yes + +# logger configured in XML with level="diag" (lower case) +ERROR yes +WARN yes +DIAG yes +INFO - +PERF - +DEBUG - + +# UserService.diagnose() with the service package at DEBUG: both custom lines print +DIAG c.a.l.s.UserService - cache size = 42 +PERF c.a.l.s.UserService - lookup took 3 ms +# and with it at INFO: only DIAG prints +DIAG c.a.l.s.UserService - cache size = 42 diff --git a/log4j2-levels/output/07-argument-evaluation.txt b/log4j2-levels/output/07-argument-evaluation.txt new file mode 100644 index 0000000..6bb8e9c --- /dev/null +++ b/log4j2-levels/output/07-argument-evaluation.txt @@ -0,0 +1,8 @@ +# times user.toString() ran for one call, threshold INFO (debug off) vs DEBUG (debug on) +call debug off debug on +debug("User: " + user) 1 1 +debug("User: {}", user) 0 1 +debug("User: {}", user.toString()) 1 1 +debug(() -> "User: " + user) 0 1 +debug("User: {}", () -> user.toString()) 0 1 +if (isDebugEnabled()) debug("User: " + user) 0 1 diff --git a/log4j2-levels/output/08-actuator-loggers.txt b/log4j2-levels/output/08-actuator-loggers.txt new file mode 100644 index 0000000..7837969 --- /dev/null +++ b/log4j2-levels/output/08-actuator-loggers.txt @@ -0,0 +1,40 @@ +# 1. a logger the XML configures, and one that only inherits from it +GET /actuator/loggers/com.ankurm.log4j2levels.service -> 200 {"configuredLevel":"DEBUG","effectiveLevel":"DEBUG"} +GET /actuator/loggers/com.ankurm.log4j2levels.service.UserService -> 200 {"effectiveLevel":"DEBUG"} + +# 2. raise the service package to TRACE and log a trace line through UserService's logger +POST /actuator/loggers/com.ankurm.log4j2levels.service {"configuredLevel":"TRACE"} -> 204 +GET /actuator/loggers/com.ankurm.log4j2levels.service.UserService -> 200 {"effectiveLevel":"TRACE"} +printed: TRACE c.a.l.s.UserService - probe + +# 3. reset it with configuredLevel null +POST /actuator/loggers/com.ankurm.log4j2levels.service {"configuredLevel":null} -> 204 +GET /actuator/loggers/com.ankurm.log4j2levels.service -> 200 {"configuredLevel":"INFO","effectiveLevel":"INFO"} +GET /actuator/loggers/com.ankurm.log4j2levels.service.UserService -> 200 {"effectiveLevel":"INFO"} +a debug line after the reset printed: nothing +POST /actuator/loggers/com.ankurm.log4j2levels.service {"configuredLevel":"DEBUG"} -> 204 + +# 4. a logger with no entry in the XML: set, then reset +GET /actuator/loggers/com.ankurm.log4j2levels.billing.InvoiceService -> 200 {"effectiveLevel":"INFO"} +POST /actuator/loggers/com.ankurm.log4j2levels.billing {"configuredLevel":"TRACE"} -> 204 +GET /actuator/loggers/com.ankurm.log4j2levels.billing.InvoiceService -> 200 {"effectiveLevel":"TRACE"} +POST /actuator/loggers/com.ankurm.log4j2levels.billing {"configuredLevel":null} -> 204 +GET /actuator/loggers/com.ankurm.log4j2levels.billing.InvoiceService -> 200 {"effectiveLevel":"INFO"} + +# 5. what the endpoint will not take +POST /actuator/loggers/com.ankurm.log4j2levels.service {"configuredLevel":"DIAG"} -> 400 +POST /actuator/loggers/com.ankurm.log4j2levels.service {"configuredLevel":"debug"} -> 204 +POST /actuator/loggers/com.ankurm.log4j2levels.service {"configuredLevel":"LOUD"} -> 400 +POST /actuator/loggers/com.ankurm.log4j2levels.service {"configuredLevel":"DEBUG"} -> 204 + +# 6. the root logger +GET /actuator/loggers/ROOT -> 404 +POST /actuator/loggers/ROOT {"configuredLevel":"WARN"} -> 204 +GET /actuator/loggers/com.ankurm.log4j2levels.billing.InvoiceService -> 200 {"effectiveLevel":"WARN"} +POST /actuator/loggers/ROOT {"configuredLevel":"INFO"} -> 204 +GET /actuator/loggers/ROOT -> 404 + +# 7. the full listing: the levels it offers, and how the root logger is named +GET /actuator/loggers -> "levels":["OFF","FATAL","ERROR","WARN","INFO","DEBUG","TRACE"] + entry: "ROOT":{"effectiveLevel":"INFO"} + lists com.ankurm.log4j2levels.service: true diff --git a/log4j2-levels/output/09-live-run.txt b/log4j2-levels/output/09-live-run.txt new file mode 100644 index 0000000..bbf4819 --- /dev/null +++ b/log4j2-levels/output/09-live-run.txt @@ -0,0 +1,42 @@ +# one request per logger name: JSON says which levels are enabled, the console shows what printed +$ curl 'localhost:18091/demo/log?name=com.ankurm.log4j2levels.service.Probe' +{"FATAL":true,"ERROR":true,"WARN":true,"DIAG":true,"INFO":true,"PERF":true,"DEBUG":true,"TRACE":false} [HTTP 200] +FATAL c.a.l.s.Probe - demo line at FATAL +ERROR c.a.l.s.Probe - demo line at ERROR +WARN c.a.l.s.Probe - demo line at WARN +DIAG c.a.l.s.Probe - demo line at DIAG +INFO c.a.l.s.Probe - demo line at INFO +PERF c.a.l.s.Probe - demo line at PERF +DEBUG c.a.l.s.Probe - demo line at DEBUG + +$ curl 'localhost:18091/demo/log?name=com.ankurm.log4j2levels.billing.Probe' +{"FATAL":true,"ERROR":true,"WARN":true,"DIAG":true,"INFO":true,"PERF":false,"DEBUG":false,"TRACE":false} [HTTP 200] +FATAL c.a.l.b.Probe - demo line at FATAL +ERROR c.a.l.b.Probe - demo line at ERROR +WARN c.a.l.b.Probe - demo line at WARN +DIAG c.a.l.b.Probe - demo line at DIAG +INFO c.a.l.b.Probe - demo line at INFO + +$ curl 'localhost:18091/demo/log?name=com.ankurm.log4j2levels.db.Probe' +{"FATAL":true,"ERROR":true,"WARN":false,"DIAG":false,"INFO":false,"PERF":false,"DEBUG":false,"TRACE":false} [HTTP 200] +FATAL c.a.l.d.Probe - demo line at FATAL +ERROR c.a.l.d.Probe - demo line at ERROR + +$ curl 'localhost:18091/demo/log?name=com.ankurm.log4j2levels.diag.Probe' +{"FATAL":true,"ERROR":true,"WARN":true,"DIAG":true,"INFO":false,"PERF":false,"DEBUG":false,"TRACE":false} [HTTP 200] +FATAL c.a.l.d.Probe - demo line at FATAL +ERROR c.a.l.d.Probe - demo line at ERROR +WARN c.a.l.d.Probe - demo line at WARN +DIAG c.a.l.d.Probe - demo line at DIAG + +# raise billing to TRACE with Actuator, repeat the request +$ curl -X POST -H 'Content-Type: application/json' -d '{"configuredLevel":"TRACE"}' localhost:18091/actuator/loggers/com.ankurm.log4j2levels.billing + [HTTP 204] +{"FATAL":true,"ERROR":true,"WARN":true,"DIAG":true,"INFO":true,"PERF":true,"DEBUG":true,"TRACE":true} [HTTP 200] +TRACE lines printed: 1 + +# the ROOT logger over real HTTP + [HTTP 404] + [HTTP 404] +# a level the endpoint does not know +{"timestamp":"2026-11-17T17:49:52.029Z","status":400,"error":"Bad Request","path":"/actuator/loggers/com.ankurm.log4j2levels.billing"} [HTTP 400] diff --git a/log4j2-levels/output/10-property-overrides.txt b/log4j2-levels/output/10-property-overrides.txt new file mode 100644 index 0000000..0853eec --- /dev/null +++ b/log4j2-levels/output/10-property-overrides.txt @@ -0,0 +1,32 @@ +# log4j2-spring.xml says: com.ankurm.log4j2levels.service = DEBUG, root = INFO + +# 1. --logging.level.com.ankurm.log4j2levels.service=WARN on the command line +{"configuredLevel":"WARN","effectiveLevel":"WARN"} [HTTP 200] + +# 2. the same override as an environment variable +{"configuredLevel":"TRACE","effectiveLevel":"TRACE"} [HTTP 200] + +# 3. --logging.level.root=ERROR, which the XML's root level should be competing with +{"effectiveLevel":"ERROR"} [HTTP 200] + +# 4. a custom level through the property: --logging.level.com.ankurm.log4j2levels.service=DIAG +app did not start; first lines of its output: +ERROR o.s.b.d.LoggingFailureAnalysisReporter - +*************************** +APPLICATION FAILED TO START +*************************** +Description: +Failed to bind properties under 'logging.level.com.ankurm.log4j2levels.service' to org.springframework.boot.logging.LogLevel: + Property: logging.level.com.ankurm.log4j2levels.service + Value: "DIAG" + Origin: "logging.level.com.ankurm.log4j2levels.service" from property source "commandLineArgs" + Reason: failed to convert java.lang.String to org.springframework.boot.logging.LogLevel (caused by java.lang.IllegalArgumentException: No enum constant org.springframework.boot.logging.LogLevel.DIAG) +Action: +Update your application's configuration. The following values are valid: + DEBUG + ERROR + FATAL + INFO + +# 5. a custom level in a separate logger written as log4j2 itself reads it (see diag in the XML) +{"configuredLevel":"DIAG","effectiveLevel":"DIAG"} [HTTP 200] diff --git a/log4j2-levels/output/11-both-logging.txt b/log4j2-levels/output/11-both-logging.txt new file mode 100644 index 0000000..826f21b --- /dev/null +++ b/log4j2-levels/output/11-both-logging.txt @@ -0,0 +1,20 @@ +# the same sources and the same dependencies as the module, minus the on spring-boot-starter-logging +$ java -jar broken/target/log4j2-levels-both-logging-1.0.0.jar +(still running after 30 s: the application started) +$ curl 'localhost:18097/demo/log?name=com.ankurm.log4j2levels.service.Probe' (the XML sets this package to DEBUG) +{"FATAL":true,"ERROR":true,"WARN":true,"DIAG":true,"INFO":true,"PERF":true,"DEBUG":false,"TRACE":false} +$ curl localhost:18097/actuator/loggers/com.ankurm.log4j2levels.service +{"effectiveLevel":"INFO"} + +# what the application printed (SLF4J startup notes, then the lines from the request above) +SLF4J(W): Class path contains multiple SLF4J providers. +SLF4J(W): Found provider [ch.qos.logback.classic.spi.LogbackServiceProvider@14acaea5] +SLF4J(W): Found provider [org.apache.logging.slf4j.SLF4JServiceProvider@46d56d67] +SLF4J(W): See https://www.slf4j.org/codes.html#multiple_bindings for an explanation. +SLF4J(I): Actual provider is of type [ch.qos.logback.classic.spi.LogbackServiceProvider@14acaea5] +2026-11-17T23:20:47.393+05:30 ERROR 3732 --- [log4j2-levels] [io-18097-exec-1] com.ankurm.log4j2levels.service.Probe : demo line at FATAL +2026-11-17T23:20:47.394+05:30 ERROR 3732 --- [log4j2-levels] [io-18097-exec-1] com.ankurm.log4j2levels.service.Probe : demo line at ERROR +2026-11-17T23:20:47.394+05:30 WARN 3732 --- [log4j2-levels] [io-18097-exec-1] com.ankurm.log4j2levels.service.Probe : demo line at WARN +2026-11-17T23:20:47.394+05:30 WARN 3732 --- [log4j2-levels] [io-18097-exec-1] com.ankurm.log4j2levels.service.Probe : demo line at DIAG +2026-11-17T23:20:47.394+05:30 INFO 3732 --- [log4j2-levels] [io-18097-exec-1] com.ankurm.log4j2levels.service.Probe : demo line at INFO +2026-11-17T23:20:47.394+05:30 INFO 3732 --- [log4j2-levels] [io-18097-exec-1] com.ankurm.log4j2levels.service.Probe : demo line at PERF diff --git a/log4j2-levels/output/12-dependency-tree.txt b/log4j2-levels/output/12-dependency-tree.txt new file mode 100644 index 0000000..47aad6e --- /dev/null +++ b/log4j2-levels/output/12-dependency-tree.txt @@ -0,0 +1,24 @@ +# mvn dependency:tree for the module (Log4j2 only) + com.ankurm:log4j2-levels:jar:1.0.0 + \- org.springframework.boot:spring-boot-starter-log4j2:jar:4.1.2:compile + +- org.apache.logging.log4j:log4j-slf4j2-impl:jar:2.25.5:compile + | +- org.apache.logging.log4j:log4j-api:jar:2.25.5:compile + | \- org.slf4j:slf4j-api:jar:2.0.20:compile + +- org.apache.logging.log4j:log4j-core:jar:2.25.5:compile + \- org.apache.logging.log4j:log4j-jul:jar:2.25.5:compile + +# mvn dependency:tree for broken/pom.xml (exclusions removed) + com.ankurm:log4j2-levels-both-logging:jar:1.0.0 + +- org.springframework.boot:spring-boot-starter-webmvc:jar:4.1.2:compile + | \- org.springframework.boot:spring-boot-starter:jar:4.1.2:compile + | \- org.springframework.boot:spring-boot-starter-logging:jar:4.1.2:compile + | +- ch.qos.logback:logback-classic:jar:1.5.38:compile + | | \- ch.qos.logback:logback-core:jar:1.5.38:compile + | +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.25.5:compile + | \- org.slf4j:jul-to-slf4j:jar:2.0.20:compile + \- org.springframework.boot:spring-boot-starter-log4j2:jar:4.1.2:compile + +- org.apache.logging.log4j:log4j-slf4j2-impl:jar:2.25.5:compile + | +- org.apache.logging.log4j:log4j-api:jar:2.25.5:compile + | \- org.slf4j:slf4j-api:jar:2.0.20:compile + +- org.apache.logging.log4j:log4j-core:jar:2.25.5:compile + \- org.apache.logging.log4j:log4j-jul:jar:2.25.5:compile diff --git a/log4j2-levels/output/13-properties-config.txt b/log4j2-levels/output/13-properties-config.txt new file mode 100644 index 0000000..2a0c886 --- /dev/null +++ b/log4j2-levels/output/13-properties-config.txt @@ -0,0 +1,9 @@ +# loaded from log4j2-example.properties +logger effective +com.ankurm.log4j2levels.service.UserService DEBUG +com.ankurm.log4j2levels.db.UserRepository ERROR +com.ankurm.log4j2levels.billing.InvoiceService INFO +org.example.Unrelated INFO +service additivity = false +db additivity = true +appenders: [Console] diff --git a/log4j2-levels/pom.xml b/log4j2-levels/pom.xml new file mode 100644 index 0000000..5e2a1bd --- /dev/null +++ b/log4j2-levels/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.1.2 + + + + com.ankurm + log4j2-levels + 1.0.0 + log4j2-levels + Log4j2 logging levels on Spring Boot 4.1: the threshold rule, per-package config, additivity, custom levels, Actuator runtime changes, and what a disabled log call still costs + + + 25 + + + + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-log4j2 + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-logging + + + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + org.springframework.boot + spring-boot-starter-logging + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/log4j2-levels/scripts/both-logging.sh b/log4j2-levels/scripts/both-logging.sh new file mode 100755 index 0000000..2ad4e51 --- /dev/null +++ b/log4j2-levels/scripts/both-logging.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Transcripts 11 and 12: what happens when Logback and Log4j2 are both on the classpath, and the +# dependency tree of the working build next to the broken one. +set -uo pipefail +source "$(dirname "$0")/lib.sh" +mkdir -p output +[ -f "$JAR" ] || mvn -B -q package -DskipTests +mvn -B -q -f broken/pom.xml package -DskipTests 2>&1 | grep -E 'ERROR|BUILD' | head -5 + +{ + echo "# the same sources and the same dependencies as the module, minus the on spring-boot-starter-logging" + echo "\$ java -jar broken/target/log4j2-levels-both-logging-1.0.0.jar" + java -jar broken/target/log4j2-levels-both-logging-1.0.0.jar --server.port=18097 > /tmp/l4j-both.log 2>&1 & + BOTH=$! + for _ in $(seq 1 30); do kill -0 "$BOTH" 2>/dev/null || break; sleep 1; done + if kill -0 "$BOTH" 2>/dev/null; then + echo "(still running after 30 s: the application started)" + echo "\$ curl 'localhost:18097/demo/log?name=com.ankurm.log4j2levels.service.Probe' (the XML sets this package to DEBUG)" + curl -s --noproxy '*' "localhost:18097/demo/log?name=com.ankurm.log4j2levels.service.Probe" ; echo + echo "\$ curl localhost:18097/actuator/loggers/com.ankurm.log4j2levels.service" + curl -s --noproxy '*' "localhost:18097/actuator/loggers/com.ankurm.log4j2levels.service" ; echo + kill "$BOTH"; wait "$BOTH" 2>/dev/null + else + wait "$BOTH"; echo "exit code: $?" + fi + echo; echo '# what the application printed (SLF4J startup notes, then the lines from the request above)' + grep -E 'SLF4J|Probe' /tmp/l4j-both.log +} > output/11-both-logging.txt 2>&1 + +{ + FILTER='org.apache.logging.log4j,ch.qos.logback,org.slf4j' + echo "# mvn dependency:tree for the module (Log4j2 only)" + mvn -B -f pom.xml dependency:tree -Dincludes="$FILTER" -DoutputFile=/tmp/l4j-tree-good.txt > /dev/null 2>&1 + sed 's/^/ /' /tmp/l4j-tree-good.txt + echo + echo "# mvn dependency:tree for broken/pom.xml (exclusions removed)" + mvn -B -f broken/pom.xml dependency:tree -Dincludes="$FILTER" -DoutputFile=/tmp/l4j-tree-bad.txt > /dev/null 2>&1 + sed 's/^/ /' /tmp/l4j-tree-bad.txt +} > output/12-dependency-tree.txt 2>&1 +echo "wrote output/11-both-logging.txt and output/12-dependency-tree.txt" diff --git a/log4j2-levels/scripts/lib.sh b/log4j2-levels/scripts/lib.sh new file mode 100755 index 0000000..d890079 --- /dev/null +++ b/log4j2-levels/scripts/lib.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# Shared helpers for the live scripts. Source this, do not run it. +set -uo pipefail +cd "$(dirname "$0")/.." +JAR=target/log4j2-levels-1.0.0.jar +PID="" + +start_app() { # start_app [spring args...] + local port=$1 log=$2; shift 2 + setsid nohup java -jar "$JAR" --server.port="$port" "$@" > "$log" 2>&1 < /dev/null & + PID=$! + for _ in $(seq 1 60); do + curl -s --noproxy '*' -o /dev/null "localhost:$port/actuator/health" && return 0 + kill -0 "$PID" 2>/dev/null || return 1 + sleep 1 + done + return 1 +} + +stop_app() { + [ -n "$PID" ] && kill "$PID" 2>/dev/null && wait "$PID" 2>/dev/null + PID="" +} + +# Print the console lines written since the last call (our pattern has no timestamp). +new_lines() { # new_lines + local log=$1 seen=${SEEN:-0} total + total=$(wc -l < "$log") + tail -n +"$((seen + 1))" "$log" + SEEN=$total +} + +http() { # http [json body] -> "status body" + local method=$1 port=$2 path=$3 body=${4:-} + if [ -n "$body" ]; then + curl -s --noproxy '*' -X "$method" -H 'Content-Type: application/json' -d "$body" -w ' [HTTP %{http_code}]' "localhost:$port$path" + else + curl -s --noproxy '*' -X "$method" -w ' [HTTP %{http_code}]' "localhost:$port$path" + fi +} diff --git a/log4j2-levels/scripts/live-run.sh b/log4j2-levels/scripts/live-run.sh new file mode 100755 index 0000000..f2b847a --- /dev/null +++ b/log4j2-levels/scripts/live-run.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +# Transcripts 09 and 10: the real packaged jar under a real Tomcat, driven with curl. +# 09 levels per logger, Actuator changes, the ROOT lookup +# 10 logging.level.* properties and environment variables against log4j2-spring.xml +set -uo pipefail +source "$(dirname "$0")/lib.sh" +P=com.ankurm.log4j2levels +mkdir -p output +[ -f "$JAR" ] || mvn -B -q package -DskipTests + +OUT=output/09-live-run.txt +{ + start_app 18091 /tmp/l4j-live.log || { echo "app did not start"; cat /tmp/l4j-live.log; exit 1; } + SEEN=$(wc -l < /tmp/l4j-live.log) + echo "# one request per logger name: JSON says which levels are enabled, the console shows what printed" + for name in $P.service.Probe $P.billing.Probe $P.db.Probe $P.diag.Probe; do + echo "\$ curl 'localhost:18091/demo/log?name=$name'" + http GET 18091 "/demo/log?name=$name"; echo + new_lines /tmp/l4j-live.log + echo + done + echo "# raise billing to TRACE with Actuator, repeat the request" + echo "\$ curl -X POST -H 'Content-Type: application/json' -d '{\"configuredLevel\":\"TRACE\"}' localhost:18091/actuator/loggers/$P.billing" + http POST 18091 /actuator/loggers/$P.billing '{"configuredLevel":"TRACE"}'; echo + http GET 18091 "/demo/log?name=$P.billing.Probe"; echo + new_lines /tmp/l4j-live.log | grep -c 'TRACE' | sed 's/^/TRACE lines printed: /' + echo + echo "# the ROOT logger over real HTTP" + http GET 18091 /actuator/loggers/ROOT; echo + http GET 18091 /actuator/loggers/root; echo + echo "# a level the endpoint does not know" + http POST 18091 /actuator/loggers/$P.billing '{"configuredLevel":"DIAG"}'; echo + stop_app +} > "$OUT" 2>&1 + +OUT=output/10-property-overrides.txt +{ + P2=$P.service + echo "# log4j2-spring.xml says: $P2 = DEBUG, root = INFO" + echo + echo "# 1. --logging.level.$P2=WARN on the command line" + start_app 18092 /tmp/l4j-p1.log --logging.level.$P2=WARN || { echo "did not start"; head -5 /tmp/l4j-p1.log; } + http GET 18092 /actuator/loggers/$P2; echo; stop_app + echo + echo "# 2. the same override as an environment variable" + LOGGING_LEVEL_COM_ANKURM_LOG4J2LEVELS_SERVICE=TRACE start_app 18093 /tmp/l4j-p2.log || { echo "did not start"; head -5 /tmp/l4j-p2.log; } + http GET 18093 /actuator/loggers/$P2; echo; stop_app + echo + echo "# 3. --logging.level.root=ERROR, which the XML's root level should be competing with" + start_app 18094 /tmp/l4j-p3.log --logging.level.root=ERROR || { echo "did not start"; head -5 /tmp/l4j-p3.log; } + http GET 18094 /actuator/loggers/$P.billing.InvoiceService; echo; stop_app + echo + echo "# 4. a custom level through the property: --logging.level.$P2=DIAG" + if start_app 18095 /tmp/l4j-p4.log --logging.level.$P2=DIAG; then + echo "app started"; http GET 18095 /actuator/loggers/$P2; echo; stop_app + else + echo "app did not start; first lines of its output:" + grep -vE '^\s+at |JAVA_TOOL|^$' /tmp/l4j-p4.log | head -16 + fi + echo + echo "# 5. a custom level in a separate logger written as log4j2 itself reads it (see diag in the XML)" + start_app 18096 /tmp/l4j-p5.log || echo "did not start" + http GET 18096 /actuator/loggers/$P.diag; echo; stop_app +} > "$OUT" 2>&1 +echo "wrote output/09-live-run.txt and output/10-property-overrides.txt" diff --git a/log4j2-levels/scripts/run-all.sh b/log4j2-levels/scripts/run-all.sh new file mode 100755 index 0000000..e153f1a --- /dev/null +++ b/log4j2-levels/scripts/run-all.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# Regenerates every file under output/. +# +# ./scripts/run-all.sh +# +# Needs a JDK 25 and Maven 3.9. Transcripts 01-08 and 13 come out of the test suite, so each number in +# them is an assertion that fails the build if it stops being true. 09-12 are the packaged jar +# under real JVMs, driven with curl. +set -euo pipefail +cd "$(dirname "$0")/.." +mkdir -p output + +echo "== test suite (transcripts 01-08 and 13)" +mvn -B test | tee /tmp/log4j2-levels-mvn.log | grep -E '^\[(INFO|WARNING|ERROR)\] Tests run:' | sed 's/^\[[A-Z]*\] //' > output/00-test-summary.txt + +echo "== packaged jar" +mvn -B -q package -DskipTests + +echo "== live runs (transcripts 09-10)" +./scripts/live-run.sh + +echo "== both loggers on the classpath, dependency trees (transcripts 11-12)" +./scripts/both-logging.sh + +echo +echo "output:" +ls -1 output diff --git a/log4j2-levels/src/main/java/com/ankurm/log4j2levels/Levels.java b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/Levels.java new file mode 100644 index 0000000..1c99a96 --- /dev/null +++ b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/Levels.java @@ -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 }) 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() { + } +} diff --git a/log4j2-levels/src/main/java/com/ankurm/log4j2levels/Log4j2LevelsApplication.java b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/Log4j2LevelsApplication.java new file mode 100644 index 0000000..8d018f3 --- /dev/null +++ b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/Log4j2LevelsApplication.java @@ -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); + } +} diff --git a/log4j2-levels/src/main/java/com/ankurm/log4j2levels/billing/InvoiceService.java b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/billing/InvoiceService.java new file mode 100644 index 0000000..983db5f --- /dev/null +++ b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/billing/InvoiceService.java @@ -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); + } +} diff --git a/log4j2-levels/src/main/java/com/ankurm/log4j2levels/db/DatabaseException.java b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/db/DatabaseException.java new file mode 100644 index 0000000..c457e7c --- /dev/null +++ b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/db/DatabaseException.java @@ -0,0 +1,7 @@ +package com.ankurm.log4j2levels.db; + +public class DatabaseException extends RuntimeException { + public DatabaseException(String message) { + super(message); + } +} diff --git a/log4j2-levels/src/main/java/com/ankurm/log4j2levels/db/User.java b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/db/User.java new file mode 100644 index 0000000..ac76df6 --- /dev/null +++ b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/db/User.java @@ -0,0 +1,4 @@ +package com.ankurm.log4j2levels.db; + +public record User(Long id, String username) { +} diff --git a/log4j2-levels/src/main/java/com/ankurm/log4j2levels/db/UserRepository.java b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/db/UserRepository.java new file mode 100644 index 0000000..b978924 --- /dev/null +++ b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/db/UserRepository.java @@ -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 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); + } +} diff --git a/log4j2-levels/src/main/java/com/ankurm/log4j2levels/service/ServiceException.java b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/service/ServiceException.java new file mode 100644 index 0000000..bc1a346 --- /dev/null +++ b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/service/ServiceException.java @@ -0,0 +1,7 @@ +package com.ankurm.log4j2levels.service; + +public class ServiceException extends RuntimeException { + public ServiceException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/log4j2-levels/src/main/java/com/ankurm/log4j2levels/service/UserService.java b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/service/UserService.java new file mode 100644 index 0000000..af2d467 --- /dev/null +++ b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/service/UserService.java @@ -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 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"); + } +} diff --git a/log4j2-levels/src/main/java/com/ankurm/log4j2levels/web/LogController.java b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/web/LogController.java new file mode 100644 index 0000000..abfe51a --- /dev/null +++ b/log4j2-levels/src/main/java/com/ankurm/log4j2levels/web/LogController.java @@ -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 log(@RequestParam String name) { + Logger logger = LogManager.getLogger(name); + Map 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; + } +} diff --git a/log4j2-levels/src/main/resources/application.yml b/log4j2-levels/src/main/resources/application.yml new file mode 100644 index 0000000..aaa4fe2 --- /dev/null +++ b/log4j2-levels/src/main/resources/application.yml @@ -0,0 +1,11 @@ +spring: + application: + name: log4j2-levels + main: + banner-mode: "off" + +management: + endpoints: + web: + exposure: + include: loggers,health diff --git a/log4j2-levels/src/main/resources/log4j2-spring.xml b/log4j2-levels/src/main/resources/log4j2-spring.xml new file mode 100644 index 0000000..1f160c3 --- /dev/null +++ b/log4j2-levels/src/main/resources/log4j2-spring.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/log4j2-levels/src/test/java/com/ankurm/log4j2levels/ActuatorLoggersTest.java b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/ActuatorLoggersTest.java new file mode 100644 index 0000000..6de1c23 --- /dev/null +++ b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/ActuatorLoggersTest.java @@ -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\"")); + } + } +} diff --git a/log4j2-levels/src/test/java/com/ankurm/log4j2levels/ArgumentEvaluationTest.java b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/ArgumentEvaluationTest.java new file mode 100644 index 0000000..642312c --- /dev/null +++ b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/ArgumentEvaluationTest.java @@ -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 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); + } +} diff --git a/log4j2-levels/src/test/java/com/ankurm/log4j2levels/Captured.java b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/Captured.java new file mode 100644 index 0000000..cbcbab5 --- /dev/null +++ b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/Captured.java @@ -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(); + } +} diff --git a/log4j2-levels/src/test/java/com/ankurm/log4j2levels/ConfigTest.java b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/ConfigTest.java new file mode 100644 index 0000000..a371e44 --- /dev/null +++ b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/ConfigTest.java @@ -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': 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': 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); + } + } +} diff --git a/log4j2-levels/src/test/java/com/ankurm/log4j2levels/CustomLevelsTest.java b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/CustomLevelsTest.java new file mode 100644 index 0000000..cc0b16b --- /dev/null +++ b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/CustomLevelsTest.java @@ -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); + } +} diff --git a/log4j2-levels/src/test/java/com/ankurm/log4j2levels/LevelsTest.java b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/LevelsTest.java new file mode 100644 index 0000000..250a02d --- /dev/null +++ b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/LevelsTest.java @@ -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(); + } +} diff --git a/log4j2-levels/src/test/java/com/ankurm/log4j2levels/PropertiesConfigTest.java b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/PropertiesConfigTest.java new file mode 100644 index 0000000..cb64525 --- /dev/null +++ b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/PropertiesConfigTest.java @@ -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(); + } +} diff --git a/log4j2-levels/src/test/java/com/ankurm/log4j2levels/Transcript.java b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/Transcript.java new file mode 100644 index 0000000..6747d4c --- /dev/null +++ b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/Transcript.java @@ -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 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); + } + } +} diff --git a/log4j2-levels/src/test/java/com/ankurm/log4j2levels/UserServiceTest.java b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/UserServiceTest.java new file mode 100644 index 0000000..3586477 --- /dev/null +++ b/log4j2-levels/src/test/java/com/ankurm/log4j2levels/UserServiceTest.java @@ -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"); + } +} diff --git a/log4j2-levels/src/test/resources/props/log4j2-example.properties b/log4j2-levels/src/test/resources/props/log4j2-example.properties new file mode 100644 index 0000000..82236ed --- /dev/null +++ b/log4j2-levels/src/test/resources/props/log4j2-example.properties @@ -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