org.apache.logging.log4j.core.appender.RollingFileAppender Java Examples

The following examples show how to use org.apache.logging.log4j.core.appender.RollingFileAppender. 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: Log4j2Util.java    From summerframework with Apache License 2.0 7 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private static void createAppenderAndStart(String loggerName, String fileName, String filePattern) {

    Layout layout = PatternLayout.newBuilder().withConfiguration(config)
        .withPattern("[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n").build();
    TimeBasedTriggeringPolicy tbtp = TimeBasedTriggeringPolicy.createPolicy(null, null);
    TriggeringPolicy tp = SizeBasedTriggeringPolicy.createPolicy("10M");
    CompositeTriggeringPolicy policyComposite = CompositeTriggeringPolicy.createPolicy(tbtp, tp);

    String loggerDir = datalogDir + File.separator;

    String loggerPathPrefix = loggerDir + File.separator;
    RollingFileAppender.Builder builder = RollingFileAppender.newBuilder().withFilePattern(filePattern)
        .withStrategy(null).withPolicy(policyComposite).withConfiguration(config);
    RollingFileAppender appender = builder.build();
    appender.start();
    config.addAppender(appender);

    AppenderRef ref = AppenderRef.createAppenderRef(loggerName, Level.INFO, null);
    AppenderRef[] refs = new AppenderRef[] {ref};
    LoggerConfig loggerConfig =
        LoggerConfig.createLogger(false, Level.ALL, loggerName, "true", refs, null, config, null);
    loggerConfig.addAppender(appender, null, null);
    config.addLogger(loggerName, loggerConfig);
    ctx.updateLoggers();
}
 
Example #2
Source File: RollingFileAppenderAccessTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
    }
}
 
Example #3
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 #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
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 #6
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 #7
Source File: Log4JLogConfigInitializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Returns a rolling file appender.
 *
 * @param file the file to output to, including path and filename.
 */
private RollingFileAppender getRollingFileAppender( String file )
{
    RollingFileAppender appender = RollingFileAppender.newBuilder().withFileName( file )
        .setName("appender_" + file)
        .withFilePattern( file + "%i")
        .setLayout( PATTERN_LAYOUT )
        .withPolicy(
            SizeBasedTriggeringPolicy.createPolicy( config.getProperty( ConfigurationKey.LOGGING_FILE_MAX_SIZE ) ) )
        .withStrategy( DefaultRolloverStrategy.newBuilder()
            .withMax( config.getProperty( ConfigurationKey.LOGGING_FILE_MAX_ARCHIVES ) ).build() )
        .build();

    appender.start();
    return appender;
}
 
Example #8
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 #9
Source File: Log4JLogConfigInitializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Configures rolling file loggers.
 *
 * @param filename the filename to output logging to.
 * @param loggers the logger names.
 */
private void configureLoggers( String filename, List<String> loggers )
{
    String file = getLogFile( filename );

    RollingFileAppender appender = getRollingFileAppender( file );

    getLogConfiguration().addAppender( appender );

    AppenderRef[] refs = createAppenderRef( "Ref_" + filename );

    for ( String loggerName : loggers )
    {
        LoggerConfig loggerConfig = LoggerConfig.createLogger( true, Level.INFO, loggerName, "true", refs, null,
            getLogConfiguration(), null );

        loggerConfig.addAppender(appender, null, null);

        getLogConfiguration().addLogger(loggerName, loggerConfig);

        log.info( "Added logger: " + loggerName + " using file: " + file );
    }
}
 
Example #10
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 #11
Source File: Log4j2ConfigurationFactoryTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testSoutJsonTempJson() {
    Configuration configuration = getLogConfig(Map.of("log_format_sout", "json"));

    assertThat(configuration.getAppenders().values()).hasSize(2);
    Optional<ConsoleAppender> consoleAppender = configuration.getAppenders().values().stream()
        .filter(ConsoleAppender.class::isInstance)
        .map(ConsoleAppender.class::cast)
        .findAny();
    assertThat(consoleAppender).isNotEmpty();
    assertThat(consoleAppender.get().getLayout()).isInstanceOf(EcsLayout.class);

    Optional<RollingFileAppender> fileAppender = configuration.getAppenders().values().stream()
        .filter(RollingFileAppender.class::isInstance)
        .map(RollingFileAppender.class::cast)
        .findAny();
    assertThat(fileAppender).isNotEmpty();
    assertThat(fileAppender.get().getLayout()).isInstanceOf(EcsLayout.class);
}
 
