本文整理汇总了Java中org.apache.logging.log4j.core.LoggerContext.getLogger方法的典型用法代码示例。如果您正苦于以下问题:Java LoggerContext.getLogger方法的具体用法?Java LoggerContext.getLogger怎么用?Java LoggerContext.getLogger使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.logging.log4j.core.LoggerContext
的用法示例。
在下文中一共展示了LoggerContext.getLogger方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: start
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
@Setup
public void start() {
counter = 0;
if (log == null) {
System.setProperty(
"Log4jContextSelector",
"org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
LoggerContext context = LoggerContext.getContext();
log = context.getLogger("Log4j2");
log.setAdditive(false);
ArrayList<Appender> list = new ArrayList<Appender>();
list.addAll(log.getAppenders().values());
for (Appender a : list) {
log.removeAppender(a);
}
}
}
示例2: testNoNulCharacters
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
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());
}
示例3: getLogger
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
/**
* Gets the test logger and assign the appender to it
*
* @param appender the name of the appender
* @return the logger
*/
private Logger getLogger(String appender) {
final LoggerContext loggerContext = Configurator.initialize(getUniqueMarker(), CONFIG_LOCATION);
Logger logger = loggerContext.getLogger(appender);
logger.getAppenders().clear();
logger.addAppender(loggerContext.getConfiguration().getAppenders().get(appender));
return logger;
}
示例4: delete
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
private LoggerTO delete(final String name, final LoggerType expectedType) {
Logger syncopeLogger = loggerDAO.find(name);
if (syncopeLogger == null) {
throw new NotFoundException("Logger " + name);
}
if (expectedType != syncopeLogger.getType()) {
throwInvalidLogger(expectedType);
}
LoggerTO loggerToDelete = new LoggerTO();
BeanUtils.copyProperties(syncopeLogger, loggerToDelete);
// remove SyncopeLogger from local storage, so that LoggerLoader won't load this next time
loggerDAO.delete(syncopeLogger);
// set log level to OFF in order to disable configured logger until next reboot
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
String auditLoggerName = AuditLoggerName.getAuditEventLoggerName(
AuthContextUtils.getDomain(), syncopeLogger.getKey());
org.apache.logging.log4j.core.Logger logger = SyncopeConstants.ROOT_LOGGER.equals(name)
? ctx.getLogger(LogManager.ROOT_LOGGER_NAME)
: LoggerType.AUDIT.equals(syncopeLogger.getType())
? ctx.getLogger(auditLoggerName)
: ctx.getLogger(name);
logger.setLevel(Level.OFF);
ctx.updateLoggers();
return loggerToDelete;
}
示例5: testMissingRootLogger
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
@Test
public void testMissingRootLogger() throws Exception {
final LoggerContext ctx = context.getLoggerContext();
final Logger logger = ctx.getLogger("sample.Logger1");
assertTrue("Logger should have the INFO level enabled", logger.isInfoEnabled());
assertFalse("Logger should have the DEBUG level disabled", logger.isDebugEnabled());
final Configuration config = ctx.getConfiguration();
assertNotNull("Config not null", config);
// final String MISSINGROOT = "MissingRootTest";
// assertTrue("Incorrect Configuration. Expected " + MISSINGROOT + " but found " + config.getName(),
// MISSINGROOT.equals(config.getName()));
final Map<String, Appender> map = config.getAppenders();
assertNotNull("Appenders not null", map);
assertThat("There should only be two appenders", map, hasSize(2));
assertThat(map, hasKey("List"));
assertThat(map, hasKey("DefaultConsole-2"));
final Map<String, LoggerConfig> loggerMap = config.getLoggers();
assertNotNull("loggerMap not null", loggerMap);
assertThat("There should only be one configured logger", loggerMap, hasSize(1));
// only the sample logger, no root logger in loggerMap!
assertThat("contains key=sample", loggerMap, hasKey("sample"));
final LoggerConfig sample = loggerMap.get("sample");
final Map<String, Appender> sampleAppenders = sample.getAppenders();
assertThat("The sample logger should only have one appender", sampleAppenders, hasSize(1));
// sample only has List appender, not Console!
assertThat("The sample appender should be a ListAppender", sampleAppenders, hasKey("List"));
assertThat(config, is(instanceOf(AbstractConfiguration.class)));
final AbstractConfiguration baseConfig = (AbstractConfiguration) config;
final LoggerConfig root = baseConfig.getRootLogger();
final Map<String, Appender> rootAppenders = root.getAppenders();
assertThat("The root logger should only have one appender", rootAppenders, hasSize(1));
// root only has Console appender!
assertThat("The root appender should be a ConsoleAppender", rootAppenders, hasKey("DefaultConsole-2"));
assertEquals(Level.ERROR, root.getLevel());
}
示例6: shutdownTest
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
@Test(timeout = 5000)
public void shutdownTest() throws Exception {
final LoggerContext ctx = (LoggerContext)LogManager.getContext(false);
final Logger logger = ctx.getLogger("Logger");
logger.info("This is a test");
ctx.stop();
}
示例7: configure
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
/**
* {@inheritDoc}
* @see com.heliosapm.streams.tracing.AbstractMetricWriter#configure(java.util.Properties)
*/
@Override
public void configure(final Properties config) {
super.configure(config);
final String loggerName = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_LOGGER_NAME, null, config);
if(loggerName==null || !LogManager.getContext(true).hasLogger(loggerName)) {
/*
* ===================================================
* FIXME: this is super ugly
* ===================================================
* TODO:
* - log4j2 async appender
* - low gc message objects
*/
final String entryPrefix = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_ENTRY_PREFIX, DEFAULT_ENTRY_PREFIX, config);
this.config.put("entryPrefix", entryPrefix);
final String entrySuffix = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_ENTRY_SUFFIX, DEFAULT_ENTRY_SUFFIX, config);
this.config.put("entrySuffix", entrySuffix);
final boolean randomAccessFile = ConfigurationHelper.getBooleanSystemThenEnvProperty(CONFIG_RA_FILE, DEFAULT_RA_FILE, config);
this.config.put("randomAccessFile", randomAccessFile);
final String fileName = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_FILE_NAME, DEFAULT_FILE_NAME, config);
this.config.put("fileName", fileName);
final File file = new File(fileName);
final File dir = file.getParentFile();
if(dir.exists()) {
if(!dir.isDirectory()) throw new IllegalArgumentException("The logging directory is a file [" + dir + "]");
} else {
if(!dir.mkdirs()) throw new IllegalArgumentException("Cannot create the logging directory [" + dir + "]");
}
LoggerContext context= (LoggerContext) LogManager.getContext();
Configuration loggingConfig = context.getConfiguration();
PatternLayout layout= PatternLayout.createLayout(entryPrefix + "%m" + entrySuffix + "%n" , null, loggingConfig, null, UTF8, false, false, null, null);
final DefaultRolloverStrategy strategy = DefaultRolloverStrategy.createStrategy("10", "1", null, null, null, true, loggingConfig);
// final int lastIndex = fileName.lastIndexOf('.');
final String format = ConfigurationHelper.getSystemThenEnvProperty(CONFIG_ROLL_PATTERN, DEFAULT_ROLL_PATTERN, config);
this.config.put("format", format);
final StringBuilder b = new StringBuilder(fileName).append(format);
// if(lastIndex==-1) {
// b.append(".").append(format);
// } else {
// b.insert(lastIndex, format);
// }
final String rolledFileFormat = b.toString();
final TriggeringPolicy trigger = TimeBasedTriggeringPolicy.createPolicy("1", "true");
if(randomAccessFile) {
appender = createRollingRandomAccessFileAppender(fileName, loggingConfig, layout, strategy, rolledFileFormat, trigger);
} else {
appender = createRollingFileAppender(fileName, loggingConfig, layout, strategy, rolledFileFormat, trigger);
}
loggingConfig.addAppender(appender);
AppenderRef ref = AppenderRef.createAppenderRef(getClass().getSimpleName(), Level.INFO, null);
AppenderRef[] refs = new AppenderRef[] { ref };
LoggerConfig loggerConfig = LoggerConfig.createLogger(
false,
Level.INFO,
getClass().getSimpleName() + "Logger",
"false", refs, null, loggingConfig, null);
loggerConfig.addAppender(appender, Level.INFO, null);
loggingConfig.addLogger(getClass().getSimpleName() + "Logger", loggerConfig);
context.updateLoggers();
org.apache.logging.log4j.core.Logger xlogger = context.getLogger(getClass().getName() + "Logger");
for(Appender app: xlogger.getAppenders().values()) {
xlogger.removeAppender(app);
}
xlogger.addAppender(appender);
metricLog = context.getLogger(getClass().getName() + "Logger");
} else {
metricLog = LogManager.getLogger(loggerName);
}
}
示例8: testDelivery
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
@Test
public void testDelivery() {
final SMTPAppender appender = SMTPAppender.createAppender("Test",
"[email protected]", "[email protected]", "[email protected]",
"[email protected]", "[email protected]", "Subject", null,
HOST, PORT, null, null, "false", "3", null, null, "true");
appender.start();
final LoggerContext context = (LoggerContext) LogManager.getContext();
final Logger root = context.getLogger("SMTPAppenderTest");
root.addAppender(appender);
root.setAdditive(false);
root.setLevel(Level.DEBUG);
final SimpleSmtpServer server = SimpleSmtpServer.start(PORTNUM);
root.debug("Debug message #1");
root.debug("Debug message #2");
root.debug("Debug message #3");
root.debug("Debug message #4");
root.error("Error with exception", new RuntimeException(
"Exception message"));
root.error("Error message #2");
server.stop();
assertTrue(server.getReceivedEmailSize() == 2);
final Iterator<SmtpMessage> messages = server.getReceivedEmail();
final SmtpMessage email = messages.next();
assertEquals("[email protected]", email.getHeaderValue("To"));
assertEquals("[email protected]", email.getHeaderValue("Cc"));
// assertEquals("[email protected]", email.getHeaderValue("Bcc")); // BCC
// can't be tested with Dumpster 1.6
assertEquals("[email protected]", email.getHeaderValue("From"));
assertEquals("[email protected]", email.getHeaderValue("Reply-To"));
assertEquals("Subject", email.getHeaderValue("Subject"));
final String body = email.getBody();
assertFalse(body.contains("Debug message #1"));
assertTrue(body.contains("Debug message #2"));
assertTrue(body.contains("Debug message #3"));
assertTrue(body.contains("Debug message #4"));
assertTrue(body.contains("Error with exception"));
assertTrue(body.contains("RuntimeException"));
assertTrue(body.contains("Exception message"));
assertFalse(body.contains("Error message #2"));
final SmtpMessage email2 = (SmtpMessage) messages.next();
final String body2 = email2.getBody();
assertFalse(body2.contains("Debug message #4"));
assertFalse(body2.contains("Error with exception"));
assertTrue(body2.contains("Error message #2"));
}
示例9: testDelivery
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
@Test
public void testDelivery() {
final String subjectKey = getClass().getName();
final String subjectValue = "SubjectValue1";
ThreadContext.put(subjectKey, subjectValue);
final SmtpAppender appender = SmtpAppender.createAppender(null, "Test", "[email protected]", "[email protected]",
"[email protected]", "[email protected]", "[email protected]", "Subject Pattern %X{" + subjectKey + "}",
null, HOST, PORT, null, null, "false", "3", null, null, "true");
appender.start();
final LoggerContext context = LoggerContext.getContext();
final Logger root = context.getLogger("SMTPAppenderTest");
root.addAppender(appender);
root.setAdditive(false);
root.setLevel(Level.DEBUG);
final SimpleSmtpServer server = SimpleSmtpServer.start(PORTNUM);
root.debug("Debug message #1");
root.debug("Debug message #2");
root.debug("Debug message #3");
root.debug("Debug message #4");
root.error("Error with exception", new RuntimeException("Exception message"));
root.error("Error message #2");
server.stop();
assertTrue(server.getReceivedEmailSize() == 2);
final Iterator<SmtpMessage> messages = server.getReceivedEmail();
final SmtpMessage email = messages.next();
assertEquals("[email protected]", email.getHeaderValue("To"));
assertEquals("[email protected]", email.getHeaderValue("Cc"));
// assertEquals("[email protected]", email.getHeaderValue("Bcc")); // BCC
// can't be tested with Dumpster 1.6
assertEquals("[email protected]", email.getHeaderValue("From"));
assertEquals("[email protected]", email.getHeaderValue("Reply-To"));
final String headerValue = email.getHeaderValue("Subject");
assertEquals(headerValue, "Subject Pattern " + subjectValue);
final String body = email.getBody();
assertFalse(body.contains("Debug message #1"));
assertTrue(body.contains("Debug message #2"));
assertTrue(body.contains("Debug message #3"));
assertTrue(body.contains("Debug message #4"));
assertTrue(body.contains("Error with exception"));
assertTrue(body.contains("RuntimeException"));
assertTrue(body.contains("Exception message"));
assertFalse(body.contains("Error message #2"));
final SmtpMessage email2 = messages.next();
final String body2 = email2.getBody();
assertFalse(body2.contains("Debug message #4"));
assertFalse(body2.contains("Error with exception"));
assertTrue(body2.contains("Error message #2"));
}
示例10: testConfig
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
@Test
public void testConfig() {
// don't bother using "error" since that's the default; try another level
final LoggerContext ctx = this.init.getLoggerContext();
ctx.reconfigure();
final Configuration config = ctx.getConfiguration();
assertThat(config, instanceOf(XmlConfiguration.class));
for (final StatusListener listener : StatusLogger.getLogger().getListeners()) {
if (listener instanceof StatusConsoleListener) {
assertSame(listener.getStatusLevel(), Level.INFO);
break;
}
}
final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
.withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
.withConfiguration(config)
.build();
// @formatter:off
final FileAppender appender = FileAppender.newBuilder()
.withFileName(LOG_FILE)
.withAppend(false)
.withName("File")
.withIgnoreExceptions(false)
.withBufferSize(4000)
.withBufferedIo(false)
.withLayout(layout)
.build();
// @formatter:on
appender.start();
config.addAppender(appender);
final AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
final AppenderRef[] refs = new AppenderRef[] {ref};
final LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "org.apache.logging.log4j",
"true", refs, null, config, null );
loggerConfig.addAppender(appender, null, null);
config.addLogger("org.apache.logging.log4j", loggerConfig);
ctx.updateLoggers();
final Logger logger = ctx.getLogger(CustomConfigurationTest.class.getName());
logger.info("This is a test");
final File file = new File(LOG_FILE);
assertThat(file, exists());
assertThat(file, hasLength(greaterThan(0L)));
}
示例11: Category
import org.apache.logging.log4j.core.LoggerContext; //导入方法依赖的package包/类
/**
* Constructor used by Logger to specify a LoggerContext.
* @param context The LoggerContext.
* @param name The name of the Logger.
*/
protected Category(final LoggerContext context, final String name) {
this.logger = context.getLogger(name);
}