### Activator and ProviderActivator Start Methods Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-api/index-all.html Methods for starting OSGi bundles. ```APIDOC ## Activator and ProviderActivator Start Methods ### Description Methods to start OSGi bundles. ### Methods - `start(BundleContext context)`: Method in class `org.apache.logging.log4j.util.Activator`. - `start(BundleContext context)`: Method in class `org.apache.logging.log4j.util.ProviderActivator`. ``` -------------------------------- ### Timer Start Methods Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-api/index-all.html Methods for starting and resuming a timer. ```APIDOC ## Timer Start Methods ### Description Methods to control the timer. ### Methods - `start()`: Start the timer. - `startOrResume()`: Start or resume the timer. ``` -------------------------------- ### Configure counter resolver examples Source: https://logging.apache.org/log4j/2.x/manual/json-template-layout.html Various configurations for the counter resolver, including default behavior, custom start values, and non-overflowing modes. ```json { "$resolver": "counter" } ``` ```json { "$resolver": "counter", "start": 1000 } ``` ```json { "$resolver": "counter", "overflowing": false } ``` -------------------------------- ### Example: Rendering Short Stack Trace Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example renders the first two lines of the exception stack trace using the 'short' option. ```java %ex{short} ``` -------------------------------- ### MarkerPatternSelector Example (Properties) Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html Example configuration of MarkerPatternSelector using Properties format. ```APIDOC ## MarkerPatternSelector Example (Properties) ### Description This snippet shows how to configure a `MarkerPatternSelector` in Properties format to change the log pattern when a specific marker (e.g., 'FLOW') is present. ### Endpoint N/A (Configuration Snippet) ### Request Body ```properties appender.0.layout.type = PatternLayout appender.0.layout.patternSelector.type = MarkerPatternSelector appender.0.layout.patternSelector.defaultPattern = %-5p [%t]: %m%n appender.0.layout.patternSelector.patternMatch.0.type = PatternMatch appender.0.layout.patternSelector.patternMatch.0.key = FLOW appender.0.layout.patternSelector.patternMatch.0.pattern = [%-5level] %c{1.} ====== %C{1.}.%M:%L %msg ======%n ``` ### Response N/A (Configuration Snippet) ``` -------------------------------- ### Example: Extended Exception with Packaging Info Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example uses the extended exception converter (%xEx) to include class packaging information in the rendered stack traces. ```java %xEx ``` -------------------------------- ### Example: Rendering Full Stack Trace Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example renders the complete exception stack trace, similar to Throwable#printStackTrace(). ```java %ex{full} ``` -------------------------------- ### MarkerPatternSelector Example (YAML) Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html Example configuration of MarkerPatternSelector using YAML format. ```APIDOC ## MarkerPatternSelector Example (YAML) ### Description This snippet shows how to configure a `MarkerPatternSelector` in YAML format to change the log pattern when a specific marker (e.g., 'FLOW') is present. ### Endpoint N/A (Configuration Snippet) ### Request Body ```yaml PatternLayout: MarkerPatternSelector: defaultPattern: "% -5p [%t]: %m%n" PatternMatch: - key: "FLOW" pattern: "[%-5level] %c{1.} ====== %C{1.}.%M:%L %msg ======%n" ``` ### Response N/A (Configuration Snippet) ``` -------------------------------- ### Example: Logging Exception File Name Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example shows how to log the file name of the first stack trace element using the 'short.fileName' property. ```java %ex{short.fileName} ``` -------------------------------- ### Route Creation Example Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/appender/routing/Route.html Demonstrates how to create a Route using the `createRoute` static method. ```APIDOC ## POST /route (Conceptual) ### Description This section illustrates the conceptual usage of creating a Route object, as the `createRoute` method is a static factory method within the Java class and not a direct API endpoint. ### Method N/A (Static Java Method) ### Endpoint N/A ### Parameters (for `createRoute` method) #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```java // Assuming Node class and Appender are defined elsewhere Node dynamicNode = ...; // Initialize a Node object String appenderReference = "MyConsoleAppender"; String routeKey = "production"; Route route = Route.createRoute(appenderReference, routeKey, dynamicNode); ``` ### Response #### Success Response (Conceptual) - **Route** (Route) - The newly created Route object. #### Response Example ```json // This is a conceptual representation, as the method returns a Java object. { "appenderRef": "MyConsoleAppender", "key": "production", "node": { ... } // Representation of the Node object } ``` ``` -------------------------------- ### ObjectArrayIterator Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/index-all.html Gets the start index for iteration. ```APIDOC ## getStartIndex ### Description Gets the start index to loop from. ### Method Method ### Class org.apache.logging.log4j.core.util.ObjectArrayIterator ### Returns - **int** (int) - The start index. ``` -------------------------------- ### Instant.getNanoOfSecond() Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/index-all.html Gets the number of nanoseconds, later along the time-line, from the start of the second. ```APIDOC ## Instant.getNanoOfSecond() ### Description Gets the number of nanoseconds, later along the time-line, from the start of the second. ### Method `getNanoOfSecond()` ### Interface `org.apache.logging.log4j.core.time.Instant` ``` -------------------------------- ### Instant.getNanoOfMillisecond() Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/index-all.html Gets the number of nanoseconds, later along the time-line, from the start of the millisecond. ```APIDOC ## Instant.getNanoOfMillisecond() ### Description Gets the number of nanoseconds, later along the time-line, from the start of the millisecond. ### Method `getNanoOfMillisecond()` ### Interface `org.apache.logging.log4j.core.time.Instant` ``` -------------------------------- ### Configure custom styles Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/pattern/JAnsiTextRenderer.html Example configuration for custom warning, key, and value styles. ```text %message{ansi}{WarningStyle=red,bold KeyStyle=white ValueStyle=blue}%n ``` -------------------------------- ### BuiltConfiguration Setup and Properties Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/config/builder/impl/BuiltConfiguration.html Details methods for setting up the configuration, retrieving content type, and managing plugin packages. ```APIDOC ## BuiltConfiguration Setup and Properties ### Description Methods related to the setup, content type, and plugin management of the BuiltConfiguration. ### Method Details - ### `setup()` `public void setup()` Overrides: `setup` in class `AbstractConfiguration` Description: Initializes the configuration. - ### `getContentType()` `public String getContentType()` Description: Retrieves the content type of the configuration. - ### `setContentType(String contentType)` `public void setContentType(String contentType)` Description: Sets the content type for the configuration. - ### `createAdvertiser(String advertiserString, ConfigurationSource configSource)` `public void createAdvertiser(String advertiserString, ConfigurationSource configSource)` Description: Creates an advertiser for the configuration. - ### `getStatusConfiguration()` `public StatusConfiguration getStatusConfiguration()` Description: Retrieves the status configuration. - ### `setPluginPackages(String packages)` `public void setPluginPackages(String packages)` Description: Sets the plugin packages to be scanned. - ### `setShutdownHook(String flag)` `public void setShutdownHook(String flag)` Description: Configures the shutdown hook. - ### `setShutdownTimeoutMillis(long shutdownTimeoutMillis)` `public void setShutdownTimeoutMillis(long shutdownTimeoutMillis)` Description: Sets the shutdown timeout in milliseconds. - ### `setMonitorInterval(int intervalSeconds)` `public void setMonitorInterval(int intervalSeconds)` Description: Sets the monitor interval in seconds. ``` -------------------------------- ### getVariablePrefixMatcher Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/lookup/StrSubstitutor.html Gets the variable prefix matcher currently in use. The variable prefix is the character or characters that identify the start of a variable. This prefix is expressed in terms of a matcher allowing advanced prefix matches. ```APIDOC ## getVariablePrefixMatcher ### Description Gets the variable prefix matcher currently in use. The variable prefix is the character or characters that identify the start of a variable. This prefix is expressed in terms of a matcher allowing advanced prefix matches. ### Method public StrMatcher getVariablePrefixMatcher() ### Returns - `StrMatcher` - the prefix matcher in use ``` -------------------------------- ### Configure filePattern with date patterns Source: https://logging.apache.org/log4j/2.x/manual/appenders/rolling-file.html Examples of filePattern configurations using date-based patterns for directory and file naming. ```text $${date:yyyy-MM}/%d{yyyy-MM-dd}.log ``` ```text %d{yyyy-MM}/%d{yyyy-MM-dd}.log ``` -------------------------------- ### POST LoggerContext.start Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/config/class-use/Configuration.html Starts the LoggerContext using a specific configuration. ```APIDOC ## POST LoggerContext.start ### Description Starts the context using a specific configuration. ### Method POST ### Endpoint LoggerContext.start(Configuration config) ### Parameters #### Request Body - **config** (Configuration) - Required - The configuration to start the context with. ``` -------------------------------- ### Install Log4jBridgeHandler programmatically Source: https://logging.apache.org/log4j/2.x/log4j-jul.html Alternatively, install the Log4jBridgeHandler by calling its install() method in your code. This requires Log4j Core as the logging implementation. ```java org.apache.logging.log4j.jul.Log4jBridgeHandler.install() ``` -------------------------------- ### KeyStoreConfiguration Constructors Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/net/ssl/KeyStoreConfiguration.html Details on how to instantiate a KeyStoreConfiguration object. ```APIDOC ## KeyStoreConfiguration Constructors ### KeyStoreConfiguration(String location, PasswordProvider passwordProvider, String keyStoreType, String keyManagerFactoryAlgorithm) **Description**: Creates a new KeyStoreConfiguration with the specified parameters. **Parameters**: - **location** (String) - Required - The location of the KeyStore (file path, URL, or resource). - **passwordProvider** (PasswordProvider) - Required - Provides the password for the KeyStore. - **keyStoreType** (String) - Optional - The type of the KeyStore. Defaults to "JKS" if null. - **keyManagerFactoryAlgorithm** (String) - Optional - The standard name of the requested algorithm for the KeyManagerFactory. **Throws**: - `StoreConfigurationException` - If this instance cannot load the KeyStore. ### KeyStoreConfiguration(String location, char[] password, String keyStoreType, String keyManagerFactoryAlgorithm) **Description**: Deprecated constructor for creating a KeyStoreConfiguration. Use `KeyStoreConfiguration(String, PasswordProvider, String, String)` instead. **Parameters**: - **location** (String) - Required - The location of the KeyStore. - **password** (char[]) - Required - The password to access the KeyStore. - **keyStoreType** (String) - Optional - The type of the KeyStore. Defaults to "JKS" if null. - **keyManagerFactoryAlgorithm** (String) - Optional - The standard name of the requested algorithm. **Throws**: - `StoreConfigurationException` - If this instance cannot load the KeyStore. ### KeyStoreConfiguration(String location, String password, String keyStoreType, String keyManagerFactoryAlgorithm) **Description**: Deprecated constructor for creating a KeyStoreConfiguration. Use `KeyStoreConfiguration(String, PasswordProvider, String, String)` instead. **Parameters**: - **location** (String) - Required - The location of the KeyStore. - **password** (String) - Required - The password to access the KeyStore. - **keyStoreType** (String) - Optional - The type of the KeyStore. Defaults to "JKS" if null. - **keyManagerFactoryAlgorithm** (String) - Optional - The standard name of the requested algorithm. **Throws**: - `StoreConfigurationException` - If this instance cannot load the KeyStore. ``` -------------------------------- ### AbstractKeyStoreConfiguration Constructor Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/net/ssl/AbstractKeyStoreConfiguration.html Initializes a new instance of the AbstractKeyStoreConfiguration class. ```APIDOC ## Constructor: AbstractKeyStoreConfiguration ### Description Creates a configuration for a KeyStore using a location, a password provider, and the store type. ### Parameters - **location** (String) - Required - The path to the KeyStore. - **passwordProvider** (PasswordProvider) - Required - The provider for the KeyStore password. - **keyStoreType** (String) - Required - The type of the KeyStore (e.g., JKS, PKCS12). ### Throws - **StoreConfigurationException** - Thrown if the configuration cannot be initialized. ``` -------------------------------- ### Get NoMarkerFilter Builder Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/filter/class-use/NoMarkerFilter.Builder.html Demonstrates how to get an instance of the NoMarkerFilter.Builder. ```APIDOC ## Get NoMarkerFilter Builder ### Description This section shows how to obtain a builder instance for creating `NoMarkerFilter` objects. ### Method `static NoMarkerFilter.Builder` ### Endpoint N/A (This is a static method call within the Log4j 2 library) ### Parameters None ### Request Example ```java NoMarkerFilter.Builder builder = NoMarkerFilter.newBuilder(); ``` ### Response #### Success Response (Builder Instance) - **NoMarkerFilter.Builder** - An instance of the builder class. ``` -------------------------------- ### Java Environment Lookup Examples Source: https://logging.apache.org/log4j/2.x/manual/lookups.html Retrieve information about the Java environment. Supported keys include version, runtime, vm, os, locale, and hw. ```text Java version 21.0.3 ``` ```text OpenJDK Runtime Environment (build 21.0.3+9-LTS) from Eclipse Adoptium ``` ```text OpenJDK 64-Bit Server VM (build 21.0.3+9-LTS, mixed mode, sharing) ``` ```text Linux 6.1.0-18-amd64, architecture: amd64-64 ``` ```text default locale: en_US, platform encoding: UTF-8 ``` ```text processors: 32, architecture: amd64-64, instruction sets: amd64 ``` -------------------------------- ### Example: Accessing Main Arguments Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/lookup/MainMapLookup.html Demonstrates how command-line arguments can be accessed using the 'main' prefix. Note the use of a backslash to escape the colon when looking up arguments with leading dashes. ```text "main:0" = "--file" "main:1" = "path/file.txt" "main:2" = "-x" "main:3" = "2" "main:\--file" = "path/file.txt" "main:\-x" = "2" ``` -------------------------------- ### get() Method Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-api/org/apache/logging/log4j/util/Supplier.html Documentation for the 'get()' method of the Supplier interface, which retrieves a value. ```APIDOC ## get() ### Description Gets a value. ### Method `T get()` ### Returns a value ### Specified by `get` in interface `Supplier` ``` -------------------------------- ### Configuration Lifecycle Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/config/AbstractConfiguration.html Methods to initialize, start, and stop the configuration. ```APIDOC ## void initialize() ### Description Initialize the configuration. ## void start() ### Description Start the configuration. ## boolean stop(long timeout, TimeUnit timeUnit) ### Description Tear down the configuration. ### Parameters #### Request Body - **timeout** (long) - Required - The timeout duration. - **timeUnit** (TimeUnit) - Required - The unit of time for the timeout. ``` -------------------------------- ### AbstractKeyStoreConfiguration Methods Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/net/ssl/AbstractKeyStoreConfiguration.html Methods available for interacting with the KeyStore configuration. ```APIDOC ## Methods ### getKeyStore Returns the loaded KeyStore object. ### getKeyStoreType Returns the string representation of the KeyStore type. ### load Loads the KeyStore from the configured location. ### equals Compares this configuration with another object for equality. ### hashCode Returns the hash code value for this configuration. ``` -------------------------------- ### MarkerPatternSelector Example (JSON) Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html Example configuration of MarkerPatternSelector using JSON format. ```APIDOC ## MarkerPatternSelector Example (JSON) ### Description This snippet shows how to configure a `MarkerPatternSelector` in JSON format to change the log pattern when a specific marker (e.g., 'FLOW') is present. ### Endpoint N/A (Configuration Snippet) ### Request Body ```json { "PatternLayout": { "MarkerPatternSelector": { "defaultPattern": "[%-5level] %c{1.} %msg%n", "PatternMatch": [ { "key": "FLOW", "pattern": "[%-5level] %c{1.} ====== %C{1.}.%M:%L %msg ======%n" } ] } } } ``` ### Response N/A (Configuration Snippet) ``` -------------------------------- ### Property Substitution Example Source: https://logging.apache.org/log4j/2.x/manual/configuration.html Demonstrates how properties are defined for substitution. ```xml ``` ```json { "Properties": { "Property": [ { "name": "FOO", "value": "foo" }, { "name": "BAR", "value": "bar" } ] } } ``` ```yaml Properties: Property: - name: "FOO" value: "foo" - name: "BAR" value: "bar" ``` ```properties property.FOO = foo property.BAR = bar ``` -------------------------------- ### MarkerPatternSelector Example (XML) Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html Example configuration of MarkerPatternSelector using XML format. ```APIDOC ## MarkerPatternSelector Example (XML) ### Description This snippet shows how to configure a `MarkerPatternSelector` in XML format to change the log pattern when a specific marker (e.g., 'FLOW') is present. ### Endpoint N/A (Configuration Snippet) ### Request Body ```xml ``` ### Response N/A (Configuration Snippet) ``` -------------------------------- ### Routes Creation and Configuration Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/appender/routing/Routes.html Details on how to create and configure Routes, including deprecated and recommended methods. ```APIDOC ## Routes Methods ### `createRoutes` (Deprecated) #### Description Deprecated. since 2.7; use `newBuilder()`. Creates the Routes container. #### Method `static Routes createRoutes(String pattern, Route... routes)` #### Parameters - `pattern` (String) - Required - The pattern for routing. - `routes` (Route...) - Required - An array of Route elements. #### Returns - `Routes` - The Routes container. ### `newBuilder` #### Description Factory method to create a new builder for `Routes`. #### Method `static Routes.Builder newBuilder()` #### Returns - `Routes.Builder` - A new builder instance. ``` -------------------------------- ### Log4jBridgeHandler Configuration Source: https://logging.apache.org/log4j/2.x/log4j-jul.html Details on how to install and configure the Log4jBridgeHandler using logging.properties or programmatic installation. ```APIDOC ## Log4jBridgeHandler Configuration ### Description The Log4jBridgeHandler redirects JUL log events to Log4j Core. It can be installed via the `logging.properties` file or programmatically. ### Configuration Properties - **org.apache.logging.log4j.jul.Log4jBridgeHandler.sysoutDebug** (boolean) - Optional - If true, prints diagnostic information to standard output. Default: false. - **org.apache.logging.log4j.jul.Log4jBridgeHandler.appendSuffix** (String) - Optional - Suffix to append to JUL logger names. Default: null. - **org.apache.logging.log4j.jul.Log4jBridgeHandler.propagateLevels** (boolean) - Optional - If true, automatically synchronizes JUL logger levels with Log4j levels to reduce overhead. Default: false. ``` -------------------------------- ### Define Properties in Configuration Source: https://logging.apache.org/log4j/2.x/manual/configuration.html Examples of defining properties in various configuration formats. ```xml ``` ```json { "Configuration": { "Properties": { "Property": [ { "name": "log.dir", "value": "/var/log" }, { "name": "log.file", "value": "${log.dir}/app.log" } ] } ``` ```yaml Configuration: Properties: Property: - name: "log.dir" value: "/var/log" - name: "log.file" value: "${log.dir}/app.log" ``` ```properties property.log.dir = /var/log property.log.file = ${log.dir}/app.log ``` -------------------------------- ### ThreadContext Static Get Method Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-api/index-all.html Documentation for the static `get(String)` method in `org.apache.logging.log4j.ThreadContext`. ```APIDOC ## ThreadContext.get(String key) ### Description Gets the context value identified by the `key` parameter from the thread context. ### Method `get(String key)` ### Class `org.apache.logging.log4j.ThreadContext` ``` -------------------------------- ### LambdaUtil Get Methods Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-api/index-all.html Covers the `get()` methods in `LambdaUtil` for retrieving messages or results from suppliers. ```APIDOC ## LambdaUtil.get() ### Description Returns the Message supplied by the specified function or the result of evaluating the specified function. ### Method `get(MessageSupplier)` `get(Supplier)` ### Class `org.apache.logging.log4j.util.LambdaUtil` ``` -------------------------------- ### Pattern Layout Output Example Source: https://logging.apache.org/log4j/2.x/manual/layouts.html Shows the output generated by PatternLayout using the '%-5p [%t]: %m%n' conversion pattern. ```text DEBUG [main]: Message 1 WARN [main]: Message 2 ``` -------------------------------- ### Message ANSI Call Site Example Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html Example of how to use custom styles in the application code. ```java logger.info("@|KeyStyle {}|@ = @|ValueStyle {}|@", entry.getKey(), entry.getValue()); ``` -------------------------------- ### Logger Configuration Examples Source: https://logging.apache.org/log4j/2.x/manual/configuration.html Examples of defining loggers in various configuration formats supported by Log4j 2. ```xml __**(1)** __**(2)** __**(3)** __**(4)** ``` ```json "Loggers": { "Root": { __**(1)** "level": "INFO", "AppenderRef": { "ref": "APPENDER1" } }, "Logger": [ { __**(2)** "name": "org.example.no_additivity", "additivity": false, "AppenderRef": { "ref": "APPENDER2" } }, { __**(3)** "name": "org.example.no_location", "includeLocation": false, "AppenderRef": { "ref": "APPENDER3" } }, { __**(4)** "name": "org.example.level", "level": "DEBUG", "AppenderRef": { "ref": "APPENDER4" } } ] } ``` ```yaml Loggers: Root: __**(1)** level: "INFO" AppenderRef: ref: "APPENDER1" Logger: - name: "org.example.no_additivity" __**(2)** additivity: false AppenderRef: ref: "APPENDER2" - name: "org.example.no_location" __**(3)** includeLocation: false AppenderRef: ref: "APPENDER3" - name: "org.example.level" __**(4)** level: "DEBUG" AppenderRef: ref: "APPENDER4" ``` ```properties rootLogger.level = INFO __**(1)** rootLogger.appenderRef.0.ref = APPENDER1 logger.0.name = org.example.no_additivity __**(2)** logger.0.additivity = false logger.0.appenderRef.0.ref = APPENDER2 logger.1.name = org.example.no_location __**(3)** logger.1.includeLocation = false logger.1.appenderRef.0.ref = APPENDER3 logger.2.name = org.example.level __**(4)** logger.2.level = DEBUG logger.2.appenderRef.0.ref = APPENDER4 ``` -------------------------------- ### newInstanceOf Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-api/org/apache/logging/log4j/util/LoaderUtil.html Loads and instantiates a class using the default constructor. ```APIDOC ## newInstanceOf ### Description Loads and instantiates a class using the default constructor. ### Parameters - **className** (String) - Required - Fully qualified class name to load, initialize, and construct. ### Response - **Returns** (T) - New instance of the class. ``` -------------------------------- ### Lazy and Supplier Get Methods Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-api/index-all.html Provides documentation for the `get()` method used with `Lazy`, `MessageSupplier`, and `Supplier` interfaces. ```APIDOC ## get() ### Description Returns the value held by this lazy object or retrieves a message or value from a supplier. ### Method `get()` ### Interface/Class `org.apache.logging.log4j.util.Lazy` `org.apache.logging.log4j.util.MessageSupplier` `org.apache.logging.log4j.util.Supplier` ``` -------------------------------- ### Configure Log4j 2.x with YAML Source: https://logging.apache.org/log4j/2.x/manual/scripts.html Example configuration using YAML to define script-based pattern selectors and filters. ```yaml Console: name: "STDOUT" PatternLayout: ScriptPatternSelector: defaultPattern: "%d %p %m%n" ScriptRef: ref: "SELECTOR_SCRIPT" PatternMatch: - key: "NoLocation" pattern: "[%-5level] %c{1.} %msg%n" - key: "Flow" pattern: "[%-5level] %c{1.} ====== %C{1.}.%M:%L %msg ======%n" Loggers: Logger: name: "EventLogger" ScriptFilter: onMatch: "ACCEPT" onMismatch: "DENY" Script: name: "EVENT_LOGGER_FILTER" language: "groovy" scriptText: | if (logEvent.getMarker() != null && logEvent.getMarker().isInstanceOf("FLOW")) { return true; } else if (logEvent.getContextMap().containsKey("UserId")) { return true; } return false; Root: level: "INFO" ScriptFilter: onMatch: "ACCEPT" onMismatch: "DENY" ScriptRef: ref: "ROOT_FILTER" AppenderRef: ref: "STDOUT" Scripts: Script: name: "SELECTOR_SCRIPT" language: "javascript" scriptText: | var result; if (logEvent.getLoggerName().equals("JavascriptNoLocation")) { result = "NoLocation"; } else if (logEvent.getMarker() != null && logEvent.getMarker().isInstanceOf("FLOW")) { result = "Flow"; } result; ScriptFile: name: "ROOT_FILTER" path: "scripts/filter.groovy" ``` -------------------------------- ### MapMessage and ThreadContextMap Get Methods Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-api/index-all.html Details the `get(String)` method for retrieving values from `MapMessage` and various `ThreadContextMap` implementations. ```APIDOC ## get(String key) ### Description Retrieves the value associated with the specified key from a `MapMessage` or a `ThreadContextMap`. Returns `null` if the key is not present. ### Method `get(String key)` ### Interface/Class `org.apache.logging.log4j.message.MapMessage` `org.apache.logging.log4j.spi.DefaultThreadContextMap` `org.apache.logging.log4j.spi.NoOpThreadContextMap` `org.apache.logging.log4j.spi.ReadOnlyThreadContextMap` `org.apache.logging.log4j.spi.ThreadContextMap` ``` -------------------------------- ### KeyStoreConfiguration Creation Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/config/plugins/class-use/PluginAttribute.html Methods for creating KeyStoreConfiguration instances. ```APIDOC ## KeyStoreConfiguration.createKeyStoreConfiguration ### Description Creates a KeyStoreConfiguration instance with specified location, password, password environment variable, password file, key store type, and key manager factory algorithm. ### Method static KeyStoreConfiguration ### Endpoint N/A (Java method) ### Parameters - **location** (String) - Description of the location parameter. - **password** (char[]) - Description of the password parameter. - **passwordEnvironmentVariable** (String) - Description of the passwordEnvironmentVariable parameter. - **passwordFile** (String) - Description of the passwordFile parameter. - **keyStoreType** (String) - Description of the keyStoreType parameter. - **keyManagerFactoryAlgorithm** (String) - Description of the keyManagerFactoryAlgorithm parameter. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Plugin Visitors with Configuration Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/config/class-use/Configuration.html Demonstrates various plugin visitors that accept a Configuration object. ```APIDOC ## Plugin Visitors ### Description Methods in `org.apache.logging.log4j.core.config.plugins.visitors` that accept a `Configuration` object for visiting nodes and retrieving values. ### Methods - **PluginAttributeVisitor.visit(Configuration configuration, Node node, LogEvent event, StringBuilder log)** - **PluginBuilderAttributeVisitor.visit(Configuration configuration, Node node, LogEvent event, StringBuilder log)** - **PluginConfigurationVisitor.visit(Configuration configuration, Node node, LogEvent event, StringBuilder log)** - **PluginElementVisitor.visit(Configuration configuration, Node node, LogEvent event, StringBuilder log)** - **PluginLoggerContextVisitor.visit(Configuration configuration, Node node, LogEvent event, StringBuilder log)** - **PluginNodeVisitor.visit(Configuration configuration, Node node, LogEvent event, StringBuilder log)** - **PluginValueVisitor.visit(Configuration configuration, Node node, LogEvent event, StringBuilder log)** - **PluginVisitor.visit(Configuration configuration, Node node, LogEvent event, StringBuilder log)** ### Parameters - **configuration** (Configuration) - Required - The configuration context. - **node** (Node) - Required - The node to visit. - **event** (LogEvent) - Required - The log event. - **log** (StringBuilder) - Required - A string builder for logging. ``` -------------------------------- ### Example: Logging Localized Exception Message Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example demonstrates logging the localized exception message using the 'short.localizedMessage' property. ```java %ex{short.localizedMessage} ``` -------------------------------- ### Example: Logging Exception Message Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example shows how to log only the exception message using the 'short.message' property of the exception converter. ```java %ex{short.message} ``` -------------------------------- ### Configure Log4j 2.x with Properties Source: https://logging.apache.org/log4j/2.x/manual/scripts.html Example configuration using the properties file format to define script-based pattern selectors and filters. ```properties appender.0.type = Console appender.0.name = STDOUT appender.0.layout.type = PatternLayout appender.0.layout.selector = ScriptPatternSelector appender.0.layout.selector.defaultPattern = %d %p %m%n appender.0.layout.selector.scriptRef.type = ScriptRef appender.0.layout.selector.scriptRef.ref = SELECTOR_SCRIPT appender.0.layout.selector.match[0].type = PatternMatch appender.0.layout.selector.match[0].key = NoLocation appender.0.layout.selector.match[0].pattern = [%-5level] %c{1.} %msg%n appender.0.layout.selector.match[1].type = PatternMatch appender.0.layout.selector.match[1].key = Flow appender.0.layout.selector.match[1].pattern = \ [%-5level] %c{1.} ====== %C{1.}.%M:%L %msg ======%n logger.0.name = EventLogger logger.0.filter.0.type = ScriptFilter logger.0.filter.0.onMatch = ACCEPT logger.0.filter.0.onMismatch = DENY logger.0.filter.0.script.type = Script logger.0.filter.0.script.name = EVENT_LOGGER_FILTER logger.0.filter.0.script.language = groovy logger.0.filter.0.script.scriptText = \ if (logEvent.getMarker() != null\ && logEvent.getMarker().isInstanceOf("FLOW"))) {\ return true;\ } else if (logEvent.getContextMap().containsKey("UserId")) {\ return true;\ }\ return false; rootLogger.level = INFO rootLogger.filter.0.type = ScriptFilter rootLogger.filter.0.onMatch = ACCEPT rootLogger.filter.0.onMismatch = DENY rootLogger.filter.0.scriptRef.type = ScriptRef rootLogger.filter.0.scriptRef.ref = ROOT_FILTER rootLogger.appenderRef.0.ref = STDOUT script.0.type = Script script.0.name = SELECTOR_SCRIPT script.0.language = javascript script.0.scriptText = \ var result;\ if (logEvent.getLoggerName().equals("JavascriptNoLocation")) {\ result = "NoLocation";\ } else if (logEvent.getMarker() != null\ && logEvent.getMarker().isInstanceOf("FLOW")) {\ result = "Flow";\ }\ result; script.1.type = ScriptFile script.1.name = ROOT_FILTER script.1.path = scripts/filter.groovy ``` -------------------------------- ### Pattern Layout Conversion Pattern Example Source: https://logging.apache.org/log4j/2.x/manual/layouts.html Demonstrates a conversion pattern for PatternLayout, showing how to format log event properties. ```java LOGGER.debug("Message 1"); LOGGER.warn("Message 2"); ``` -------------------------------- ### MapFilter Example in log4j2.json Source: https://logging.apache.org/log4j/2.x/manual/filters.html An example of a MapFilter configured in log4j2.json. It mirrors the XML configuration, specifying the operator and KeyValuePair elements. ```json "MapFilter": { "operator": "AND", "KeyValuePair": [ { "key": "eventType", "value": "authentication" }, { "key": "eventId", "value": "login" }, { "key": "eventId", "value": "logout" } ] } ``` -------------------------------- ### KeyStoreConfiguration.createKeyStoreConfiguration Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/net/ssl/class-use/KeyStoreConfiguration.html Creates a new KeyStoreConfiguration instance using location, password, and algorithm settings. ```APIDOC ## KeyStoreConfiguration.createKeyStoreConfiguration ### Description Creates a KeyStoreConfiguration instance for SSL support. ### Parameters - **location** (String) - Required - The location of the keystore. - **password** (char[]) - Required - The password for the keystore. - **passwordEnvironmentVariable** (String) - Optional - Environment variable for the password. - **passwordFile** (String) - Optional - File path containing the password. - **keyStoreType** (String) - Required - The type of the keystore (e.g., PKCS12, JKS). - **keyManagerFactoryAlgorithm** (String) - Required - The algorithm for the KeyManagerFactory. ``` -------------------------------- ### JSON Event Template Example Source: https://logging.apache.org/log4j/2.x/manual/layouts.html An example JSON template defining the structure for log events, including timestamp, constants, and messages. ```json { "instant": { "$resolver": "timestamp", "pattern": { "format": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "timeZone": "UTC" } }, "someConstant": 1, "message": { "$resolver": "message", "stringified": true } } ``` -------------------------------- ### Example: Custom Separator for Stack Trace Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example uses a custom separator string literal for the exception stack trace output. ```java %ex{separator(---)} ``` -------------------------------- ### Start HttpAppender Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/appender/HttpAppender.html Initializes the appender and makes it available for use. ```java public void start() ``` -------------------------------- ### Initialize Loggers Source: https://logging.apache.org/log4j/2.x/manual/api.html Demonstrates common ways to initialize a Logger, with a preference for the no-argument LogManager.getLogger() method. ```java public class LoggerNameTest { Logger logger1 = LogManager.getLogger(LoggerNameTest.class); Logger logger2 = LogManager.getLogger(LoggerNameTest.class.getName()); Logger logger3 = LogManager.getLogger(); } ``` -------------------------------- ### Example: Custom Suffix for Stack Trace Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example applies a Pattern Layout conversion pattern as a suffix to the exception stack trace output. ```java %ex{suffix(%n%d)} ``` -------------------------------- ### Java Logging with System.out.format for Context Source: https://logging.apache.org/log4j/2.x/manual/getting-started.html This example improves upon basic logging by using System.out.format to include dynamic information, such as a table name, within the log message. It also demonstrates how to specify log severity and use platform-independent newlines. ```java private void truncateTable(String tableName) { System.out.format("[WARN] truncating table \`%s\`%n", tableName); db.truncate(tableName); } ``` -------------------------------- ### Example: Filtering Stack Trace Elements Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example filters out stack trace elements belonging to the 'org.junit' package, denoting suppressed elements. ```java %ex{filters(org.junit)} ``` -------------------------------- ### Log method entry with parameters Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-api/org/apache/logging/log4j/spi/AbstractLogger.html Demonstrates manual usage of the entry method to log method parameters. Consider using traceEntry methods or aspect-oriented programming for cleaner implementation. ```java public void doSomething(String foo, int bar) { LOGGER.entry(foo, bar); // do something } ``` -------------------------------- ### Configurator.initialize Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/class-use/LoggerContext.html Initializes the Logging Context using various configuration sources. ```APIDOC ## static Configurator.initialize ### Description Initializes the Logging Context with the provided configuration source or object. ### Parameters #### Method Parameters - **loader** (ClassLoader) - Required - The class loader to use. - **configuration** (Configuration) - Required - The configuration object. - **source** (ConfigurationSource) - Required - The configuration source. - **externalContext** (Object) - Optional - An external context object. ``` -------------------------------- ### XML Layout Example Output Source: https://logging.apache.org/log4j/2.x/manual/layouts.html This is an example of how a log event is encoded using the XML Layout. Note that this layout is planned for removal in a future release. ```xml Hello, world! one two ``` -------------------------------- ### Example: Logging Exception Method Name Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example shows how to log the method name of the first stack trace element using the 'short.methodName' property. ```java %ex{short.methodName} ``` -------------------------------- ### createKeyStoreConfiguration Method Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/net/ssl/KeyStoreConfiguration.html Factory method for creating KeyStoreConfiguration instances. ```APIDOC ## POST /websites/logging_apache_log4j_2_x/createKeyStoreConfiguration ### Description Factory method to create a KeyStoreConfiguration. ### Method POST ### Endpoint /websites/logging_apache_log4j_2_x/createKeyStoreConfiguration ### Parameters #### Query Parameters - **location** (String) - Required - The location of the KeyStore, a file path, URL or resource. - **password** (char[]) - Required - The password to access the KeyStore. - **passwordEnvironmentVariable** (String) - Optional - The environment variable containing the password. - **passwordFile** (String) - Optional - The file containing the password. - **type** (String) - Optional - The KeyStore type, null defaults to "JKS". - **keyManagerFactoryAlgorithm** (String) - Optional - The standard name of the requested algorithm. See the Java Secure Socket Extension Reference Guide for information about these names. ### Returns a new KeyStoreConfiguration ### Throws - `StoreConfigurationException` - Thrown if this call cannot load the KeyStore. ### Deprecated Methods - `createKeyStoreConfiguration(String location, char[] password, String keyStoreType, String keyManagerFactoryAlgorithm)`: Use the overloaded method with more parameters. - `createKeyStoreConfiguration(String location, String password, String keyStoreType, String keyManagerFactoryAlgorithm)`: Use the overloaded method with more parameters. ``` -------------------------------- ### AbstractKeyStoreConfiguration Constructors Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/index-all.html Constructors for KeyStore configuration. Includes deprecated versions and a recommended constructor using PasswordProvider. ```APIDOC ## Class: AbstractKeyStoreConfiguration ### Description Configuration of the KeyStore ### Constructors #### `AbstractKeyStoreConfiguration(String keyStoreName, char[] keyStorePassword, String keyStoreType)` * **Deprecated**: Use `AbstractKeyStoreConfiguration(String, PasswordProvider, String)` instead. #### `AbstractKeyStoreConfiguration(String keyStoreName, String keyStorePassword, String keyStoreType)` * **Deprecated**: Use `AbstractKeyStoreConfiguration(String, PasswordProvider, String)` instead. #### `AbstractKeyStoreConfiguration(String keyStoreName, PasswordProvider keyStorePasswordProvider, String keyStoreType)` * Constructs the KeyStore configuration. ``` -------------------------------- ### Example: Logging Exception Line Number Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example demonstrates logging the line number of the first stack trace element using the 'short.lineNumber' property. ```java %ex{short.lineNumber} ``` -------------------------------- ### HtmlLayout Creation Methods Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/layout/HtmlLayout.html Demonstrates how to create instances of HtmlLayout using static factory methods. ```APIDOC ## HtmlLayout Creation ### Create Default Layout ```java HtmlLayout layout = HtmlLayout.createDefaultLayout(); ``` ### Create Layout with Custom Settings (Deprecated) ```java // Deprecated method, usenewBuilder() for new configurations Charset charset = StandardCharsets.UTF_8; HtmlLayout layout = HtmlLayout.createLayout(true, "My Log", "text/html", charset, "10pt", "arial,sans-serif"); ``` ### Using the Builder API ```java HtmlLayout layout = HtmlLayout.newBuilder() .withLocationInfo(true) .withTitle("My Log Page") .withCharset(StandardCharsets.UTF_8) .withFontSize("12pt") .withFont("Verdana, sans-serif") .build(); ``` ``` -------------------------------- ### Routes Builder and Configuration Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/appender/routing/class-use/Route.html This section explains how to build and configure Routes using the Routes.Builder. ```APIDOC ## Routes Builder and Configuration ### Description This section covers the methods for building and configuring `Routes` using the `Routes.Builder` class, including setting and adding `Route` objects. ### Methods #### `static Routes createRoutes(String pattern, Route... routes)` **Description:** Creates a `Routes` object with a pattern and an array of `Route` objects. This method is deprecated. **Parameters:** - **pattern** (String) - Required - The pattern for the routes. - **routes** (Route...) - Required - An array of `Route` objects. **Deprecated:** since 2.7; use `Routes.newBuilder()`. #### `Routes.Builder setRoutes(Route[] routes)` **Description:** Sets the array of `Route` objects for the `Routes.Builder`. **Parameters:** - **routes** (Route[]) - Required - An array of `Route` objects to set. **Returns:** - `Routes.Builder` - The updated `Routes.Builder` instance. #### `Routes.Builder withRoutes(Route[] routes)` **Description:** Adds an array of `Route` objects to the `Routes.Builder`. This method is deprecated. **Parameters:** - **routes** (Route[]) - Required - An array of `Route` objects to add. **Deprecated:** since 2.26.0 use `Routes.Builder.setRoutes(Route[])`. ### Request Example ```json { "example": "No direct request example, as this is typically configured via Log4j configuration files or programmatically." } ``` ### Response #### Success Response (200) - **Routes.Builder** (Object) - The builder object for configuring Routes. #### Response Example ```json { "example": "Builder object details would be represented here if retrieved directly." } ``` ``` -------------------------------- ### Example: Logging Exception Class Name Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example demonstrates logging the class name of the first stack trace element using the 'short.className' property. ```java %ex{short.className} ``` -------------------------------- ### SystemPropertyArbiter.Builder Methods Source: https://logging.apache.org/log4j/2.x/javadoc/log4j-core/org/apache/logging/log4j/core/config/arbiters/SystemPropertyArbiter.Builder.html Methods available for configuring and building a SystemPropertyArbiter instance. ```APIDOC ## Method: setPropertyName ### Description Sets the system property name to be evaluated by the arbiter. ### Parameters - **propertyName** (String) - Required - The name of the system property. ### Response - **Builder** - Returns the builder instance for chaining. ## Method: setPropertyValue ### Description Sets the expected value for the system property. ### Parameters - **propertyValue** (String) - Required - The value to match against the system property. ### Response - **Builder** - Returns the builder instance for chaining. ## Method: build ### Description Constructs the SystemPropertyArbiter instance using the configured property name and value. ### Response - **SystemPropertyArbiter** - The fully configured instance. ``` -------------------------------- ### Example: Including Stack Trace with Custom Separator Source: https://logging.apache.org/log4j/2.x/manual/pattern-layout.html This example demonstrates how to explicitly add a newline before the exception stack trace when using the %ex converter. ```java %n%ex ```