Java Code Examples for org.apache.logging.log4j.core.config.Configuration#getAppender()

The following examples show how to use org.apache.logging.log4j.core.config.Configuration#getAppender() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void testDailyRollingFileAppender(final String configResource, final String name, final String filePattern) throws URISyntaxException {
	final Configuration configuration = getConfiguration(configResource);
	final Appender appender = configuration.getAppender(name);
	assertNotNull(appender);
	assertEquals(name, appender.getName());
	assertTrue(appender.getClass().getName(), appender instanceof RollingFileAppender);
	final RollingFileAppender rfa = (RollingFileAppender) appender;
	assertEquals("target/hadoop.log", rfa.getFileName());
	assertEquals(filePattern, rfa.getFilePattern());
	final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy();
	assertNotNull(triggeringPolicy);
	assertTrue(triggeringPolicy.getClass().getName(), triggeringPolicy instanceof CompositeTriggeringPolicy);
	final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy;
	final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies();
	assertEquals(1, triggeringPolicies.length);
	final TriggeringPolicy tp = triggeringPolicies[0];
	assertTrue(tp.getClass().getName(), tp instanceof TimeBasedTriggeringPolicy);
	final TimeBasedTriggeringPolicy tbtp = (TimeBasedTriggeringPolicy) tp;
	assertEquals(1, tbtp.getInterval());
	final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy();
	assertTrue(rolloverStrategy.getClass().getName(), rolloverStrategy instanceof DefaultRolloverStrategy);
	final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy;
	assertEquals(Integer.MAX_VALUE, drs.getMaxIndex());
	configuration.start();
	configuration.stop();
}
 
Example 2
Source File: CustomLevelsWithFiltersTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfiguration() {
    final Configuration configuration = context.getConfiguration();
    assertNotNull(configuration);
    final FileAppender appender = configuration.getAppender("info");
    assertNotNull(appender);
    final CompositeFilter compFilter = (CompositeFilter) appender.getFilter();
    assertNotNull(compFilter);
    final Filter[] filters = compFilter.getFiltersArray();
    assertNotNull(filters);
    boolean foundLevel = false;
    for (final Filter filter : filters) {
        final ThresholdFilter tFilter = (ThresholdFilter) filter;
        if (infom1Level.equals(tFilter.getLevel())) {
            foundLevel = true;
            break;
        }
    }
    Assert.assertTrue("Level not found: " + infom1Level, foundLevel);
}
 
Example 3
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void testDailyRollingFileAppender(final String configResource, final String name, final String filePattern) throws URISyntaxException {
	final Configuration configuration = getConfiguration(configResource);
	final Appender appender = configuration.getAppender(name);
	assertNotNull(appender);
	assertEquals(name, appender.getName());
	assertTrue(appender.getClass().getName(), appender instanceof RollingFileAppender);
	final RollingFileAppender rfa = (RollingFileAppender) appender;
	assertEquals("target/hadoop.log", rfa.getFileName());
	assertEquals(filePattern, rfa.getFilePattern());
	final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy();
	assertNotNull(triggeringPolicy);
	assertTrue(triggeringPolicy.getClass().getName(), triggeringPolicy instanceof CompositeTriggeringPolicy);
	final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy;
	final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies();
	assertEquals(1, triggeringPolicies.length);
	final TriggeringPolicy tp = triggeringPolicies[0];
	assertTrue(tp.getClass().getName(), tp instanceof TimeBasedTriggeringPolicy);
	final TimeBasedTriggeringPolicy tbtp = (TimeBasedTriggeringPolicy) tp;
	assertEquals(1, tbtp.getInterval());
	final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy();
	assertTrue(rolloverStrategy.getClass().getName(), rolloverStrategy instanceof DefaultRolloverStrategy);
	final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy;
	assertEquals(Integer.MAX_VALUE, drs.getMaxIndex());
	configuration.start();
	configuration.stop();
}
 
Example 4
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void testRollingFileAppender(final String configResource, final String name, final String filePattern) throws URISyntaxException {
	final Configuration configuration = getConfiguration(configResource);
	final Appender appender = configuration.getAppender(name);
	assertNotNull(appender);
	assertEquals(name, appender.getName());
	assertTrue(appender.getClass().getName(), appender instanceof RollingFileAppender);
	final RollingFileAppender rfa = (RollingFileAppender) appender;
	assertEquals("target/hadoop.log", rfa.getFileName());
	assertEquals(filePattern, rfa.getFilePattern());
	final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy();
	assertNotNull(triggeringPolicy);
	assertTrue(triggeringPolicy.getClass().getName(), triggeringPolicy instanceof CompositeTriggeringPolicy);
	final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy;
	final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies();
	assertEquals(1, triggeringPolicies.length);
	final TriggeringPolicy tp = triggeringPolicies[0];
	assertTrue(tp.getClass().getName(), tp instanceof SizeBasedTriggeringPolicy);
	final SizeBasedTriggeringPolicy sbtp = (SizeBasedTriggeringPolicy) tp;
	assertEquals(256 * 1024 * 1024, sbtp.getMaxFileSize());
	final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy();
	assertTrue(rolloverStrategy.getClass().getName(), rolloverStrategy instanceof DefaultRolloverStrategy);
	final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy;
	assertEquals(20, drs.getMaxIndex());
	configuration.start();
	configuration.stop();
}
 
