001package io.jstach.rainbowgum.systemlogger;
002
003import java.lang.System.Logger;
004import java.util.Locale;
005import java.util.function.Supplier;
006
007import org.jspecify.annotations.Nullable;
008
009import io.jstach.rainbowgum.LogProperties;
010import io.jstach.rainbowgum.LogProperty;
011import io.jstach.rainbowgum.LogRouter;
012import io.jstach.rainbowgum.LoggerAPI;
013import io.jstach.rainbowgum.RainbowGum;
014import io.jstach.rainbowgum.spi.RainbowGumServiceProvider;
015
016/**
017 * Abstract System Logger Finder to allow users to create their own custom
018 * System.LoggerFinder. <strong>This implementation does not cache System Loggers</strong>
019 * by name!
020 * <p>
021 * <b>GraalVM native image</b>: this module bundles a {@code native-image.properties} (at
022 * {@code META-INF/native-image/io.jstach.rainbowgum/rainbowgum-systemlogger/}) with
023 * {@code --initialize-at-build-time} for {@code RouterProvider} plus the core classes
024 * ({@code GlobalLogRouter}, {@code StaticLevelResolver}) its {@code LogRouter.global()}
025 * fallback touches on first real use. See {@link #routerProvider} for why this is still
026 * needed even though this class resolves its router lazily rather than eagerly in its
027 * constructor, and why what gets frozen in is just the cheap "nothing bound yet" state,
028 * not anything environment-specific. native-image's own embedded configuration discovery
029 * picks this up from this module's jar automatically, no extra plugin or flag needed on
030 * the consuming side.
031 *
032 * @see #INITIALIZE_RAINBOW_GUM_PROPERTY
033 */
034public abstract class RainbowGumSystemLoggerFinder extends System.LoggerFinder {
035
036        /**
037         * Initialization flag.
038         * <p>
039         * Property: <code>{@index logging.systemlogger.initialize}</code>
040         * @see InitOption
041         */
042        public static final String INITIALIZE_RAINBOW_GUM_PROPERTY = LogProperties.ROOT_PREFIX + "systemlogger.initialize";
043
044        private final Supplier<? extends InitOption> optSupplier;
045
046        /*
047         * Resolved lazily, on the first getLogger(...) call at run time, never in the
048         * constructor and never while a native image is being built.
049         *
050         * The JDK calls System.getLogger(...) for its own diagnostics from unrelated code,
051         * including during a GraalVM native-image build. Observed triggers:
052         * java.time/java.util.Locale formatting, and TrustStoreManagerFeature loading the
053         * default trust store, whose JCA security event logging asks
054         * System.getLogger("jdk.event.security").isLoggable(...). Whatever this finder
055         * resolves then is frozen into the image heap. Resolving the init option at build
056         * time would start a real Rainbow Gum whenever no RainbowGumEagerLoad (SLF4J) is on
057         * the class path, and that gum, plus the JUL handler its configurators install, would
058         * land in the image heap and fail the build. So during an image build this returns
059         * the queuing global router and resolves nothing; see isImageBuildTime().
060         */
061        private volatile @Nullable RouterProvider routerProvider;
062
063        /*
064         * Created lazily like routerProvider and for the same reason. Held here because
065         * RainbowGum.onGlobalChange only keeps a weak reference.
066         */
067        private volatile @Nullable GlobalRainbowGum global;
068
069        /**
070         * Values (case is ignored) for {@value #INITIALIZE_RAINBOW_GUM_PROPERTY}.
071         */
072        public enum InitOption {
073
074                /**
075                 * Will not initialize rainbow gum.
076                 */
077                FALSE,
078                /**
079                 * Will initialize rainbow gum.
080                 */
081                TRUE,
082                /**
083                 * (default) Will check if there are implementations of
084                 * {@link RainbowGumServiceProvider.RainbowGumEagerLoad} and if there are not will
085                 * load rainbow gum.
086                 */
087                CHECK,
088                /**
089                 * Will reuse an existing rainbow gum or fail.
090                 */
091                REUSE;
092
093                /**
094                 * Parses an init option from a property value.
095                 * @param input from properties.
096                 * @return init option.
097                 */
098                public static InitOption parse(String input) {
099                        if (input.isBlank())
100                                return FALSE;
101                        return LogProperty.enumValue(InitOption.class, input, "blank");
102                }
103
104        }
105
106        /**
107         * Creates the logger inder based on init option.
108         * @param optSupplier can be resolved with {@link #initOption(LogProperties)}.
109         */
110        protected RainbowGumSystemLoggerFinder(Supplier<? extends InitOption> optSupplier) {
111                this.optSupplier = optSupplier;
112        }
113
114        private RouterProvider routerProvider() {
115                var rp = this.routerProvider;
116                if (rp != null) {
117                        return rp;
118                }
119                if (isImageBuildTime()) {
120                        /*
121                         * Not cached: the image starts with this finder unresolved, so the first real
122                         * getLogger(...) at run time still applies the init option.
123                         */
124                        return n -> LogRouter.global();
125                }
126                try {
127                        var opt = optSupplier.get();
128                        rp = switch (opt) {
129                                case FALSE -> n -> LogRouter.global();
130                                case TRUE -> new InitRouterProvider(RainbowGum::ofOrNull);
131                                case CHECK -> {
132                                        if (RainbowGumServiceProvider.RainbowGumEagerLoad.exists()) {
133                                                yield n -> LogRouter.global();
134                                        }
135                                        yield new InitRouterProvider(RainbowGum::ofOrNull);
136                                }
137                                case REUSE -> new InitRouterProvider(() -> {
138                                        var gum = RainbowGum.getOrNull();
139                                        if (gum == null) {
140                                                throw new IllegalStateException(
141                                                                "SystemLogging was configured to reuse a loaded Rainbow Gum but none was found. "
142                                                                                + INITIALIZE_RAINBOW_GUM_PROPERTY + "=" + opt);
143                                        }
144                                        return gum;
145                                });
146                        };
147                        this.routerProvider = rp;
148                        return rp;
149                }
150                catch (Exception e) {
151                        // We have to do this because it because very difficult
152                        // to determine why the System Logging fails as it does not even print the
153                        // exception.
154                        var gum = RainbowGum.getOrNull();
155                        if (gum != null) {
156                                gum.config().alerts().error(getClass(), "Failed to create System.LoggerFinder", e);
157                        }
158                        else {
159                                System.err.println("[ERROR] - RAINBOW_GUM Failed to create System.LoggerFinder");
160                                e.printStackTrace();
161                        }
162                        throw e;
163                }
164        }
165
166        @Override
167        public Logger getLogger(String name, Module module) {
168                var router = routerProvider().router(name);
169                var global = global();
170                if (!router.isChangeable(name)) {
171                        var level = router.levelResolver().resolveLevel(name);
172                        return LevelSystemLogger.of(name, level, router.route(name, level), global);
173                }
174                return new RainbowGumSystemLogger(name, router, global);
175        }
176
177        private GlobalRainbowGum global() {
178                var g = this.global;
179                if (g != null) {
180                        return g;
181                }
182                synchronized (this) {
183                        g = this.global;
184                        if (g == null) {
185                                g = this.global = GlobalRainbowGum.of();
186                        }
187                        return g;
188                }
189        }
190
191        /**
192         * Whether a GraalVM native image is being built right now, from the system property
193         * GraalVM sets for that, so this module does not need GraalVM's SDK.
194         */
195        static boolean isImageBuildTime() {
196                return "buildtime".equals(System.getProperty("org.graalvm.nativeimage.imagecode"));
197        }
198
199        /**
200         * Gets the init option from properties.
201         * @param properties usually system properties.
202         * @return initialization option.
203         */
204        protected static InitOption initOption(LogProperties properties) {
205                return properties.forKey(INITIALIZE_RAINBOW_GUM_PROPERTY)
206                        .ofString()
207                        .map(InitOption::parse)
208                        .or(InitOption.CHECK)
209                        .validateNow(RainbowGumSystemLoggerFinder.class);
210        }
211
212        private interface RouterProvider {
213
214                LogRouter.RootRouter router(String loggerName);
215
216        }
217
218        private class InitRouterProvider implements RouterProvider {
219
220                private final Supplier<? extends @Nullable RainbowGum> supplier;
221
222                private volatile boolean initialized;
223
224                InitRouterProvider(Supplier<? extends @Nullable RainbowGum> supplier) {
225                        super();
226                        this.supplier = supplier;
227                }
228
229                @Override
230                public LogRouter.RootRouter router(String loggerName) {
231                        LogRouter.RootRouter router;
232                        /*
233                         * The first lookup finds or starts a gum as the init option says. Later ones
234                         * follow the holder, so a removed gum is neither kept nor started again.
235                         */
236                        var current = RainbowGumSystemLoggerFinder.this.global;
237                        RainbowGum gum = current == null ? null : current.gum();
238                        if (gum == null) {
239                                if (initialized) {
240                                        return LogRouter.global();
241                                }
242                                gum = supplier.get();
243                                if (gum == null) {
244                                        /*
245                                         * This thread is starting a gum, for example a dependency logging
246                                         * while properties are provided. The global router holds the events
247                                         * until it is bound.
248                                         */
249                                        return LogRouter.global();
250                                }
251                        }
252                        initialized = true;
253                        gum.config().loggerRegistry().registerLoggerName(LoggerAPI.Standard.SYSTEM_LOGGER, loggerName);
254                        if (gum.config().changePublisher().isEnabled(loggerName)) {
255                                router = LogRouter.global();
256                        }
257                        else {
258                                router = gum.router();
259                        }
260                        return router;
261                }
262
263        }
264
265}