Example #12
Source File: Log4j2ConfigurationFactoryTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testSoutPlainTextTempJson() {
    Configuration configuration = getLogConfig(Map.of());

    assertThat(configuration.getAppenders().values()).hasSize(2);
    Optional<ConsoleAppender> consoleAppender = configuration.getAppenders().values().stream()
        .filter(ConsoleAppender.class::isInstance)
        .map(ConsoleAppender.class::cast)
        .findAny();
    assertThat(consoleAppender).isNotEmpty();
    assertThat(consoleAppender.get().getLayout()).isInstanceOf(PatternLayout.class);

    Optional<RollingFileAppender> fileAppender = configuration.getAppenders().values().stream()
        .filter(RollingFileAppender.class::isInstance)
        .map(RollingFileAppender.class::cast)
        .findAny();
    assertThat(fileAppender).isNotEmpty();
    assertThat(fileAppender.get().getLayout()).isInstanceOf(EcsLayout.class);
}
 
Example #13
Source File: RollingFileAppenderAccessTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Not a real test, just make sure we can compile access to the typed manager.
 *
 * @throws IOException
 */
@Test
public void testAccessManagerWithBuilder() 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());
    }
}
 
Example #14
Source File: CronTriggeringPolicyTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void testBuilder() {
    // @formatter:off
    final RollingFileAppender raf = RollingFileAppender.newBuilder()
        .setName("test1")
        .setFileName("target/testcmd1.log")
        .setFilePattern("target/testcmd1.log.%d{yyyy-MM-dd}")
        .setPolicy(createPolicy())
        .setStrategy(createStrategy())
        .setConfiguration(configuration)
        .build();
    // @formatter:on
    Assert.assertNotNull(raf);
}
 
Example #15
Source File: RollingFileAppenderLayoutTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultLayout() throws Exception {
    // @formatter:off
    Assert.assertNotNull(RollingFileAppender.newBuilder()
            .setName(RollingFileAppenderLayoutTest.class.getName())
            .setConfiguration(new DefaultConfiguration())
            .setFileName("log.txt")
            .setFilePattern("FilePattern")
            .setPolicy(OnStartupTriggeringPolicy.createPolicy(1))
            .setCreateOnDemand(true) // no need to clutter up test folder with another file
            .build().getLayout());
    // @formatter:on
}
 
Example #16
Source File: RollingAppenderSizeTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsCreateOnDemand() {
    final RollingFileAppender rfAppender = loggerContextRule.getRequiredAppender("RollingFile",
            RollingFileAppender.class);
    final RollingFileManager manager = rfAppender.getManager();
    Assert.assertNotNull(manager);
    Assert.assertEquals(createOnDemand, manager.isCreateOnDemand());
}
 
Example #17
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 #18
Source File: RollingAppenderDirectWriteStartupSizeTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRollingFileAppenderWithReconfigure() throws Exception {
  final RollingFileAppender rfAppender = loggerContextRule.getRequiredAppender("RollingFile",
      RollingFileAppender.class);
  final RollingFileManager manager = rfAppender.getManager();

  Assert.assertNotNull(manager);
  Assert.assertEquals("Existing file size not preserved on startup", MESSAGE.getBytes().length, manager.size);
}
 