Example 5
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSystemProperties1() throws Exception {
       final String tempFileName = System.getProperty("java.io.tmpdir") + "/hadoop.log";
       final Path tempFilePath = new File(tempFileName).toPath();
       Files.deleteIfExists(tempFilePath);
       try {
           final Configuration configuration = getConfiguration("config-1.2/log4j-system-properties-1.properties");
           final RollingFileAppender appender = configuration.getAppender("RFA");
		appender.stop(10, TimeUnit.SECONDS);
           // System.out.println("expected: " + tempFileName + " Actual: " + appender.getFileName());
           assertEquals(tempFileName, appender.getFileName());
       } finally {
		try {
			Files.deleteIfExists(tempFilePath);
		} catch (final FileSystemException e) {
			e.printStackTrace();
		}
       }
}
 
Example 6
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void testRollingFileAppender(final String configResource, final String name, final String filePattern) throws URISyntaxException {
	final Configuration configuration = getConfiguration(configResource);
	final Appender appender = configuration.getAppender(name);
	assertNotNull(appender);
	assertEquals(name, appender.getName());
	assertTrue(appender.getClass().getName(), appender instanceof RollingFileAppender);
	final RollingFileAppender rfa = (RollingFileAppender) appender;
	assertEquals("target/hadoop.log", rfa.getFileName());
	assertEquals(filePattern, rfa.getFilePattern());
	final TriggeringPolicy triggeringPolicy = rfa.getTriggeringPolicy();
	assertNotNull(triggeringPolicy);
	assertTrue(triggeringPolicy.getClass().getName(), triggeringPolicy instanceof CompositeTriggeringPolicy);
	final CompositeTriggeringPolicy ctp = (CompositeTriggeringPolicy) triggeringPolicy;
	final TriggeringPolicy[] triggeringPolicies = ctp.getTriggeringPolicies();
	assertEquals(1, triggeringPolicies.length);
	final TriggeringPolicy tp = triggeringPolicies[0];
	assertTrue(tp.getClass().getName(), tp instanceof SizeBasedTriggeringPolicy);
	final SizeBasedTriggeringPolicy sbtp = (SizeBasedTriggeringPolicy) tp;
	assertEquals(256 * 1024 * 1024, sbtp.getMaxFileSize());
	final RolloverStrategy rolloverStrategy = rfa.getManager().getRolloverStrategy();
	assertTrue(rolloverStrategy.getClass().getName(), rolloverStrategy instanceof DefaultRolloverStrategy);
	final DefaultRolloverStrategy drs = (DefaultRolloverStrategy) rolloverStrategy;
	assertEquals(20, drs.getMaxIndex());
	configuration.start();
	configuration.stop();
}
 
Example 7
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSystemProperties1() throws Exception {
       final String tempFileName = System.getProperty("java.io.tmpdir") + "/hadoop.log";
       final Path tempFilePath = new File(tempFileName).toPath();
       Files.deleteIfExists(tempFilePath);
       try {
           final Configuration configuration = getConfiguration("config-1.2/log4j-system-properties-1.properties");
           final RollingFileAppender appender = configuration.getAppender("RFA");
		appender.stop(10, TimeUnit.SECONDS);
           System.out.println("expected: " + tempFileName + " Actual: " + appender.getFileName());
           assertEquals(tempFileName, appender.getFileName());
       } finally {
		try {
			Files.deleteIfExists(tempFilePath);
		} catch (final FileSystemException e) {
			e.printStackTrace();
		}
       }
}
 
Example 8
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSystemProperties2() throws Exception {
	final Configuration configuration = getConfiguration("config-1.2/log4j-system-properties-2.properties");
	final RollingFileAppender appender = configuration.getAppender("RFA");
	assertEquals("${java.io.tmpdir}/hadoop.log", appender.getFileName());
	appender.stop(10, TimeUnit.SECONDS);
	Path path = new File(appender.getFileName()).toPath();
       Files.deleteIfExists(path);
       path = new File("${java.io.tmpdir}").toPath();
       Files.deleteIfExists(path);
}
 
