Created
August 27, 2023 19:03
-
-
Save mbarkley/c9f2311c35b6d46231ca5d6cd6176d65 to your computer and use it in GitHub Desktop.
Log4J Interpolation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///usr/bin/env jbang "$0" "$@" ; exit $? | |
//DEPS org.apache.logging.log4j:log4j-core:2.14.0 | |
//DEPS org.apache.logging.log4j:log4j-api:2.14.0 | |
//RUNTIME_OPTIONS -Dlog4j2.enableJndiLookup=true -Dtest.system.property=the-test-value | |
import org.apache.logging.log4j.Level; | |
import org.apache.logging.log4j.LogManager; | |
import org.apache.logging.log4j.Logger; | |
import org.apache.logging.log4j.core.config.Configurator; | |
import org.apache.logging.log4j.core.config.builder.api.*; | |
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration; | |
public class log4j { | |
public static void main(String... args) { | |
System.out.println("JNDI lookup: " + System.getProperty("log4j2.enableJndiLookup")); | |
System.out.println("Test system property: " + System.getProperty("test.system.property")); | |
ConfigurationBuilder<BuiltConfiguration> builder | |
= ConfigurationBuilderFactory.newConfigurationBuilder(); | |
AppenderComponentBuilder console = builder.newAppender("stdout", "Console"); | |
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.INFO); | |
rootLogger.add(builder.newAppenderRef("stdout")); | |
LayoutComponentBuilder standard = builder.newLayout("PatternLayout"); | |
standard.addAttribute("pattern", "%d [%t] %-5level: [${sys:test.system.property}] %msg%n%throwable"); | |
console.add(standard); | |
builder.add(console); | |
builder.add(rootLogger); | |
Configurator.initialize(builder.build()); | |
String value = "${sys:test.system.property}"; | |
final Logger log = LogManager.getLogger(log4j.class); | |
log.info("Will this concatenation get interpreted?: " + value); | |
log.info("Will this interpolation get interpreted?: {}", value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment