下面列出了怎么用org.apache.logging.log4j.core.LoggerContext的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Use this to override the default application log file, before you
* initialize the logging system.
*
* @param file The file to use as the application log file
*/
synchronized static void setApplicationLogFile(File file) {
if (APPLICATION_LOG_FILE != null && !SystemUtilities.isInTestingMode()) {
// don't throw the exception so that we may can continue to work
System.err.println("Cannot change the log file once it has been " +
"initialized!\nYou must call this method before calling " +
"LoggingInitialization.initializeLoggingSystem()");
(new IllegalStateException()).printStackTrace();
}
APPLICATION_LOG_FILE = file;
// Need to set the system property that the log4j2 configuration reads in
// order to determine the log file name. Once that's set, the log
// configuration must be 'kicked' to pick up the change.
System.setProperty("logFilename", file.getAbsolutePath());
if (INITIALIZED) {
((LoggerContext) LogManager.getContext(false)).reconfigure();
}
}
/**
* Use this to override the default application log file, before you
* initialize the logging system.
*
* @param file The file to use as the application log file
*/
synchronized static void setScriptLogFile(File file) {
if (SCRIPT_LOG_FILE != null && !SystemUtilities.isInTestingMode()) {
// don't throw the exception so that we may can continue to work
System.err.println("Cannot change the log file once it has been " +
"initialized!\nYou must call this method before calling " +
"LoggingInitialization.initializeLoggingSystem()");
(new IllegalStateException()).printStackTrace();
}
SCRIPT_LOG_FILE = file;
// Need to set the system property that the log4j2 configuration reads in
// order to determine the script log file name. Once that's set, the log
// configuration must be 'kicked' to pick up the change.
System.setProperty("scriptLogFilename", file.getAbsolutePath());
if (INITIALIZED) {
((LoggerContext) LogManager.getContext(false)).reconfigure();
}
}
private void createBizLogger() {
if (env.containsProperty(MonitorConfigSpringApplicationRunListener.LOG_KAFKA_BOOTSTRAPSERVERS)) {
String appenderName = "AdvancedKafkaAppender";
LoggerContext loggerContext = (LoggerContext)LogManager.getContext(false);
Configuration configuration = loggerContext.getConfiguration();
AdvancedKafkaAppender kafkaAppender =
AdvancedKafkaAppender.createAppender(CustomJsonLayout.createDefaultLayout(), null, configuration,
appenderName, getKafkaTopic(), getBootstrapservers());
kafkaAppender.start();
AppenderRef ref = AppenderRef.createAppenderRef(appenderName, null, null);
AppenderRef[] refs = new AppenderRef[] {ref};
LoggerConfig loggerConfig =
LoggerConfig.createLogger(false, Level.INFO, "BizLogger", null, refs, null, configuration, null);
loggerConfig.addAppender(kafkaAppender, null, null);
configuration.addLogger("BizLogger", loggerConfig);
}
}
/**
* Directly test the methods in the {@link LogLevel} annotation class
*/
@LogLevel("org.apache.solr.bogus_logger.MethodLogLevel=TRACE")
public void testWhiteBoxMethods() {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
final Map<String,Level> oldLevels = LogLevel.Configurer.setLevels(bogus_logger_prefix + "=TRACE");
//
assertEquals(oldLevels.toString(), 1, oldLevels.size());
assertNull(oldLevels.get(bogus_logger_prefix));
//
assertEquals(Level.TRACE, config.getLoggerConfig(bogus_logger_prefix).getLevel());
assertEquals(Level.TRACE, LogManager.getLogger(bogus_logger_prefix).getLevel());
// restore (to 'unset' values)...
LogLevel.Configurer.restoreLogLevels(oldLevels);
assertEquals(bogus_logger_prefix
+ " should have had it's config unset; should now return the 'root' LoggerConfig",
config.getRootLogger(),
config.getLoggerConfig(bogus_logger_prefix));
assertEquals(DEFAULT_LOG_LEVEL, LogManager.getLogger(bogus_logger_prefix).getLevel());
}
public void testNoNulCharacters(final String message, final String expected) throws IOException {
@SuppressWarnings("resource")
final LoggerContext loggerContext = loggerContextRule.getLoggerContext();
final Logger logger = loggerContext.getLogger("com.example");
logger.error("log:", message);
loggerContext.stop();
final File file = new File(FILE_PATH);
final byte[] contents = FileUtils.readFileToByteArray(file);
int count0s = 0;
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < contents.length; i++) {
final byte b = contents[i];
if (b == 0) {
sb.append(i);
sb.append(", ");
count0s++;
}
}
Assert.assertEquals("File contains " + count0s + " 0x00 byte at indices " + sb, 0, count0s);
final List<String> readLines = FileUtils.readLines(file, Charset.defaultCharset());
final String actual = readLines.get(0);
// Assert.assertTrue(actual, actual.contains(message));
Assert.assertEquals(actual, expected, actual);
Assert.assertEquals(1, readLines.size());
}
@Override
public StringWriter addLoggingWriterAppender(String appenderName)
{
// Get the configuration
final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
final Configuration configuration = loggerContext.getConfiguration();
// Create a string writer as part of the appender so logging will be written to it.
StringWriter stringWriter = new StringWriter();
// Create and start the appender with the string writer.
Appender appender = WriterAppender.createAppender(null, null, stringWriter, appenderName, false, true);
appender.start();
// Add the appender to the root logger.
configuration.getRootLogger().addAppender(appender, null, null);
// Return the string writer.
return stringWriter;
}
/**
* Sets the levels of <code>parentLogger</code> and all 'child' loggers to the given <code>level</code>.
* @param parentLogger the parent logger
* @param level the new level
*/
public static void setAllLevels(final String parentLogger, final Level level) {
// 1) get logger config
// 2) if exact match, use it, if not, create it.
// 3) set level on logger config
// 4) update child logger configs with level
// 5) update loggers
final LoggerContext loggerContext = LoggerContext.getContext(false);
final Configuration config = loggerContext.getConfiguration();
boolean set = setLevel(parentLogger, level, config);
for (final Map.Entry<String, LoggerConfig> entry : config.getLoggers().entrySet()) {
if (entry.getKey().startsWith(parentLogger)) {
set |= setLevel(entry.getValue(), level);
}
}
if (set) {
loggerContext.updateLoggers();
}
}
public void test(final String[] args) {
System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
// System.out.println(System.getProperty("java.class.path"));
final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml"
: args[0];
try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) {
final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class);
logger.fatal("Fatal message.");
logger.error("Error message.");
logger.warn("Warning message.");
logger.info("Information message.");
logger.debug("Debug message.");
logger.trace("Trace message.");
logger.error("Error message.", new IOException("test"));
}
}
/**
* Not a real test, just make sure we can compile access to the typed manager.
*
* @throws IOException
*/
@Test
public void testAccessManagerWithStrings() throws IOException {
try (final LoggerContext ctx = LoggerContext.getContext(false)) {
final Configuration config = ctx.getConfiguration();
final File file = File.createTempFile("RollingFileAppenderAccessTest", ".tmp");
file.deleteOnExit();
// @formatter:off
final RollingFileAppender appender = RollingFileAppender.newBuilder()
.setFileName(file.getCanonicalPath())
.setFilePattern("FilePattern")
.setName("Name")
.setPolicy(OnStartupTriggeringPolicy.createPolicy(1))
.setConfiguration(config)
.build();
// @formatter:on
final RollingFileManager manager = appender.getManager();
// Since the RolloverStrategy and TriggeringPolicy are immutable, we could also use generics to type their
// access.
Assert.assertNotNull(manager.getRolloverStrategy());
Assert.assertNotNull(manager.getTriggeringPolicy());
}
}
/** {@inheritDoc} */
@Override public void setNodeId(UUID nodeId) {
A.notNull(nodeId, "nodeId");
this.nodeId = nodeId;
// Set nodeId as system variable to be used at configuration.
System.setProperty(NODE_ID, U.id8(nodeId));
if (inited) {
final LoggerContext ctx = impl.getContext();
synchronized (mux) {
inited = false;
}
addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
@Override public Logger apply(Boolean init) {
if (init)
ctx.reconfigure();
return (Logger)LogManager.getRootLogger();
}
});
}
}
@Test
public void testRewrite() throws Exception {
Logger logger = LogManager.getLogger("test");
ThreadContext.put("key1", "This is a test");
ThreadContext.put("hello", "world");
logger.debug("Say hello");
LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
Configuration configuration = context.getConfiguration();
Map<String, Appender> appenders = configuration.getAppenders();
ListAppender eventAppender = null;
for (Map.Entry<String, Appender> entry : appenders.entrySet()) {
if (entry.getKey().equals("events")) {
eventAppender = (ListAppender) ((AppenderAdapter.Adapter) entry.getValue()).getAppender();
}
}
assertNotNull("No Event Appender", eventAppender);
List<LoggingEvent> events = eventAppender.getEvents();
assertTrue("No events", events != null && events.size() > 0);
assertNotNull("No properties in the event", events.get(0).getProperties());
assertTrue("Key was not inserted", events.get(0).getProperties().containsKey("key2"));
assertEquals("Key value is incorrect", "Log4j", events.get(0).getProperties().get("key2"));
}
@Test
public void testConfig() {
try (final LoggerContext ctx = Configurator.initialize("Test1",
"target/test-classes/log4j2-dynamicfilter.xml")) {
final Configuration config = ctx.getConfiguration();
final Filter filter = config.getFilter();
assertNotNull("No DynamicThresholdFilter", filter);
assertTrue("Not a DynamicThresholdFilter", filter instanceof DynamicThresholdFilter);
final DynamicThresholdFilter dynamic = (DynamicThresholdFilter) filter;
final String key = dynamic.getKey();
assertNotNull("Key is null", key);
assertEquals("Incorrect key value", "loginId", key);
final Map<String, Level> map = dynamic.getLevelMap();
assertNotNull("Map is null", map);
assertEquals("Incorrect number of map elements", 1, map.size());
}
}
@Override
public void shutdown(final String fqcn, final ClassLoader loader, final boolean currentContext,
final boolean allContexts) {
LoggerContext ctx = null;
if (currentContext) {
ctx = ContextAnchor.THREAD_CONTEXT.get();
} else if (loader != null) {
ctx = findContext(loader);
} else {
final Class<?> clazz = StackLocatorUtil.getCallerClass(fqcn);
if (clazz != null) {
ctx = findContext(clazz.getClassLoader());
}
if (ctx == null) {
ctx = ContextAnchor.THREAD_CONTEXT.get();
}
}
if (ctx != null) {
ctx.stop(DEFAULT_STOP_TIMEOUT, TimeUnit.MILLISECONDS);
}
}
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
final boolean currentContext, final List<URI> configLocations, final String name) {
final LoggerContext ctx = selector
.getContext(fqcn, loader, currentContext, null/*this probably needs to change*/);
if (externalContext != null && ctx.getExternalContext() == null) {
ctx.setExternalContext(externalContext);
}
if (name != null) {
ctx.setName(name);
}
if (ctx.getState() == LifeCycle.State.INITIALIZED) {
if ((configLocations != null && !configLocations.isEmpty())) {
ContextAnchor.THREAD_CONTEXT.set(ctx);
final List<AbstractConfiguration> configurations = new ArrayList<>(configLocations.size());
for (final URI configLocation : configLocations) {
final Configuration currentReadConfiguration = ConfigurationFactory.getInstance()
.getConfiguration(ctx, name, configLocation);
if (currentReadConfiguration instanceof AbstractConfiguration) {
configurations.add((AbstractConfiguration) currentReadConfiguration);
} else {
LOGGER.error(
"Found configuration {}, which is not an AbstractConfiguration and can't be handled by CompositeConfiguration",
configLocation);
}
}
final CompositeConfiguration compositeConfiguration = new CompositeConfiguration(configurations);
LOGGER.debug("Starting LoggerContext[name={}] from configurations at {}", ctx.getName(),
configLocations);
ctx.start(compositeConfiguration);
ContextAnchor.THREAD_CONTEXT.remove();
} else {
ctx.start();
}
}
return ctx;
}
@Override
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final boolean currentContext,
final URI configLocation) {
final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
return ctx != null ? ctx : CONTEXT;
}
@BeforeEach
void setUp() {
ctx = new LoggerContext("Test");
ctx.reconfigure();
ctx.getConfiguration().getProperties().put("node.id", "foo");
root = ctx.getRootLogger();
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
EcsLayout ecsLayout = EcsLayout.newBuilder()
.setConfiguration(ctx.getConfiguration())
.setServiceName("test")
.setIncludeMarkers(true)
.setIncludeOrigin(true)
.setStackTraceAsArray(true)
.setEventDataset("testdataset.log")
.setAdditionalFields(new KeyValuePair[]{
new KeyValuePair("cluster.uuid", "9fe9134b-20b0-465e-acf9-8cc09ac9053b"),
new KeyValuePair("node.id", "${node.id}"),
new KeyValuePair("empty", "${empty}"),
new KeyValuePair("clazz", "%C"),
new KeyValuePair("custom", "%custom"),
new KeyValuePair("emptyPattern", "%notEmpty{%invalidPattern}"),
})
.build();
listAppender = new ListAppender("ecs", null, ecsLayout, false, false);
listAppender.start();
root.addAppender(listAppender);
root.setLevel(Level.DEBUG);
}
/**
* The main method of the application.
*
* @param args the command line arguments passed to the program.
*/
@SuppressWarnings("PMD.DoNotCallSystemExit") // Using System.exit is allowed for an actual application to exit.
public static void main(String[] args)
{
ToolsCommonConstants.ReturnValue returnValue;
try
{
// Initialize Log4J with the resource. The configuration itself can use "monitorInterval" to have it refresh if it came from a file.
LoggerContext loggerContext = Configurator.initialize(null, ToolsCommonConstants.LOG4J_CONFIG_LOCATION);
// For some initialization errors, a null context will be returned.
if (loggerContext == null)
{
// We shouldn't get here since we already checked if the location existed previously.
throw new IllegalArgumentException("Invalid configuration found at resource location: \"" + ToolsCommonConstants.LOG4J_CONFIG_LOCATION + "\".");
}
RetentionExpirationDestroyerApp exporterApp = new RetentionExpirationDestroyerApp();
returnValue = exporterApp.go(args);
}
catch (Exception e)
{
LOGGER.error("Error running herd retention expiration destroyer application. {}", e.toString(), e);
returnValue = ToolsCommonConstants.ReturnValue.FAILURE;
}
// Exit with the return code.
System.exit(returnValue.getReturnCode());
}
/**
* Extracts the {@link LogPanelAppender} from the root logger configuration
* and hands an instance of this panel to it.
*/
private void addLogAppender() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LogPanelAppender logAppender = config.getAppender("logPanel");
if (logAppender == null) {
Msg.error(this, "Couldn't find LogPanelAppender instance in the Log4j context; " +
"nothing will be logged to the application's Front-end panel.");
return;
}
logAppender.setLogListener(this);
}
public AdvancedKafkaManager(final LoggerContext loggerContext, final String name, final String bootstrapServers) {
super(loggerContext, name);
config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
config.put(ProducerConfig.ACKS_CONFIG, "all");
config.put(ProducerConfig.RETRIES_CONFIG, 0);
config.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
config.put(ProducerConfig.LINGER_MS_CONFIG, 1);
config.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
}
@Test
public void testAdvertisementsRemovedOnConfigStop() {
verifyExpectedEntriesAdvertised(InMemoryAdvertiser.getAdvertisedEntries());
final LoggerContext ctx = LoggerContext.getContext();
ctx.stop();
final Map<Object, Map<String, String>> entries = InMemoryAdvertiser.getAdvertisedEntries();
assertTrue("Entries found: " + entries, entries.isEmpty());
//reconfigure for subsequent testing
ctx.start();
}
private static void setLogLevel(Logger logger, Level level) {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
loggerConfig.setLevel(level);
ctx.updateLoggers();
}
private void initializeJndi(final String location) {
final URI configLocation = getConfigURI(location);
if (this.name == null) {
throw new IllegalStateException("A log4jContextName context parameter is required");
}
LoggerContext context;
final LoggerContextFactory factory = LogManager.getFactory();
if (factory instanceof Log4jContextFactory) {
final ContextSelector selector = ((Log4jContextFactory) factory).getSelector();
if (selector instanceof NamedContextSelector) {
this.namedContextSelector = (NamedContextSelector) selector;
context = this.namedContextSelector.locateContext(this.name, this.servletContext, configLocation);
ContextAnchor.THREAD_CONTEXT.set(context);
if (context.isInitialized()) {
context.start();
}
ContextAnchor.THREAD_CONTEXT.remove();
} else {
LOGGER.warn("Potential problem: Selector is not an instance of NamedContextSelector.");
return;
}
} else {
LOGGER.warn("Potential problem: LoggerContextFactory is not an instance of Log4jContextFactory.");
return;
}
this.loggerContext = context;
LOGGER.debug("Created logger context for [{}] using [{}].", this.name, context.getClass().getClassLoader());
}
public static void appendSimplifiedConsoleLogger(Level level) {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
Layout layout = PatternLayout.createLayout("%msg%n", null, config, null, null, true, false, null, null);
Appender appender = ConsoleAppender.createAppender(layout, null, ConsoleAppender.Target.SYSTEM_OUT, "stdout", true, true);
appender.start();
config.getRootLogger().addAppender(appender, level, null);
ctx.updateLoggers();
}
public static void appendFileLogger(Level level, String name, Path filePath) {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
Layout layout = PatternLayout.createLayout("%d{HH:mm} [%-5p] %msg%n", null, config, null, null, true, false, null, null);
Appender appender = FileAppender.createAppender(filePath.toFile().getAbsolutePath(), "true", "false", name, "true",
"false", "false", "8192", layout, null, "false", null, config);
appender.start();
config.getRootLogger().addAppender(appender, level, null);
ctx.updateLoggers();
}
private void addLogTopicHandler() {
if (logAppender == null) return;
LoggerContext context = LoggerContext.getContext(false);
Configuration config = context.getConfiguration();
config.addAppender(logAppender);
for (final LoggerConfig loggerConfig : config.getLoggers().values()) {
loggerConfig.addAppender(logAppender, null, null);
}
config.getRootLogger().addAppender(logAppender, null, null);
}
/**
* Apply the logging configuration.
*/
public void apply() {
LoggerContext context = getLoggerContext();
Configuration config = context.getConfiguration();
ConfigurationSource configSource = config.getConfigurationSource();
String packageHomeDir = WekaPackageManager.getPackageHome().getPath();
if (ConfigurationSource.NULL_SOURCE.equals(configSource)) {
// Use log4j2.xml shipped with the package ...
URI uri = Paths.get(packageHomeDir, "wekaDeeplearning4j", "src", "main", "resources",
"log4j2.xml").toUri();
context.setConfigLocation(uri);
log.info("Logging configuration loaded from source: {}", uri.toString());
}
String fileAppenderName = "fileAppender";
if (!context.getRootLogger().getAppenders().containsKey(fileAppenderName)) {
// Get console appender layout
Appender consoleAppender = context.getLogger(log.getName()).getAppenders().get("Console");
Layout<? extends Serializable> layout = consoleAppender.getLayout();
// Add file appender
String filePath = resolveLogFilePath();
FileAppender.Builder appenderBuilder = new FileAppender.Builder();
appenderBuilder.withFileName(filePath);
appenderBuilder.withAppend(append);
appenderBuilder.withName(fileAppenderName);
appenderBuilder.withLayout(layout);
FileAppender appender = appenderBuilder.build();
appender.start();
context.getRootLogger().addAppender(appender);
}
}
/**
* Creates console appender with some reasonable default logging settings.
*
* @return Logger with auto configured console appender.
*/
public Logger createConsoleLogger() {
// from http://logging.apache.org/log4j/2.x/manual/customconfig.html
final LoggerContext ctx = impl.getContext();
final Configuration cfg = ctx.getConfiguration();
PatternLayout.Builder builder = PatternLayout.newBuilder()
.withPattern("%d{ISO8601}][%-5p][%t][%c{1}] %m%n")
.withCharset(Charset.defaultCharset())
.withAlwaysWriteExceptions(false)
.withNoConsoleNoAnsi(false);
PatternLayout layout = builder.build();
ConsoleAppender.Builder consoleAppenderBuilder = ConsoleAppender.newBuilder()
.withName(CONSOLE_APPENDER)
.withLayout(layout);
ConsoleAppender consoleApp = consoleAppenderBuilder.build();
consoleApp.start();
cfg.addAppender(consoleApp);
cfg.getRootLogger().addAppender(consoleApp, Level.TRACE, null);
ctx.updateLoggers(cfg);
return ctx.getRootLogger();
}
public static Logger initializeDefaultLogger(Level level, Class<?> clazz) {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
final ConsoleAppender appender = ConsoleAppender.newBuilder().setName("Console").build();
config.addAppender(appender);
final AppenderRef ref = AppenderRef.createAppenderRef("Console", level, null);
final AppenderRef[] refs = new AppenderRef[] {ref};
final LoggerConfig loggerConfig =
LoggerConfig.createLogger(true, level, clazz.getName(), null, refs, null, config, null);
config.addLogger(clazz.getName(), loggerConfig);
ctx.updateLoggers();
return LogManager.getLogger(clazz);
}
public static synchronized void update(final LoggingConfiguration configuration) {
COLOR.set(configuration.isColorEnabled());
DESTINATION = configuration.getDestination();
INCLUDE_EVENTS = configuration.isIncludeEventsEnabled();
INCLUDE_VALIDATOR_DUTIES = configuration.isIncludeValidatorDutiesEnabled();
FILE = configuration.getFile();
FILE_PATTERN = configuration.getFileNamePattern();
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
addLoggers((AbstractConfiguration) ctx.getConfiguration());
ctx.updateLoggers();
}
/**
* Configures Logging in case it has not been configured via this method
* before.
*/
public static void configure() {
if (ALREADY_CONFIGURED.compareAndSet(false, true)) {
final File log4jFile = new File("log4j2.xml");
if (log4jFile.isFile()) {
LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.setConfigLocation(log4jFile.toURI());
} else {
final Logger logger = LogManager.getLogger(LoggingConfigurator.class);
logger.info("log4j configuration file ('" + log4jFile.getAbsolutePath() + "') not found.");
}
}
}