Example 9
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullAppender() throws Exception {
	final Configuration configuration = getConfiguration("config-1.2/log4j-NullAppender.properties");
	final Appender appender = configuration.getAppender("NullAppender");
	assertNotNull(appender);
	assertEquals("NullAppender", appender.getName());
	assertTrue(appender.getClass().getName(), appender instanceof NullAppender);
}
 
Example 10
Source File: LogPanel.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 11
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout<?> testConsole(final String configResource) throws Exception {
    final Configuration configuration = getConfiguration(configResource);
    final String name = "Console";
    final ConsoleAppender appender = configuration.getAppender(name);
    assertNotNull("Missing appender '" + name + "' in configuration " + configResource + " → " + configuration,
            appender);
    assertEquals(Target.SYSTEM_ERR, appender.getTarget());
    //
    final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
    assertNotNull(loggerConfig);
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    configuration.start();
    configuration.stop();
    return appender.getLayout();
}
 
Example 12
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout<?> testFile(final String configResource) throws Exception {
	final Configuration configuration = getConfiguration(configResource);
	final FileAppender appender = configuration.getAppender("File");
	assertNotNull(appender);
	assertEquals("target/mylog.txt", appender.getFileName());
	//
	final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
	assertNotNull(loggerConfig);
	assertEquals(Level.DEBUG, loggerConfig.getLevel());
	configuration.start();
	configuration.stop();
	return appender.getLayout();
}
 
Example 13
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullAppender() throws Exception {
	final Configuration configuration = getConfiguration("config-1.2/log4j-NullAppender.properties");
	final Appender appender = configuration.getAppender("NullAppender");
	assertNotNull(appender);
	assertEquals("NullAppender", appender.getName());
	assertTrue(appender.getClass().getName(), appender instanceof NullAppender);
}
 
Example 14
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout<?> testFile(final String configResource) throws Exception {
	final Configuration configuration = getConfiguration(configResource);
	final FileAppender appender = configuration.getAppender("File");
	assertNotNull(appender);
	assertEquals("target/mylog.txt", appender.getFileName());
	//
	final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
	assertNotNull(loggerConfig);
	assertEquals(Level.DEBUG, loggerConfig.getLevel());
	configuration.start();
	configuration.stop();
	return appender.getLayout();
}
 
Example 15
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSystemProperties2() throws Exception {
	final Configuration configuration = getConfiguration("config-1.2/log4j-system-properties-2.properties");
	final RollingFileAppender appender = configuration.getAppender("RFA");
	assertEquals("${java.io.tmpdir}/hadoop.log", appender.getFileName());
	appender.stop(10, TimeUnit.SECONDS);
	Path path = new File(appender.getFileName()).toPath();
       Files.deleteIfExists(path);
       path = new File("${java.io.tmpdir}").toPath();
       Files.deleteIfExists(path);
}
 
Example 16
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout<?> testConsole(final String configResource) throws Exception {
    final Configuration configuration = getConfiguration(configResource);
    final String name = "Console";
    final ConsoleAppender appender = configuration.getAppender(name);
    assertNotNull("Missing appender '" + name + "' in configuration " + configResource + " → " + configuration,
            appender);
    assertEquals(Target.SYSTEM_ERR, appender.getTarget());
    //
    final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
    assertNotNull(loggerConfig);
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    configuration.start();
    configuration.stop();
    return appender.getLayout();
}
 
Example 17
Source File: MapAppenderIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenLoggerEmitsLoggingEvent_thenAppenderReceivesEvent() throws Exception {
    logger.error("Error log message from {}", this.getClass()
        .getSimpleName());
    LoggerContext context = LoggerContext.getContext(false);
    Configuration config = context.getConfiguration();
    MapAppender appender = config.getAppender("MapAppender");
    assertEquals(appender.getEventMap()
        .size(), 1);
}
 