Example #19
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 #20
Source File: LogFactory.java    From chronus with Apache License 2.0 5 votes vote down vote up
private Appender getAppender(String clKey, Configuration config, Appender appenderCfg) {
    Appender appender = null;
    if (appenderCfg instanceof RollingFileAppender) {
        RollingFileAppender rollingFileAppender = (RollingFileAppender) appenderCfg;
        appender = RollingFileAppender.newBuilder()
                .setConfiguration(config)
                .withName(clKey)
                .withFileName(rollingFileAppender.getFileName())
                .withFilePattern(rollingFileAppender.getFilePattern())
                .withLayout(rollingFileAppender.getLayout())
                .withFilter(rollingFileAppender.getFilter())
                .withPolicy(rollingFileAppender.getTriggeringPolicy())
                .withStrategy(rollingFileAppender.getManager().getRolloverStrategy())
                .build();
    } else if (appenderCfg instanceof FileAppender) {
        FileAppender fileAppender = (FileAppender) appenderCfg;
        appender = FileAppender.newBuilder()
                .setConfiguration(config)
                .withName(appenderCfg.getName())
                .withFileName(fileAppender.getFileName())
                .withLayout(fileAppender.getLayout())
                .withFilter(fileAppender.getFilter())
                .build();
    } else {
        LogManager.getLogger(LogFactory.class).warn("unsupported appender type ,appender type not in(RollingFileAppender,ConsoleAppender,FileAppender)", appenderCfg.getClass());
    }
    if (appender != null) {
        config.addAppender(appender);
    }
    return appender;
}
 
Example #21
Source File: Log4j1ConfigurationParser.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void buildRollingFileAppender(final String appenderName) {
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName,
            RollingFileAppender.PLUGIN_NAME);
    buildFileAppender(appenderName, appenderBuilder);
    final String fileName = getLog4jAppenderValue(appenderName, "File");
    appenderBuilder.addAttribute("filePattern", fileName + ".%i");
    final String maxFileSizeString = getLog4jAppenderValue(appenderName, "MaxFileSize", "10485760");
    final String maxBackupIndexString = getLog4jAppenderValue(appenderName, "MaxBackupIndex", "1");
    final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies").addComponent(
            builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", maxFileSizeString));
    appenderBuilder.addComponent(triggeringPolicy);
    appenderBuilder.addComponent(
            builder.newComponent("DefaultRolloverStrategy").addAttribute("max", maxBackupIndexString));
    builder.add(appenderBuilder);
}
 
Example #22
Source File: RollingFileAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Appender createAppender(final String name, final Log4j1Configuration config, final Layout layout,
        final Filter filter, final boolean bufferedIo, boolean immediateFlush, final String fileName,
        final String level, final String maxSize, final String maxBackups) {
    org.apache.logging.log4j.core.Layout<?> fileLayout = null;
    if (bufferedIo) {
        immediateFlush = true;
    }
    if (layout instanceof LayoutWrapper) {
        fileLayout = ((LayoutWrapper) layout).getLayout();
    } else if (layout != null) {
        fileLayout = new LayoutAdapter(layout);
    }
    org.apache.logging.log4j.core.Filter fileFilter = buildFilters(level, filter);
    if (fileName == null) {
        LOGGER.warn("Unable to create File Appender, no file name provided");
        return null;
    }
    String filePattern = fileName +"%d{yyy-MM-dd}";
    TriggeringPolicy timePolicy = TimeBasedTriggeringPolicy.newBuilder().setModulate(true).build();
    SizeBasedTriggeringPolicy sizePolicy = SizeBasedTriggeringPolicy.createPolicy(maxSize);
    CompositeTriggeringPolicy policy = CompositeTriggeringPolicy.createPolicy(sizePolicy, timePolicy);
    RolloverStrategy strategy = DefaultRolloverStrategy.newBuilder()
            .setConfig(config)
            .setMax(maxBackups)
            .build();
    return new AppenderWrapper(RollingFileAppender.newBuilder()
            .setName(name)
            .setConfiguration(config)
            .setLayout(fileLayout)
            .setFilter(fileFilter)
            .setBufferedIo(bufferedIo)
            .setImmediateFlush(immediateFlush)
            .setFileName(fileName)
            .setFilePattern(filePattern)
            .setPolicy(policy)
            .setStrategy(strategy)
            .build());
}
 
