Class LoggingScope


  • public abstract class LoggingScope
    extends Object
    An opaque scope marker which can be attached to log sites to provide "per scope" behaviour for stateful logging operations (e.g. rate limiting).

    Scopes are provided via the Provider interface and found by looking for the current ScopedLoggingContexts.

    Stateful fluent logging APIs which need to look up per log site information (e.g. rate limit state) should do so via a LogSiteMap using the LogSiteKey passed into the LogContext.postProcess(LogSiteKey) method. If scopes are present in the log site Metadata then the log site key provided to the postProcess() method will already be specialized to take account of any scopes present.

    Note that scopes have no effect when applied to stateless log statements (e.g. log statements without rate limiting) since the log site key for that log statement will not be used in any maps.

    • Constructor Detail

      • LoggingScope

        protected LoggingScope​(String label)
        Creates a basic scope with the specified label. Custom subclasses of LoggingScope must manage their own lifecycles to avoid leaking memory and polluting LogSiteMaps with unused keys.
    • Method Detail

      • create

        public static LoggingScope create​(String label)
        Creates a scope which automatically removes any associated keys from LogSiteMaps when it's garbage collected. The given label is used only for debugging purposes and may appear in log statements, it should not contain any user data or other runtime information.
      • specialize

        protected abstract LogSiteKey specialize​(LogSiteKey key)
        Returns a specialization of the given key which accounts for this scope instance. Two specialized keys should compare as Object.equals(Object) if and only if they are specializations from the same log site, with the same sequence of scopes applied.

        The returned instance:

        • Must be an immutable "value type".
        • Must not compare as Object.equals(Object) to the given key.
        • Should have a different Object.hashCode() to the given key.
        • Should be efficient and lightweight.
        As such it is recommended that the SpecializedLogSiteKey.of(LogSiteKey, Object) method is used in implementations, passing in a suitable qualifier (which need not be the scope itself, but must be unique per scope).
      • onClose

        protected abstract void onClose​(Runnable removalHook)
        Registers "hooks" which should be called when this scope is "closed". The hooks are intended to remove the keys associated with this scope from any data structures they may be held in, to avoid leaking allocations.

        Note that a key may be specialized with several scopes and the first scope to be closed will remove it from any associated data structures (conceptually the scope that a log site is called from is the intersection of all the currently active scopes which apply to it).