Example 18
Source File: ServletAppenderTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAppender() throws Exception {
    ContextAnchor.THREAD_CONTEXT.remove();
    final ServletContext servletContext = new MockServletContext();
    servletContext.setAttribute("TestAttr", "AttrValue");
    servletContext.setInitParameter("TestParam", "ParamValue");
    servletContext.setAttribute("Name1", "Ben");
    servletContext.setInitParameter("Name2", "Jerry");
    servletContext.setInitParameter(Log4jWebSupport.LOG4J_CONFIG_LOCATION, CONFIG);
    final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext);
    try {
        initializer.start();
        initializer.setLoggerContext();
        final LoggerContext ctx = ContextAnchor.THREAD_CONTEXT.get();
        assertNotNull("No LoggerContext", ctx);
        assertNotNull("No ServletContext", ctx.getExternalContext());
        final Configuration configuration = ctx.getConfiguration();
        assertNotNull("No configuration", configuration);
        final Appender appender = configuration.getAppender("Servlet");
        assertNotNull("No ServletAppender", appender);
        final Logger logger = LogManager.getLogger("Test");
        logger.info("This is a test");
        logger.error("This is a test 2", new IllegalStateException().fillInStackTrace());
    } catch (final IllegalStateException e) {
        fail("Failed to initialize Log4j properly." + e.getMessage());
    } finally {
        initializer.stop();
        ContextAnchor.THREAD_CONTEXT.remove();
    }
}
 
Example 19
Source File: ApsSystemUtils.java    From entando-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void init() throws Exception {
    String active = (String) this.systemParams.get(INIT_PROP_LOG_ACTIVE_FILE_OUTPUT);
    if (StringUtils.isEmpty(active) || !active.equalsIgnoreCase("true")) {
        return;
    }
    String appenderName = "ENTANDO";
    String conversionPattern = (String) this.systemParams.get("log4jConversionPattern");
    if (StringUtils.isBlank(conversionPattern)) {
        conversionPattern = "%d{yyyy-MM-dd HH:mm:ss.SSS} - %-5p -  %c - %m%n";
    }
    String maxFileSize = (String) this.systemParams.get(INIT_PROP_LOG_FILE_SIZE);
    if (StringUtils.isBlank(maxFileSize)) {
        maxFileSize = "1MB"; //default size
    } else {
        long mega = new Long(maxFileSize) / KILOBYTE;
        maxFileSize = mega + "KB";
    }
    String filePattern = (String) this.systemParams.get(INIT_PROP_LOG_FILE_PATTERN);
    String filename = (String) this.systemParams.get(INIT_PROP_LOG_NAME);
    int maxBackupIndex = Integer.parseInt((String) this.systemParams.get(INIT_PROP_LOG_FILES_COUNT));
    String log4jLevelString = (String) this.systemParams.get(INIT_PROP_LOG_LEVEL);
    if (StringUtils.isBlank(log4jLevelString)) {
        log4jLevelString = "INFO"; //default level
    }
    Configurator.setRootLevel(Level.getLevel(log4jLevelString));
    LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    loggerContext.getRootLogger().setLevel(Level.getLevel(log4jLevelString));
    Configurator.setAllLevels(loggerContext.getRootLogger().getName(), Level.getLevel(log4jLevelString));
    Configuration configuration = loggerContext.getConfiguration();
    RollingFileAppender fileAppender = (RollingFileAppender) configuration.getAppender(appenderName);
    if (null == fileAppender) {
        PathCondition[] pathConditions = new PathCondition[]{IfAccumulatedFileCount.createFileCountCondition(maxBackupIndex)};
        String basePath = filePattern.substring(0, filePattern.lastIndexOf(File.separator));
        DeleteAction deleteAction = DeleteAction.createDeleteAction(basePath, true, 1, false, null, pathConditions, null, configuration);
        SizeBasedTriggeringPolicy policy = SizeBasedTriggeringPolicy.createPolicy(maxFileSize);
        PatternLayout layout = PatternLayout.newBuilder().withPattern(conversionPattern).build();
        DefaultRolloverStrategy strategy = DefaultRolloverStrategy.newBuilder()
                .withConfig(configuration).withMax(String.valueOf(maxBackupIndex))
                .withCustomActions(new Action[]{deleteAction}).build();
        fileAppender = RollingFileAppender.newBuilder()
                .withName(appenderName)
                .setConfiguration(configuration)
                .withLayout(layout)
                .withFileName(filename)
                .withFilePattern(filePattern)
                .withPolicy(policy)
                .withStrategy(strategy)
                .build();
        configuration.addAppender(fileAppender);
        Configurator.setLevel(appenderName, Level.getLevel(log4jLevelString));
        fileAppender.start();
    }
    AsyncAppender async = (AsyncAppender) loggerContext.getRootLogger().getAppenders().get("async");
    if (null == async) {
        AppenderRef ref = AppenderRef.createAppenderRef(appenderName, Level.getLevel(log4jLevelString), null);
        async = AsyncAppender.newBuilder().setName("async")
                .setConfiguration(configuration)
                .setAppenderRefs(new AppenderRef[]{ref}).build();
        configuration.addAppender(async);
        loggerContext.getRootLogger().addAppender(async);
        async.start();
    }
    loggerContext.updateLoggers();
}