Example #23
Source File: DailyRollingFileAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private <T extends Log4j1Configuration> Appender createAppender(final String name, final Layout layout,
        final Filter filter, final String fileName, final boolean append, boolean immediateFlush,
        final String level, final boolean bufferedIo, final int bufferSize, final T configuration) {

    org.apache.logging.log4j.core.Layout<?> fileLayout = null;
    if (bufferedIo) {
        immediateFlush = true;
    }
    if (layout instanceof LayoutWrapper) {
        fileLayout = ((LayoutWrapper) layout).getLayout();
    } else if (layout != null) {
        fileLayout = new LayoutAdapter(layout);
    }
    org.apache.logging.log4j.core.Filter fileFilter = buildFilters(level, filter);
    if (fileName == null) {
        LOGGER.warn("Unable to create File Appender, no file name provided");
        return null;
    }
    String filePattern = fileName +"%d{yyy-MM-dd}";
    TriggeringPolicy policy = TimeBasedTriggeringPolicy.newBuilder().setModulate(true).build();
    RolloverStrategy strategy = DefaultRolloverStrategy.newBuilder()
            .setConfig(configuration)
            .setMax(Integer.toString(Integer.MAX_VALUE))
            .build();
    return new AppenderWrapper(RollingFileAppender.newBuilder()
            .setName(name)
            .setConfiguration(configuration)
            .setLayout(fileLayout)
            .setFilter(fileFilter)
            .setFileName(fileName)
            .setBufferSize(bufferSize)
            .setImmediateFlush(immediateFlush)
            .setFilePattern(filePattern)
            .setPolicy(policy)
            .setStrategy(strategy)
            .build());
}
 
Example #24
Source File: Log4j1ConfigurationParser.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void buildRollingFileAppender(final String appenderName) {
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName,
            RollingFileAppender.PLUGIN_NAME);
    buildFileAppender(appenderName, appenderBuilder);
    final String fileName = getLog4jAppenderValue(appenderName, "File");
    appenderBuilder.addAttribute("filePattern", fileName + ".%i");
    final String maxFileSizeString = getLog4jAppenderValue(appenderName, "MaxFileSize", "10485760");
    final String maxBackupIndexString = getLog4jAppenderValue(appenderName, "MaxBackupIndex", "1");
    final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies").addComponent(
            builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", maxFileSizeString));
    appenderBuilder.addComponent(triggeringPolicy);
    appenderBuilder.addComponent(
            builder.newComponent("DefaultRolloverStrategy").addAttribute("max", maxBackupIndexString));
    builder.add(appenderBuilder);
}
 
Example #25
Source File: Log4j1ConfigurationParser.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void buildDailyRollingFileAppender(final String appenderName) {
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName,
            RollingFileAppender.PLUGIN_NAME);
    buildFileAppender(appenderName, appenderBuilder);
    final String fileName = getLog4jAppenderValue(appenderName, "File");
    final String datePattern = getLog4jAppenderValue(appenderName, "DatePattern", fileName + "'.'yyyy-MM-dd");
    appenderBuilder.addAttribute("filePattern", fileName + "%d{" + datePattern + "}");
    final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies")
            .addComponent(builder.newComponent("TimeBasedTriggeringPolicy").addAttribute("modulate", true));
    appenderBuilder.addComponent(triggeringPolicy);
    appenderBuilder
            .addComponent(builder.newComponent("DefaultRolloverStrategy").addAttribute("max", Integer.MAX_VALUE));
    builder.add(appenderBuilder);
}
 
Example #26
Source File: Log4j1ConfigurationParser.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private void buildDailyRollingFileAppender(final String appenderName) {
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName,
            RollingFileAppender.PLUGIN_NAME);
    buildFileAppender(appenderName, appenderBuilder);
    final String fileName = getLog4jAppenderValue(appenderName, "File");
    final String datePattern = getLog4jAppenderValue(appenderName, "DatePattern", fileName + "'.'yyyy-MM-dd");
    appenderBuilder.addAttribute("filePattern", fileName + "%d{" + datePattern + "}");
    final ComponentBuilder<?> triggeringPolicy = builder.newComponent("Policies")
            .addComponent(builder.newComponent("TimeBasedTriggeringPolicy").addAttribute("modulate", true));
    appenderBuilder.addComponent(triggeringPolicy);
    appenderBuilder
            .addComponent(builder.newComponent("DefaultRolloverStrategy").addAttribute("max", Integer.MAX_VALUE));
    builder.add(appenderBuilder);
}
 
