001package io.jstach.rainbowgum; 002 003import java.lang.System.Logger.Level; 004import java.lang.ref.WeakReference; 005import java.util.ArrayDeque; 006import java.util.ArrayList; 007import java.util.List; 008import java.util.Objects; 009import java.util.Optional; 010import java.util.Queue; 011import java.util.ServiceLoader; 012import java.util.UUID; 013import java.util.concurrent.ConcurrentLinkedQueue; 014import java.util.concurrent.atomic.AtomicInteger; 015import java.util.concurrent.locks.ReentrantReadWriteLock; 016import java.util.function.Consumer; 017import java.util.function.Function; 018import java.util.function.Supplier; 019 020import org.jspecify.annotations.Nullable; 021 022import io.jstach.rainbowgum.LogRouter.RootRouter; 023import io.jstach.rainbowgum.LogRouter.Router; 024import io.jstach.rainbowgum.spi.RainbowGumServiceProvider; 025 026//@formatter:off 027/** 028 * The main entry point and configuration of RainbowGum logging. 029 * <p> 030 * RainbowGum logging loads configuration through the service loader. While you can 031 * manually set RainbowGum using {@link #set(Supplier)} it is better to register 032 * implementations through the ServiceLoader so that RainbowGum will load prior to any 033 * external logging. 034 * <p> 035 * To register a custom RainbowGum: 036 * 037 * 038{@snippet class="snippets.RainbowGumProviderExample" region="provider" : 039 040class RainbowGumProviderExample implements RainbowGumProvider { 041 042 @Override 043 public Optional<RainbowGum> provide(LogConfig config) { 044 045 Integer bufferSize = config.properties() // 046 .forKey("logging.custom.async.bufferSize") 047 .ofInt() 048 .or(1024) 049 .validateNow(RainbowGumProviderExample.class); 050 051 LogProvider<LogOutput> output = (name, cfg) -> cfg.properties() 052 .forKey("logging.custom.output") 053 .ofProvider(LogOutput::of) 054 .or(LogOutput.ofStandardOut()) 055 .validateNow(RainbowGumProviderExample.class) 056 .provide(name, cfg); 057 058 var gum = RainbowGum.builder() // 059 .route(r -> { 060 r.publisher(PublisherFactory // 061 .async() // 062 .bufferSize(bufferSize) // 063 .build()); 064 r.appender("console", a -> { 065 a.output(output); 066 }); 067 r.level(Level.INFO); 068 }) 069 .build(); 070 071 return Optional.of(gum); 072 } 073 074} 075} 076 * <p> 077 * <strong>Initialization order</strong> - most of the actual work happens in 078 * {@link LogConfig.Builder#build()}, {@link LogRouter.Router.Builder}, and 079 * {@code LogAppenderRegistry}; this is the exact sequence for anyone debugging a 080 * configuration or writing a {@link RainbowGumServiceProvider.RainbowGumProvider}: 081 * <ol> 082 * <li>{@link LogConfig.Builder#build()} builds the shared {@link LogConfig}: 083 * <ol> 084 * <li>Resolve the {@link ServiceRegistry} (default: a new empty one) and 085 * {@link LogProperties} - manually added 086 * {@link RainbowGumServiceProvider.PropertiesProvider}s, else (if a 087 * {@link java.util.ServiceLoader} was supplied) SPI-discovered ones, with system 088 * properties always layered in as a final fallback. Providers receive a temporary 089 * {@link LogAlerts} collector.</li> 090 * <li>Build {@link LogAlerts} and {@link LogMetrics} from properties.</li> 091 * <li>Build the global level resolver ({@code logging.level.*} and 092 * {@code logging.group.*}, plus anything added directly on the builder).</li> 093 * <li>Construct the {@link LogConfig} itself and replay provider alerts into its 094 * configured {@link LogAlerts}. This is also where the {@link LogConfig#globals() 095 * globals} are resolved and the default output/encoder/publisher registries are 096 * created.</li> 097 * <li>Run every {@link RainbowGumServiceProvider.Configurator} (manually added, 098 * then SPI-discovered), highest {@linkplain RainbowGumServiceProvider.Configurator#priority() 099 * priority} first. A configurator returning {@code false} is retried in a later 100 * pass (see {@link RainbowGumServiceProvider#PASSES}) - useful if it depends on 101 * another configurator running first.</li> 102 * <li>Start {@link LogAlerts} - deliberately last, so a configurator's own alert 103 * listener is already registered before alerts decides whether an unobserved 104 * error should refuse startup.</li> 105 * </ol> 106 * </li> 107 * <li>{@link Builder#build()} builds each named {@link LogRouter.Router} (a single 108 * route named {@value LogProperties#DEFAULT_NAME}, unless {@code logging.routes} 109 * names several) via {@link LogRouter.Router.Builder}'s own (package-private) 110 * {@code build()}: 111 * <ol> 112 * <li>Resolve route flags ({@code logging.route.<name>.flags}).</li> 113 * <li>Build a route-scoped level resolver: anything configured directly on the 114 * route builder, layered over {@code logging.route.<name>.level.*}, falling back 115 * to the global level resolver from step 1 (skipped entirely if the route flag 116 * {@code IGNORE_GLOBAL_LEVEL_RESOLVER} is set) - and finally to {@code INFO} if 117 * nothing at all resolves a level.</li> 118 * <li>Resolve appenders - only if none were added programmatically on the route 119 * builder (that check is all-or-nothing: adding even one appender in code skips 120 * property-based resolution entirely). See <strong>Appender resolution</strong> 121 * below.</li> 122 * <li>Resolve the publisher - {@code logging.route.<name>.publisher.uri}, falling 123 * back to a synchronous publisher if unset.</li> 124 * <li>Hand the resolved appenders to the publisher and register the publisher in 125 * the {@link ServiceRegistry}.</li> 126 * </ol> 127 * </li> 128 * <li>{@link #start()} starts the root router, which starts each route's 129 * publisher, which starts each of its appenders, which starts its output (e.g. 130 * opening a file).</li> 131 * </ol> 132 * <strong>Appender resolution</strong> - the part most often mistaken for a bug, 133 * since no appenders are ever added programmatically in the common case: 134 * <ol> 135 * <li>{@code logging.route.<name>.appenders} names the route's appenders; for the 136 * {@value LogProperties#DEFAULT_NAME} route only, a missing value falls back to 137 * the unprefixed {@code logging.appenders}.</li> 138 * <li>If that is <em>still</em> missing: for the default route only, the list 139 * defaults to {@code [file, console]} if {@code logging.file.name} (or Spring 140 * Boot's convention) is set, otherwise just {@code [console]}. A non-default 141 * route with no appenders configured anywhere is a startup failure, not a silent 142 * no-op.</li> 143 * <li>Each named appender then resolves independently. {@code file} and 144 * {@code console} are the two built-in special cases, each with its own output 145 * property/fallback ({@code logging.file.name} then 146 * {@code logging.appender.file.output.uri} for {@code file}; 147 * {@code logging.appender.console.output.uri} falling back to standard-out for 148 * {@code console}). Any other name is fully generic: 149 * {@code logging.appender.<name>.output.uri}/{@code .encoder.uri}/{@code .flags}/ 150 * {@code .type}, with the output's own URI scheme choosing which registered 151 * {@link LogOutput.OutputProvider} builds it.</li> 152 * <li>An output can supply its own encoder by implementing 153 * {@link LogOutput.ProvidesEncoder} (rare, e.g. some structured outputs): with 154 * {@link LogOutput.ProvidesEncoder.Policy#MANDATORY} that encoder is used as-is 155 * and the {@code .encoder.uri} property is never consulted (configuring one anyway 156 * is a startup failure); with {@link LogOutput.ProvidesEncoder.Policy#DEFAULT} 157 * it is only a fallback and the {@code .encoder.uri} property, if set, still wins. 158 * An output that does not implement {@link LogOutput.ProvidesEncoder} at all is 159 * unaffected: the {@code .encoder.uri} property (or the registry's default for the 160 * output's type) always applies.</li> 161 * </ol> 162 */ 163//@formatter:on 164@SuppressWarnings("InvalidInlineTag") 165public sealed interface RainbowGum extends AutoCloseable, LogEventLogger { 166 167 /** 168 * Gets the currently statically bound RainbowGum and will try to load and find one if 169 * there is none currently bound. <strong> This is a blocking operation as in locks 170 * are used and will block indefinitely till a gum has loaded. </strong> If that is 171 * not desired see {@link #getOrNull()}. 172 * @return current RainbowGum or new loaded one. 173 * @throws IllegalStateException if called on a thread that is starting the global 174 * RainbowGum, for example by logging while it loads. See {@link #ofOrNull()}. 175 */ 176 public static RainbowGum of() { 177 var gum = RainbowGumHolder.getOrNullIfStarting(); 178 if (gum == null) { 179 throw new IllegalStateException("RainbowGum component tried to log too early. " 180 + "This is usually caused by dependencies calling logging."); 181 } 182 return gum; 183 } 184 185 /** 186 * Same as {@link #of()} except that it returns <code>null</code> instead of throwing 187 * when called on a thread that is starting the global RainbowGum, for example by 188 * logging while it loads. A logging facade getting <code>null</code> can use 189 * {@link LogRouter#global()}, which holds events until a RainbowGum is bound. 190 * @return current RainbowGum or new loaded one, or <code>null</code> if this thread 191 * is starting one. 192 */ 193 public static @Nullable RainbowGum ofOrNull() { 194 return RainbowGumHolder.getOrNullIfStarting(); 195 } 196 197 /** 198 * Gets the currently statically bound RainbowGum or <code>null</code> if none are 199 * <strong>finished binding</strong>. Unlike {@link #of()} this will never load or 200 * start an instance but rather just gets the currently bound one. It will also never 201 * block and does not wait if one is currently being loaded. This is a snapshot: the 202 * instance can be replaced or closed after it is read. 203 * @return current RainbowGum or <code>null</code> 204 */ 205 public static @Nullable RainbowGum getOrNull() { 206 return RainbowGumHolder.current(); 207 } 208 209 /** 210 * Provides the service loader default based RainbowGum. 211 * @return RainbowGum. 212 */ 213 public static RainbowGum defaults() { 214 return RainbowGumServiceProvider.provide(); 215 } 216 217 /** 218 * Creates a RainbowGum that will <strong>ALWAYS</strong> use the global router. 219 * @param config config. 220 * @return rainbow gum that always uses global router. 221 */ 222 public static RainbowGum queued(LogConfig config) { 223 return new SimpleRainbowGum(config, LogRouter.global(), UUID.randomUUID()); 224 } 225 226 /** 227 * Sets the global default RainbowGum. The supplied {@link RainbowGum} must not 228 * already be started. 229 * @param supplier the supplier will be memoized when {@linkplain Supplier#get() 230 * accessed} and {@link RainbowGum#start()} will be called. 231 */ 232 public static void set(Supplier<RainbowGum> supplier) { 233 RainbowGumHolder.set(supplier); 234 } 235 236 /** 237 * Subscribes to changes of the globally bound RainbowGum: a new one becoming bound 238 * (see {@link #set(Supplier)}, {@link #set(RainbowGum)}, {@link Builder#set()}) or 239 * the bound one no longer being bound (closing it, {@link Builder#unset()}, or 240 * {@link #set(Supplier)} replacing it). This is primarily for components like SLF4J's 241 * logger factory that are themselves bootstrapped once (often before "the real" 242 * RainbowGum has loaded, e.g. a framework's own pre-boot sequence) and otherwise have 243 * no way of finding out that a different RainbowGum has since replaced the one they 244 * captured. 245 * <p> 246 * Only a {@linkplain java.lang.ref.WeakReference weak reference} to 247 * <code>consumer</code> is retained, so subscribing does not by itself keep the 248 * consumer (or whatever it is attached to) reachable - the caller is responsible for 249 * keeping a strong reference to <code>consumer</code> for as long as it needs to keep 250 * receiving notifications, otherwise it may silently stop being called once garbage 251 * collected. 252 * <p> 253 * The consumer receives what {@link #getOrNull()} returns after the change: the newly 254 * bound instance, or <code>null</code> when none is bound anymore. Removing when none 255 * is bound is not a change. Registering a supplier neither starts it nor closes the 256 * gum it replaces. Subscribing does not replay the currently bound instance. 257 * Notifications are delivered in the order of the changes. A concurrent or reentrant 258 * change queues its notification until the current delivery finishes, so its caller 259 * may return before subscribers have seen it. A subscriber throwing a runtime 260 * exception is reported through the internal error log and does not prevent later 261 * deliveries. A notification is not a guarantee that the supplied gum is still 262 * current or open when the consumer runs. 263 * @apiNote A consumer receiving <code>null</code> should drop what it holds rather 264 * than call {@link #of()}, which would start another gum while the application may be 265 * shutting down. 266 * @param consumer called with the newly bound global RainbowGum or <code>null</code> 267 * when none is bound. Never called while any RainbowGum internal lock is held. 268 */ 269 public static void onGlobalChange(Consumer<@Nullable RainbowGum> consumer) { 270 RainbowGumHolder.globalChangePublisher.add(consumer); 271 } 272 273 /** 274 * Sets a Rainbow Gum and provides a supplier that will start it globally. 275 * @param gum that will be set immediatly. 276 * @return supplier that will set, get and start the supplied gum and if it is not the 277 * same will throw {@link IllegalStateException}. 278 */ 279 public static Supplier<? extends RainbowGum> set(RainbowGum gum) { 280 Supplier<RainbowGum> supplier = () -> gum; 281 RainbowGumHolder.set(supplier); 282 return () -> RainbowGumHolder.startIfStillSet(supplier); 283 } 284 285 /** 286 * The config associated with this instance. 287 * @return config. 288 */ 289 public LogConfig config(); 290 291 /** 292 * The router that will route log messages to publishers. 293 * @return router 294 */ 295 public RootRouter router(); 296 297 /** 298 * Starts the rainbow gum and returns it. It is returned for try-with usage 299 * convenience. 300 * @return the started RainbowGum. 301 */ 302 default RainbowGum start() { 303 router().start(config()); 304 var debugMode = config().debugMode(); 305 if (debugMode == LogConfig.DebugModeType.ALL || debugMode == LogConfig.DebugModeType.HELP) { 306 var report = config().reporter() 307 .report(LogReporter.Options.builder() 308 .section(LogReporter.Section.VERSION) 309 .section(LogReporter.Section.COMPONENTS) 310 .section(LogReporter.Section.READ_PROPERTIES) 311 .build()); 312 MetaLog.error(LogEventFactory.of(RainbowGum.class.getName()) 313 .eventNoArg(Level.INFO, "Rainbow Gum started:\n" + report, null)); 314 } 315 if (config() instanceof DefaultLogConfig c) { 316 var check = c.unusedKeyCheck(); 317 if (check != null) { 318 reportUnusedKeys(check); 319 check.stopRecording(); 320 } 321 } 322 if (config().alerts() instanceof DefaultLogAlerts alerts) { 323 try { 324 alerts.finishStartup(); 325 } 326 catch (RuntimeException e) { 327 close(); 328 throw e; 329 } 330 } 331 return this; 332 } 333 334 /* 335 * By default an unused key with a suggestion is almost always a typo, so it is a 336 * warning about configuration, which the default logging.alerts.fail=config (and 337 * logging.debug=help) turns into a failure. So is an unread URI query parameter, 338 * since its URI chose the component. Any other is only information: the key may be 339 * for a component type that was not chosen, such as encoder options left behind by a 340 * profile that switches encoder. logging.alerts.unusedKey raises both for strict 341 * configurations. 342 */ 343 private void reportUnusedKeys(UnusedKeyCheck check) { 344 var eventFactory = LogEventFactory.of(LogConfig.class.getName()); 345 var unusedKeyLevel = config().alerts() instanceof DefaultLogAlerts alerts ? alerts.unusedKeyLevel() 346 : LogAlerts.UnusedKeyLevel.INFO; 347 for (var u : check.unused()) { 348 var level = unusedKeyLevel.level(u.likelyMistake()); 349 var event = eventFactory.eventNoArg(level, u.message(), DefaultLogAlerts.configKeyValues(), null); 350 config().alerts().alert(event); 351 if (level == Level.INFO && config().debugMode().checksUnusedKeys()) { 352 MetaLog.error(event); 353 } 354 } 355 } 356 357 /** 358 * Unique id of rainbow gum instance. 359 * @return random id created on creation. 360 */ 361 public UUID instanceId(); 362 363 /** 364 * Will close the RainbowGum and all registered components as well as removed from the 365 * shutdown hooks. If the rainbow gum is set as global it will no longer be global and 366 * replaced with the bootstrapping in memory queue. {@inheritDoc} 367 */ 368 @Override 369 public void close(); 370 371 /** 372 * This append call is mainly for testing as it does not avoid making events that do 373 * not need to be made if no logging needs to be done. {@inheritDoc} 374 */ 375 @Override 376 default void log(LogEvent event) { 377 var r = router().route(event.loggerName(), event.level()); 378 if (r.isEnabled()) { 379 r.log(event); 380 } 381 } 382 383 /** 384 * Use to build a custom {@link RainbowGum} which will use the {@link LogConfig} 385 * provided by the service loader, so installed modules are discovered. 386 * @return builder. 387 * @see #builder(Consumer) 388 */ 389 public static Builder builder() { 390 ServiceLoader<RainbowGumServiceProvider> loader = ServiceLoader.load(RainbowGumServiceProvider.class); 391 var config = RainbowGumServiceProvider.provideConfig(loader); 392 return builder(config); 393 } 394 395 /** 396 * Use to build a custom {@link RainbowGum} with supplied config. 397 * @param config the config 398 * @return builder. 399 * @see #builder() 400 */ 401 public static Builder builder(LogConfig config) { 402 return new Builder(config); 403 } 404 405 /** 406 * Use to build a custom {@link RainbowGum} whose config starts like 407 * {@link #builder()}: the config builder already uses the service loader, so 408 * installed modules are discovered, and the consumer changes only what it needs to. 409 * Calling {@link LogConfig.Builder#serviceLoader(ServiceLoader)} in the consumer 410 * replaces the service loader. To build without the service loader use 411 * {@link #builder(LogConfig)} with a config from {@link LogConfig#builder()}. 412 * @param config consumer that has first argument as config builder. 413 * @return builder. 414 * @see #builder() 415 */ 416 public static Builder builder(Consumer<? super LogConfig.Builder> config) { 417 var b = LogConfig.builder().serviceLoader(ServiceLoader.load(RainbowGumServiceProvider.class)); 418 config.accept(b); 419 return builder(b.build()); 420 } 421 422 /** 423 * RainbowGum Builder. 424 */ 425 public class Builder { 426 427 private final LogConfig config; 428 429 private final List<Router> routes = new ArrayList<>(); 430 431 private Builder(LogConfig config) { 432 this.config = config; 433 } 434 435 /** 436 * Adds a router. 437 * @param route a router. 438 * @return builder. 439 */ 440 public Builder route(Router route) { 441 bind(); 442 this.routes.add(route); 443 return this; 444 } 445 446 /* 447 * Routers provision outputs/appenders into the config as soon as they are built, 448 * so the config must be claimed before that, not just at build(). 449 */ 450 private void bind() { 451 ((DefaultLogConfig) config).bind(this); 452 } 453 454 /** 455 * Adds a route by using a consumer of the route builder. 456 * @param name name of router. 457 * @param consumer consumer is passed router builder. The consumer does not need 458 * to call {@link Router#builder(String,LogConfig)} 459 * @return builder. 460 * @see io.jstach.rainbowgum.LogRouter.Router.Builder 461 */ 462 public Builder route(String name, Consumer<Router.Builder> consumer) { 463 bind(); 464 var builder = Router.builder(name, config); 465 consumer.accept(builder); 466 return route(builder.build()); 467 } 468 469 /** 470 * Adds a route by using a consumer of the route builder. 471 * @param consumer consumer is passed router builder. The consumer does not need 472 * to call {@link Router#builder(String,LogConfig)} 473 * @return builder. 474 * @see io.jstach.rainbowgum.LogRouter.Router.Builder 475 */ 476 public Builder route(Consumer<Router.Builder> consumer) { 477 bind(); 478 var builder = Router.builder(Router.DEFAULT_ROUTER_NAME, config); 479 consumer.accept(builder); 480 return route(builder.build()); 481 } 482 483 /** 484 * Builds an un-started {@link RainbowGum}. 485 * @return an un-started {@link RainbowGum}. 486 */ 487 public RainbowGum build() { 488 return build(UUID.randomUUID()); 489 } 490 491 /** 492 * Builds an un-started {@link RainbowGum}. 493 * @param instanceId unique id for rainbow gum instance. 494 * @return an un-started {@link RainbowGum}. 495 */ 496 private RainbowGum build(UUID instanceId) { 497 ((DefaultLogConfig) config).markBuilt(this); 498 var routes = this.routes; 499 var config = this.config; 500 if (routes.isEmpty()) { 501 var routeNamesResult = config.properties() // 502 .forKey(LogProperties.ROUTES_PROPERTY) 503 .ofList() 504 .or(List.of()); 505 List<String> routeNames = routeNamesResult.validateNow(Builder.class); 506 /* 507 * Validated as a plain list of names, before any of them is used to build 508 * a Router, so a bad name is reported against this list property itself, 509 * not deferred until some unrelated {name}-keyed property (e.g. this 510 * route's own level) happens to interpolate it first. 511 */ 512 LogProperty.Validator.validateNames(LogRouter.class, "route", routeNamesResult, routeNames); 513 if (routeNames.isEmpty()) { 514 routes = List.of(Router.builder(Router.DEFAULT_ROUTER_NAME, config).build()); 515 } 516 else { 517 routes = routeNames.stream().map(n -> Router.builder(n, config).build()).toList(); 518 } 519 } 520 var root = InternalRootRouter.of(routes, config); 521 config.changePublisher().subscribe(c -> { 522 root.changePublisher().publish(root); 523 }); 524 ((DefaultLogConfig) config).reporter().bind(root); 525 return new SimpleRainbowGum(config, root, instanceId); 526 } 527 528 /** 529 * Builds, starts and sets the RainbowGum as the global one picked up by logging 530 * facades. 531 * @return started and set rainbow that can be used in a try-close. 532 */ 533 public RainbowGum set() { 534 return RainbowGumHolder.setAndStart(() -> build(UUID.randomUUID())); 535 } 536 537 /** 538 * Removes the currently set Rainbow Gum which will close it if one exists and 539 * will be replaced by the default provision process if {@link RainbowGum#of()} is 540 * called before {@link #set()}. 541 * @apiNote This is largely an internal detail for unit testing the provision 542 * process. 543 */ 544 public void unset() { 545 RainbowGumHolder.remove(null); 546 } 547 548 /** 549 * For returning an optional for the LogProvider contract. 550 * @return optional that always has a rainbow gum. 551 * @apiNote this method is for ergonomics. 552 */ 553 public Optional<RainbowGum> optional() { 554 return Optional.of(this.build()); 555 } 556 557 /** 558 * For returning an optional for the LogProvider contract. 559 * @param condition condition to check if this rainbow gum should be used. 560 * @return optional rainbow gum. 561 * @apiNote this method is for ergonomics. 562 */ 563 public Optional<RainbowGum> optional(Function<? super LogConfig, Boolean> condition) { 564 var cond = condition.apply(config); 565 if (cond) { 566 return Optional.of(this.build()); 567 } 568 return Optional.empty(); 569 } 570 571 } 572 573} 574 575final class RainbowGumHolder { 576 577 /* 578 * Serializes provisioning and changes to the supplier/router. Snapshot reads only 579 * need the volatile field; neither a read lock nor a stamp can pin a returned gum's 580 * lifetime after the read completes. 581 */ 582 private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); 583 584 private static Supplier<RainbowGum> supplier = RainbowGumServiceProvider::provide; 585 586 private static volatile @Nullable RainbowGum rainbowGum = null; 587 588 static final GlobalChangePublisher globalChangePublisher = new GlobalChangePublisher(); 589 590 /* 591 * Lock free read for per event hot paths (see KeyValuesContributor.global()) where 592 * possibly seeing the previous gum while another one binds is harmless. 593 */ 594 static @Nullable RainbowGum peek() { 595 return rainbowGum; 596 } 597 598 static @Nullable RainbowGum current() { 599 return rainbowGum; 600 } 601 602 /* 603 * Returns the existing binding during a replacement. When provisioning the first 604 * binding reenters on this thread, returns null instead of provisioning recursively. 605 */ 606 static @Nullable RainbowGum getOrNullIfStarting() { 607 lock.readLock().lock(); 608 try { 609 var r = rainbowGum; 610 if (r != null) { 611 return r; 612 } 613 } 614 finally { 615 lock.readLock().unlock(); 616 } 617 if (lock.writeLock().isHeldByCurrentThread()) { 618 return null; 619 } 620 lock.writeLock().lock(); 621 try { 622 var r = rainbowGum; 623 if (r != null) { 624 return r; 625 } 626 r = supplier.get(); 627 start(r); 628 rainbowGum = r; 629 globalChangePublisher.enqueue(Optional.of(r)); 630 return r; 631 632 } 633 finally { 634 lock.writeLock().unlock(); 635 /* 636 * Enqueue under the write lock to preserve binding order, but invoke user 637 * callbacks only after releasing it. The publisher never holds its monitor 638 * while calling a subscriber, including one that binds another gum. 639 */ 640 drainGlobalChanges(); 641 } 642 643 } 644 645 /* 646 * Installs the supplier and starts and binds its gum in one step under the write 647 * lock, returning exactly that gum: another thread binding at the same time cannot 648 * make the caller start or return a different one. 649 */ 650 static RainbowGum setAndStart(Supplier<RainbowGum> rainbowGumSupplier) { 651 Objects.requireNonNull(rainbowGumSupplier); 652 if (lock.writeLock().isHeldByCurrentThread()) { 653 throw new IllegalStateException("RainbowGum component tried to log too early. " 654 + "This is usually caused by dependencies calling logging."); 655 } 656 lock.writeLock().lock(); 657 try { 658 // Prepare the candidate before changing the visible holder or supplier. 659 // A failed build/start leaves the previous binding intact. 660 var r = rainbowGumSupplier.get(); 661 start(r); 662 var original = rainbowGum; 663 supplier = rainbowGumSupplier; 664 rainbowGum = r; 665 if (original != null) { 666 globalChangePublisher.enqueue(Optional.empty()); 667 } 668 globalChangePublisher.enqueue(Optional.of(r)); 669 return r; 670 } 671 finally { 672 lock.writeLock().unlock(); 673 drainGlobalChanges(); 674 } 675 } 676 677 /* 678 * Starts and binds the gum of a supplier installed earlier by set, under the write 679 * lock, only if that supplier is still the installed one. 680 */ 681 @SuppressWarnings("ReferenceEquality") 682 static RainbowGum startIfStillSet(Supplier<RainbowGum> rainbowGumSupplier) { 683 if (lock.writeLock().isHeldByCurrentThread()) { 684 throw new IllegalStateException("RainbowGum component tried to log too early. " 685 + "This is usually caused by dependencies calling logging."); 686 } 687 lock.writeLock().lock(); 688 try { 689 if (supplier != rainbowGumSupplier) { 690 throw new IllegalStateException("Another Rainbow Gum was set as the global one after this one."); 691 } 692 var r = rainbowGum; 693 if (r != null) { 694 return r; 695 } 696 r = rainbowGumSupplier.get(); 697 start(r); 698 supplier = rainbowGumSupplier; 699 rainbowGum = r; 700 globalChangePublisher.enqueue(Optional.of(r)); 701 return r; 702 } 703 finally { 704 lock.writeLock().unlock(); 705 drainGlobalChanges(); 706 } 707 } 708 709 static boolean remove(@Nullable RainbowGum gum) { 710 lock.writeLock().lock(); 711 try { 712 var original = rainbowGum; 713 if (gum != null && original != gum) { 714 return false; 715 } 716 rainbowGum = null; 717 supplier = RainbowGumServiceProvider::provide; 718 if (original != null) { 719 /* 720 * Unbound and queued before the global router is reset, so a failing 721 * output close still publishes the removal. 722 */ 723 globalChangePublisher.enqueue(Optional.empty()); 724 LogRouter.global().close(); 725 } 726 return true; 727 } 728 finally { 729 lock.writeLock().unlock(); 730 drainGlobalChanges(); 731 } 732 } 733 734 static void set(Supplier<RainbowGum> rainbowGumSupplier) { 735 Objects.requireNonNull(rainbowGumSupplier); 736 if (lock.writeLock().isHeldByCurrentThread()) { 737 throw new IllegalStateException("RainbowGum component tried to log too early. " 738 + "This is usually caused by dependencies calling logging."); 739 } 740 lock.writeLock().lock(); 741 try { 742 var original = rainbowGum; 743 rainbowGum = null; 744 supplier = rainbowGumSupplier; 745 if (original != null) { 746 globalChangePublisher.enqueue(Optional.empty()); 747 } 748 } 749 finally { 750 lock.writeLock().unlock(); 751 drainGlobalChanges(); 752 } 753 } 754 755 /* 756 * Component code can reenter remove() during startup or shutdown, so only the 757 * outermost lifecycle operation calls subscribers. 758 */ 759 private static void drainGlobalChanges() { 760 if (!lock.writeLock().isHeldByCurrentThread()) { 761 globalChangePublisher.drain(); 762 } 763 } 764 765 static boolean shutdownHook(LogConfig config) { 766 return config.globals().shutdownHook() == LogConfig.Globals.ShutdownHookMode.ON; 767 } 768 769 @SuppressWarnings("ReferenceEquality") // Throwable self-suppression. 770 private static void start(RainbowGum gum) { 771 Objects.requireNonNull(gum); 772 var previousRouter = GlobalLogRouter.INSTANCE.currentRouter(); 773 boolean binding = false; 774 long dropped; 775 try { 776 gum.start(); 777 if (shutdownHook(gum.config())) { 778 ShutdownManager.addShutdownHook(gum); 779 } 780 binding = true; 781 dropped = InternalRootRouter.setRouter(gum.router()); 782 } 783 catch (RuntimeException | Error failure) { 784 if (binding) { 785 try { 786 GlobalLogRouter.INSTANCE.restoreAfterFailedBind(previousRouter, (InternalRootRouter) gum.router()); 787 } 788 catch (RuntimeException | Error restoreFailure) { 789 if (failure != restoreFailure) { 790 failure.addSuppressed(restoreFailure); 791 } 792 } 793 } 794 try (gum) { 795 } 796 catch (RuntimeException | Error closeFailure) { 797 if (failure != closeFailure) { 798 failure.addSuppressed(closeFailure); 799 } 800 } 801 finally { 802 ShutdownManager.removeShutdownHook(gum); 803 } 804 throw failure; 805 } 806 if (dropped > 0) { 807 gum.config() 808 .alerts() 809 .warn(RainbowGum.class, 810 "Dropped " + dropped 811 + " events logged while no Rainbow Gum was bound because the queue was full. See " 812 + LogProperties.GLOBAL_QUEUE_SIZE_PROPERTY + "."); 813 } 814 } 815 816} 817 818/* 819 * Unlike LogConfig.ChangePublisher/LogRouter.RouteChangePublisher (both scoped to a 820 * single RainbowGum/router instance and torn down with it) this is a JVM-lifetime static 821 * registry, so consumers are held only weakly - otherwise every SLF4J logger factory (or 822 * any other subscriber) ever created over the life of the JVM, e.g. across many 823 * short-lived RainbowGums in tests, would be pinned forever. 824 */ 825final class GlobalChangePublisher { 826 827 private final Queue<WeakReference<Consumer<@Nullable RainbowGum>>> consumers = new ConcurrentLinkedQueue<>(); 828 829 /* 830 * Both guarded by this. No callbacks may run while this monitor is held. Empty is a 831 * removal, as ArrayDeque does not allow null. 832 */ 833 private final Queue<Optional<RainbowGum>> pending = new ArrayDeque<>(); 834 835 private boolean draining; 836 837 void add(Consumer<@Nullable RainbowGum> consumer) { 838 Objects.requireNonNull(consumer); 839 consumers.add(new WeakReference<>(consumer)); 840 } 841 842 synchronized void enqueue(Optional<RainbowGum> state) { 843 pending.add(state); 844 } 845 846 void drain() { 847 synchronized (this) { 848 if (draining) { 849 return; 850 } 851 draining = true; 852 } 853 try { 854 while (true) { 855 Optional<RainbowGum> state; 856 synchronized (this) { 857 state = pending.poll(); 858 if (state == null) { 859 draining = false; 860 return; 861 } 862 } 863 publish(state.orElse(null)); 864 } 865 } 866 catch (RuntimeException | Error e) { 867 synchronized (this) { 868 draining = false; 869 } 870 throw e; 871 } 872 } 873 874 private void publish(@Nullable RainbowGum gum) { 875 for (var it = consumers.iterator(); it.hasNext();) { 876 var consumer = it.next().get(); 877 if (consumer == null) { 878 it.remove(); 879 } 880 else { 881 try { 882 consumer.accept(gum); 883 } 884 catch (RuntimeException e) { 885 MetaLog.error(RainbowGum.class, "Global change subscriber threw", e); 886 } 887 } 888 } 889 } 890 891} 892 893final class SimpleRainbowGum implements RainbowGum, Shutdownable { 894 895 private final LogConfig config; 896 897 private final RootRouter router; 898 899 private final AtomicInteger state = new AtomicInteger(0); 900 901 private final UUID instanceId; 902 903 private static final int INIT = 0; 904 905 private static final int STARTED = 1; 906 907 private static final int CLOSED = 2; 908 909 public SimpleRainbowGum(LogConfig config, RootRouter router, UUID instanceId) { 910 super(); 911 this.config = config; 912 this.router = router; 913 this.instanceId = instanceId; 914 } 915 916 @Override 917 public LogConfig config() { 918 return this.config; 919 } 920 921 @Override 922 public RootRouter router() { 923 return this.router; 924 } 925 926 @Override 927 public RainbowGum start() { 928 int current; 929 if ((current = state.compareAndExchange(INIT, STARTED)) == INIT) { 930 return RainbowGum.super.start(); 931 } 932 throw new IllegalStateException("Cannot start. This rainbowgum is " + stateLabel(current)); 933 } 934 935 @Override 936 public UUID instanceId() { 937 return this.instanceId; 938 } 939 940 @Override 941 public void close() { 942 if (state.compareAndSet(STARTED, CLOSED)) { 943 try { 944 RainbowGumHolder.remove(this); 945 } 946 finally { 947 try { 948 shutdown(); 949 } 950 finally { 951 ShutdownManager.removeShutdownHook(this); 952 } 953 } 954 return; 955 } 956 } 957 958 @Override 959 public void shutdown() { 960 /* 961 * queued(config) borrows the global router. Only remove() resets it, as closing 962 * it here could reset a replacement that is already bound. 963 */ 964 if (!(router instanceof GlobalLogRouter)) { 965 router.close(); 966 } 967 config().alerts().close(); 968 config().serviceRegistry().close(); 969 } 970 971 @Override 972 public String toString() { 973 return "SimpleRainbowGum [instanceId=" + instanceId + ", config=" + config + ", router=" + router + ", state=" 974 + stateLabel(state.get()) + "]"; 975 } 976 977 private static String stateLabel(int state) { 978 return switch (state) { 979 case INIT -> "created"; 980 case STARTED -> "started"; 981 case CLOSED -> "closed"; 982 default -> { 983 throw new IllegalArgumentException("" + state); 984 } 985 }; 986 } 987 988}