下面列出了怎么用org.apache.logging.log4j.core.LifeCycle的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void contextDestroyed(final ServletContextEvent event) {
if (this.servletContext == null || this.initializer == null) {
LOGGER.warn("Context destroyed before it was initialized.");
return;
}
LOGGER.debug("Log4jServletContextListener ensuring that Log4j shuts down properly.");
this.initializer.clearLoggerContext(); // the application is finished
// shutting down now
final String stopTimeoutStr = servletContext.getInitParameter(KEY_STOP_TIMEOUT);
final long stopTimeout = Strings.isEmpty(stopTimeoutStr) ? DEFAULT_STOP_TIMEOUT
: Long.parseLong(stopTimeoutStr);
final String timeoutTimeUnitStr = servletContext.getInitParameter(KEY_STOP_TIMEOUT_TIMEUNIT);
final TimeUnit timeoutTimeUnit = Strings.isEmpty(timeoutTimeUnitStr) ? DEFAULT_STOP_TIMEOUT_TIMEUNIT
: TimeUnit.valueOf(timeoutTimeUnitStr.toUpperCase(Locale.ROOT));
((LifeCycle) this.initializer).stop(stopTimeout, timeoutTimeUnit);
}
/**
* Loads the LoggerContext using the ContextSelector.
* @param fqcn The fully qualified class name of the caller.
* @param loader The ClassLoader to use or null.
* @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext.
* @param currentContext If true returns the current Context, if false returns the Context appropriate
* for the caller if a more appropriate Context can be determined.
* @param source The configuration source.
* @return The LoggerContext.
*/
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
final boolean currentContext, final ConfigurationSource source) {
final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, null);
if (externalContext != null && ctx.getExternalContext() == null) {
ctx.setExternalContext(externalContext);
}
if (ctx.getState() == LifeCycle.State.INITIALIZED) {
if (source != null) {
ContextAnchor.THREAD_CONTEXT.set(ctx);
final Configuration config = ConfigurationFactory.getInstance().getConfiguration(ctx, source);
LOGGER.debug("Starting LoggerContext[name={}] from configuration {}", ctx.getName(), source);
ctx.start(config);
ContextAnchor.THREAD_CONTEXT.remove();
} else {
ctx.start();
}
}
return ctx;
}
/**
* Loads the LoggerContext using the ContextSelector using the provided Configuration
* @param fqcn The fully qualified class name of the caller.
* @param loader The ClassLoader to use or null.
* @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext.
* @param currentContext If true returns the current Context, if false returns the Context appropriate
* for the caller if a more appropriate Context can be determined.
* @param configuration The Configuration.
* @return The LoggerContext.
*/
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
final boolean currentContext, final Configuration configuration) {
final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, null);
if (externalContext != null && ctx.getExternalContext() == null) {
ctx.setExternalContext(externalContext);
}
if (ctx.getState() == LifeCycle.State.INITIALIZED) {
ContextAnchor.THREAD_CONTEXT.set(ctx);
try {
ctx.start(configuration);
} finally {
ContextAnchor.THREAD_CONTEXT.remove();
}
}
return ctx;
}
/**
* Loads the LoggerContext using the ContextSelector.
* @param fqcn The fully qualified class name of the caller.
* @param loader The ClassLoader to use or null.
* @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext.
* @param currentContext If true returns the current Context, if false returns the Context appropriate
* for the caller if a more appropriate Context can be determined.
* @param configLocation The location of the configuration for the LoggerContext (or null).
* @return The LoggerContext.
*/
@Override
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
final boolean currentContext, final URI configLocation, final String name) {
final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext, configLocation);
if (externalContext != null && ctx.getExternalContext() == null) {
ctx.setExternalContext(externalContext);
}
if (name != null) {
ctx.setName(name);
}
if (ctx.getState() == LifeCycle.State.INITIALIZED) {
if (configLocation != null || name != null) {
ContextAnchor.THREAD_CONTEXT.set(ctx);
final Configuration config = ConfigurationFactory.getInstance().getConfiguration(ctx, name, configLocation);
LOGGER.debug("Starting LoggerContext[name={}] from configuration at {}", ctx.getName(), configLocation);
ctx.start(config);
ContextAnchor.THREAD_CONTEXT.remove();
} else {
ctx.start();
}
}
return ctx;
}
public void initialize() {
if (!initialized) {
LOGGER.debug("Initializing triggering policy {}", triggeringPolicy);
initialized = true;
triggeringPolicy.initialize(this);
if (triggeringPolicy instanceof LifeCycle) {
((LifeCycle) triggeringPolicy).start();
}
if (directWrite) {
// LOG4J2-2485: Initialize size from the most recently written file.
File file = new File(getFileName());
if (file.exists()) {
size = file.length();
} else {
((DirectFileRolloverStrategy) rolloverStrategy).clearCurrentFileName();
}
}
}
}
public void setTriggeringPolicy(final TriggeringPolicy triggeringPolicy) {
triggeringPolicy.initialize(this);
final TriggeringPolicy policy = this.triggeringPolicy;
int count = 0;
boolean policyUpdated = false;
do {
++count;
} while (!(policyUpdated = triggeringPolicyUpdater.compareAndSet(this, this.triggeringPolicy, triggeringPolicy))
&& count < MAX_TRIES);
if (policyUpdated) {
if (triggeringPolicy instanceof LifeCycle) {
((LifeCycle) triggeringPolicy).start();
}
if (policy instanceof LifeCycle) {
((LifeCycle) policy).stop();
}
} else {
if (triggeringPolicy instanceof LifeCycle) {
((LifeCycle) triggeringPolicy).stop();
}
}
}
@Test
public void testPropertiesConfiguration() {
final Configuration config = context.getConfiguration();
assertNotNull("No configuration created", config);
assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
final Map<String, Appender> appenders = config.getAppenders();
assertNotNull(appenders);
assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
final Map<String, LoggerConfig> loggers = config.getLoggers();
assertNotNull(loggers);
assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
final Filter filter = config.getFilter();
assertNotNull("No Filter", filter);
assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
final Logger logger = LogManager.getLogger(getClass());
logger.info("Welcome to Log4j!");
}
@Test
public void testPropertiesConfiguration() {
final Configuration config = context.getConfiguration();
assertNotNull("No configuration created", config);
assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
final Map<String, Appender> appenders = config.getAppenders();
assertNotNull(appenders);
assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
final Map<String, LoggerConfig> loggers = config.getLoggers();
assertNotNull(loggers);
assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 1);
final Filter filter = config.getFilter();
assertNotNull("No Filter", filter);
assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
final Logger logger = LogManager.getLogger(getClass());
logger.info("Welcome to Log4j!");
}
@Test
public void testPropertiesConfiguration() {
final Configuration config = context.getConfiguration();
assertNotNull("No configuration created", config);
assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
final Map<String, Appender> appenders = config.getAppenders();
assertNotNull(appenders);
assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
final Map<String, LoggerConfig> loggers = config.getLoggers();
assertNotNull(loggers);
assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
final Filter filter = config.getFilter();
assertNotNull("No Filter", filter);
assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
final Logger logger = LogManager.getLogger(getClass());
assertEquals("Incorrect level " + logger.getLevel(), Level.DEBUG, logger.getLevel());
logger.debug("Welcome to Log4j!");
}
@Test
public void testPropertiesConfiguration() {
final Configuration config = context.getConfiguration();
assertNotNull("No configuration created", config);
assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
final Map<String, Appender> appenders = config.getAppenders();
assertNotNull(appenders);
assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 3);
final Map<String, LoggerConfig> loggers = config.getLoggers();
assertNotNull(loggers);
assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
final Filter filter = config.getFilter();
assertNotNull("No Filter", filter);
assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
final Logger logger = LogManager.getLogger(getClass());
logger.info("Welcome to Log4j!");
}
@Override
public void onApplicationEvent(final ContextClosedEvent event) {
logger.info("Gracefully shutting down application.");
manager.stop();
manager.tearDown();
logger.info("JOAL gracefully shut down.");
// Since we disabled log4j2 shutdown hook, we need to handle it manually.
final LifeCycle loggerContext = (LoggerContext) LogManager.getContext(false);
loggerContext.stop();
}
private void validate(final Configuration config) {
assertNotNull(config);
assertNotNull(config.getName());
assertFalse(config.getName().isEmpty());
assertNotNull(config, "No configuration created");
assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
final Map<String, Appender> appenders = config.getAppenders();
assertNotNull(appenders);
assertEquals("Incorrect number of Appenders: " + appenders.size(), appenders.size(), 2);
final PulsarAppender pulsarAppender = (PulsarAppender) appenders.get("Pulsar");
final GelfLayout gelfLayout = (GelfLayout) pulsarAppender.getLayout();
final Map<String, LoggerConfig> loggers = config.getLoggers();
assertNotNull(loggers);
assertEquals("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size(), 2);
final LoggerConfig rootLoggerConfig = loggers.get("");
assertEquals(Level.ERROR, rootLoggerConfig.getLevel());
assertFalse(rootLoggerConfig.isIncludeLocation());
final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j");
assertEquals(Level.DEBUG, loggerConfig.getLevel());
assertTrue(loggerConfig.isIncludeLocation());
final Filter filter = config.getFilter();
assertNotNull(filter, "No Filter");
assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
final List<CustomLevelConfig> customLevels = config.getCustomLevels();
assertNotNull(filter, "No CustomLevels");
assertEquals(1, customLevels.size());
final CustomLevelConfig customLevel = customLevels.get(0);
assertEquals("Panic", customLevel.getLevelName());
assertEquals(17, customLevel.getIntLevel());
final Logger logger = LogManager.getLogger(getClass());
logger.info("Welcome to Log4j!");
}
/**
* Perform whatever cleanup is required of the underlying object..
*/
@Override
public void close()
{
LifeCycle lc = ((LifeCycle)LogManager.getContext());
if (lc.isStarted())
{
lc.stop();
}
}
@Test
public void testCleanup() throws Exception {
Log4jLoggerFactory factory = (Log4jLoggerFactory) LoggerFactory.getILoggerFactory();
factory.getLogger("test");
Set<LoggerContext> set = factory.getLoggerContexts();
LoggerContext ctx1 = set.toArray(new LoggerContext[0])[0];
assertTrue("LoggerContext is not enabled for shutdown", ctx1 instanceof LifeCycle);
((LifeCycle) ctx1).stop();
set = factory.getLoggerContexts();
assertTrue("Expected no LoggerContexts", set.isEmpty());
}
private void validate(final Configuration config) {
assertNotNull(config);
assertNotNull(config.getName());
assertFalse(config.getName().isEmpty());
assertNotNull("No configuration created", config);
assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
final Map<String, Appender> appenders = config.getAppenders();
assertNotNull(appenders);
assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 2);
final KafkaAppender kafkaAppender = (KafkaAppender) appenders.get("Kafka");
final GelfLayout gelfLayout = (GelfLayout) kafkaAppender.getLayout();
final Map<String, LoggerConfig> loggers = config.getLoggers();
assertNotNull(loggers);
assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
final LoggerConfig rootLoggerConfig = loggers.get("");
assertEquals(Level.ERROR, rootLoggerConfig.getLevel());
assertFalse(rootLoggerConfig.isIncludeLocation());
final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j");
assertEquals(Level.DEBUG, loggerConfig.getLevel());
assertTrue(loggerConfig.isIncludeLocation());
final Filter filter = config.getFilter();
assertNotNull("No Filter", filter);
assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
final List<CustomLevelConfig> customLevels = config.getCustomLevels();
assertNotNull("No CustomLevels", filter);
assertEquals(1, customLevels.size());
final CustomLevelConfig customLevel = customLevels.get(0);
assertEquals("Panic", customLevel.getLevelName());
assertEquals(17, customLevel.getIntLevel());
final Logger logger = LogManager.getLogger(getClass());
logger.info("Welcome to Log4j!");
}
@Test
public void testCleanup() throws Exception {
Log4jLoggerFactory factory = (Log4jLoggerFactory) StaticLoggerBinder.getSingleton().getLoggerFactory();
factory.getLogger("test");
Set<LoggerContext> set = factory.getLoggerContexts();
LoggerContext ctx1 = set.toArray(new LoggerContext[0])[0];
assertTrue("LoggerContext is not enabled for shutdown", ctx1 instanceof LifeCycle);
((LifeCycle) ctx1).stop();
set = factory.getLoggerContexts();
assertTrue("Expected no LoggerContexts", set.isEmpty());
}
/**
* Loads the LoggerContext using the ContextSelector.
* @param fqcn The fully qualified class name of the caller.
* @param loader The ClassLoader to use or null.
* @param currentContext If true returns the current Context, if false returns the Context appropriate
* for the caller if a more appropriate Context can be determined.
* @param externalContext An external context (such as a ServletContext) to be associated with the LoggerContext.
* @return The LoggerContext.
*/
@Override
public LoggerContext getContext(final String fqcn, final ClassLoader loader, final Object externalContext,
final boolean currentContext) {
final LoggerContext ctx = selector.getContext(fqcn, loader, currentContext);
if (externalContext != null && ctx.getExternalContext() == null) {
ctx.setExternalContext(externalContext);
}
if (ctx.getState() == LifeCycle.State.INITIALIZED) {
ctx.start();
}
return ctx;
}
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 boolean stop(final long timeout, final TimeUnit timeUnit) {
setStopping();
boolean stopped = true;
for (final TriggeringPolicy triggeringPolicy : triggeringPolicies) {
stopped &= ((LifeCycle) triggeringPolicy).stop(timeout, timeUnit);
}
setStopped();
return stopped;
}
@Override
public boolean stop(final long timeout, final TimeUnit timeUnit) {
this.setStopping();
for (final Filter filter : filters) {
((LifeCycle) filter).stop(timeout, timeUnit);
}
setStopped();
return true;
}
/**
* Cleanup the Filter.
*/
protected boolean stop(final long timeout, final TimeUnit timeUnit, final boolean changeLifeCycleState) {
if (changeLifeCycleState) {
this.setStopping();
}
boolean stopped = true;
if (filter != null) {
stopped = ((LifeCycle) filter).stop(timeout, timeUnit);
}
if (changeLifeCycleState) {
this.setStopped();
}
return stopped;
}
private void validate(final Configuration config) {
assertNotNull(config);
assertNotNull(config.getName());
assertFalse(config.getName().isEmpty());
assertNotNull("No configuration created", config);
assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
final Map<String, Appender> appenders = config.getAppenders();
assertNotNull(appenders);
assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
final ConsoleAppender consoleAppender = (ConsoleAppender)appenders.get("Stdout");
final PatternLayout gelfLayout = (PatternLayout)consoleAppender.getLayout();
final Map<String, LoggerConfig> loggers = config.getLoggers();
assertNotNull(loggers);
assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
final LoggerConfig rootLoggerConfig = loggers.get("");
assertEquals(Level.ERROR, rootLoggerConfig.getLevel());
assertFalse(rootLoggerConfig.isIncludeLocation());
final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j");
assertEquals(Level.DEBUG, loggerConfig.getLevel());
assertTrue(loggerConfig.isIncludeLocation());
final Filter filter = config.getFilter();
assertNotNull("No Filter", filter);
assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
final List<CustomLevelConfig> customLevels = config.getCustomLevels();
assertNotNull("No CustomLevels", filter);
assertEquals(1, customLevels.size());
final CustomLevelConfig customLevel = customLevels.get(0);
assertEquals("Panic", customLevel.getLevelName());
assertEquals(17, customLevel.getIntLevel());
final Logger logger = LogManager.getLogger(getClass());
logger.info("Welcome to Log4j!");
}
public final void createLoggerProgrammatically(Supplier<ElasticsearchAppender.Builder> appenderBuilder, Function<Configuration, AsyncLoggerConfigDelegate> delegateSupplier) {
LoggerContext ctx = LoggerContext.getContext(false);
final Configuration config = ctx.getConfiguration();
Appender appender = appenderBuilder.get().build();
appender.start();
AppenderRef ref = AppenderRef.createAppenderRef(DEFAULT_APPENDER_NAME, Level.INFO, null);
AppenderRef[] refs = new AppenderRef[] {ref};
// set up disruptor forcefully
((LifeCycle)delegateSupplier.apply(config)).start();
AsyncLoggerConfig loggerConfig = (AsyncLoggerConfig) AsyncLoggerConfig.createLogger(false, Level.INFO, DEFAULT_LOGGER_NAME,
"false", refs, null, config, null );
loggerConfig.addAppender(appender, Level.INFO, null);
config.addAppender(appender);
config.addLogger(DEFAULT_LOGGER_NAME, loggerConfig);
}
@Test
public void lifecycleStart() {
// given
LifeCycle lifeCycle = createLifeCycleTestObject();
assertFalse(lifeCycle.isStarted());
// when
lifeCycle.start();
// then
assertFalse(lifeCycle.isStopped());
assertTrue(lifeCycle.isStarted());
}
@Test
public void lifecycleStop() {
// given
LifeCycle lifeCycle = createLifeCycleTestObject();
assertFalse(lifeCycle.isStarted());
lifeCycle.start();
assertTrue(lifeCycle.isStarted());
// when
lifeCycle.stop();
// then
assertFalse(lifeCycle.isStarted());
assertTrue(lifeCycle.isStopped());
}
private LifeCycle createLifeCycleTestObject() {
return createTestElasticsearchAppenderBuilder(JacksonJsonLayout.newBuilder()
.setConfiguration(LoggerContext.getContext(false).getConfiguration())
.build()).build();
}
@TearDown(Level.Trial)
public void down() {
((LifeCycle) LogManager.getContext(false)).stop();
new File("perftest.log").delete();
}
@TearDown(Level.Trial)
public void down() {
((LifeCycle) LogManager.getContext(false)).stop();
new File("perftest.log").delete();
}
@TearDown(Level.Trial)
public void down() {
((LifeCycle) LogManager.getContext(false)).stop();
new File("perftest.log").delete();
}
@TearDown
public final void after() {
((LifeCycle) LogManager.getContext(false)).stop();
new File("target/ConcurrentAsyncLoggerToFileBenchmark.log").delete();
logger = null;
}