Example #27
Source File: Log4J2Logger.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Nullable @Override public String fileName() {
    for (Logger log = impl; log != null; log = log.getParent()) {
        for (Appender a : log.getAppenders().values()) {
            if (a instanceof FileAppender)
                return ((FileAppender)a).getFileName();

            if (a instanceof RollingFileAppender)
                return ((RollingFileAppender)a).getFileName();

            if (a instanceof RoutingAppender) {
                try {
                    RoutingAppender routing = (RoutingAppender)a;

                    Field appsFiled = routing.getClass().getDeclaredField("appenders");

                    appsFiled.setAccessible(true);

                    Map<String, AppenderControl> appenders = (Map<String, AppenderControl>)appsFiled.get(routing);

                    for (AppenderControl control : appenders.values()) {
                        Appender innerApp = control.getAppender();

                        if (innerApp instanceof FileAppender)
                            return normalize(((FileAppender)innerApp).getFileName());

                        if (innerApp instanceof RollingFileAppender)
                            return normalize(((RollingFileAppender)innerApp).getFileName());
                    }
                }
                catch (IllegalAccessException | NoSuchFieldException e) {
                    error("Failed to get file name (was the implementation of log4j2 changed?).", e);
                }
            }
        }
    }

    return null;
}
 
Example #28
Source File: Log4JLogConfigInitializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Configures a root file logger.
 *
 * @param filename the filename to output logging to.
 */
private void configureRootLogger( String filename )
{
    String file = getLogFile( filename );

    RollingFileAppender appender = getRollingFileAppender( file );

    getLogConfiguration().addAppender( appender );

    getLogConfiguration().getRootLogger().addAppender( getLogConfiguration().getAppender( appender.getName() ),
        Level.INFO, null );

    log.info( "Added root logger using file: " + file );
}
 
Example #29
Source File: LogFactory.java    From chronus with Apache License 2.0 5 votes vote down vote up
private Appender getAppender(LogConfig abyLogConfig, Configuration config, Appender appenderCfg) {
    Appender appender = null;
    if (appenderCfg instanceof RollingFileAppender) {
        RollingFileAppender rollingFileAppender = (RollingFileAppender) appenderCfg;
        appender = RollingFileAppender.newBuilder()
                .setConfiguration(config)
                .withName(appenderCfg.getName().replace(abyLogConfig.getAppenderNameKey(), abyLogConfig.getName()))
                .withFileName(rollingFileAppender.getFileName().replaceAll(abyLogConfig.getFileNameKey(), abyLogConfig.getFileName()))
                .withFilePattern(rollingFileAppender.getFilePattern().replaceAll(abyLogConfig.getFileNameKey(), abyLogConfig.getFileName()))
                .withLayout(rollingFileAppender.getLayout())
                .withFilter(rollingFileAppender.getFilter())
                .withPolicy(rollingFileAppender.getTriggeringPolicy())
                .withStrategy(rollingFileAppender.getManager().getRolloverStrategy())
                .build();
    } else if (appenderCfg instanceof FileAppender) {
        FileAppender fileAppender = (FileAppender) appenderCfg;
        appender = FileAppender.newBuilder()
                .setConfiguration(config)
                .withName(appenderCfg.getName().replace(abyLogConfig.getAppenderNameKey(), abyLogConfig.getName()))
                .withFileName(fileAppender.getFileName().replaceAll(abyLogConfig.getFileNameKey(), abyLogConfig.getFileName()))
                .withLayout(fileAppender.getLayout())
                .withFilter(fileAppender.getFilter())
                .build();
    } else {
        LogManager.getLogger(LogFactory.class).warn("unsupported appender type ,appender type not in(RollingFileAppender,ConsoleAppender,FileAppender)", appenderCfg.getClass());
    }
    if (appender != null) {
        if (!appender.isStarted()) {
            appender.start();
        }
        config.addAppender(appender);
    }
    return appender;
}
 
Example #30
Source File: Log4j2ConfigurationFactoryTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Test
void testLogFileJson(@TempDir Path tempDir) {
    String logFile = tempDir.resolve("agent.json").toString();
    Configuration configuration = getLogConfig(Map.of("log_file", logFile, "log_format_file", "json"));

    assertThat(configuration.getAppenders().values()).hasSize(1);
    Appender appender = configuration.getAppenders().values().iterator().next();

    assertThat(appender).isInstanceOf(RollingFileAppender.class);
    assertThat(((RollingFileAppender) appender).getFileName()).isEqualTo(logFile);
    assertThat(appender.getLayout()).isInstanceOf(EcsLayout.class);
}