Skip to content

Instantly share code, notes, and snippets.

@kentyeh
Last active March 30, 2021 09:15
Show Gist options
  • Save kentyeh/408aa6139e67ecaaba457e040abc1568 to your computer and use it in GitHub Desktop.
Save kentyeh/408aa6139e67ecaaba457e040abc1568 to your computer and use it in GitHub Desktop.
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.ConfigurationBuilder;
import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.layout.PatternLayout;
/**
* @see
* <a href="https://stackoverflow.com/questions/30881990/how-to-configure-log4j-2-x-purely-programmatically/58002997#58002997">From
* Stack Overflow</a>
*/
public class Log4j2Console {
//Must inintialize in main thread.
static {
ConfigurationBuilder<BuiltConfiguration> builder
= ConfigurationBuilderFactory.newConfigurationBuilder();
// configure a console appender
builder.add(
builder.newAppender("stdout", "Console")
.add(
builder.newLayout(PatternLayout.class.getSimpleName())
.addAttribute(
"pattern",
"%d{HH:mm:ss.SSS} [%t] %highlight{%-5level} %class{1.}.%M(%L) - %highlight{%msg}%n%ex{full}%n"
)
)
);
// configure the root logger
builder.add(
builder.newRootLogger(Level.INFO)
.add(builder.newAppenderRef("stdout"))
// Additional Logger for package
).add(builder.newLogger("com.example", Level.DEBUG)
);
// apply the configuration
Configurator.initialize(builder.build());
}
public static Logger getLogger(Class<?> clazz) {
return LogManager.getLogger(clazz);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment