Java Code Examples for org.apache.logging.log4j.core.config.Configurator#initialize()

The following examples show how to use org.apache.logging.log4j.core.config.Configurator#initialize() . 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: ConsoleAppenderAnsiStyleLayoutMain.java    From logging-log4j2 with Apache License 2.0 7 votes vote down vote up
public void test(final String[] args) {
    System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
    // System.out.println(System.getProperty("java.class.path"));
    final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml"
            : args[0];
    try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) {
        final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class);
        logger.fatal("Fatal message.");
        logger.error("Error message.");
        logger.warn("Warning message.");
        logger.info("Information message.");
        logger.debug("Debug message.");
        logger.trace("Trace message.");
        logger.error("Error message.", new IOException("test"));
    }
}
 
Example 2
Source File: ConfigurationAssemblerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildConfiguration() throws Exception {
    try {
        System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR,
                "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector");
        final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory
                .newConfigurationBuilder();
        CustomConfigurationFactory.addTestFixtures("config name", builder);
        final Configuration configuration = builder.build();
        try (LoggerContext ctx = Configurator.initialize(configuration)) {
            validate(configuration);
        }
    } finally {
        System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR);
    }
}
 
Example 3
Source File: ConsoleAppenderJAnsiMessageMain.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public void test(final String[] args) {
    System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
    // System.out.println(System.getProperty("java.class.path"));
    final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-msg-ansi.xml"
            : args[0];
    try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
            config)) {
        final Logger logger = LogManager.getLogger(ConsoleAppenderJAnsiMessageMain.class);
        logger.info(ansi().fg(RED).a("Hello").fg(CYAN).a(" World").reset());
        // JAnsi format:
        // logger.info("@|red Hello|@ @|cyan World|@");
        for (final Entry<Object, Object> entry : System.getProperties().entrySet()) {
            logger.info("@|KeyStyle {}|@ = @|ValueStyle {}|@", entry.getKey(), entry.getValue());
        }
    }
}
 
Example 4
Source File: ConsoleAppenderAnsiStyleJira319Main.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) {
    System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
    // System.out.println(System.getProperty("java.class.path"));
    final String config = args.length == 0 ? "target/test-classes/log4j2-319.xml" : args[0];
    try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
            config)) {
        LOG.fatal("Fatal message.");
        LOG.error("Error message.");
        LOG.warn("Warning message.");
        LOG.info("Information message.");
        LOG.debug("Debug message.");
        LOG.trace("Trace message.");
        try {
            throw new NullPointerException();
        } catch (final Exception e) {
            LOG.error("Error message.", e);
            LOG.catching(Level.ERROR, e);
        }
        LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?");
        LOG.info("Information message.");
    }
}
 
Example 5
Source File: SimpleConfiguratorIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenDefaultLog4j2Environment_whenProgrammaticallyConfigured_thenLogsCorrectly() {
    ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    AppenderComponentBuilder console = builder.newAppender("Stdout", "CONSOLE")
            .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
    console.add(builder.newLayout("PatternLayout")
            .addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable"));
    builder.add(console);
    builder.add(builder.newLogger("com", Level.DEBUG)
            .add(builder.newAppenderRef("Stdout"))
            .addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR)
            .add(builder.newAppenderRef("Stdout")));
    Configurator.initialize(builder.build());
    LogPrinter logPrinter = new LogPrinter();
    logPrinter.printlog();
}
 
Example 6
Source File: LoggerFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static void initGuiLogging(String logFile) {
  ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
  builder.add(builder.newRootLogger(Level.INFO));
  LoggerContext context = Configurator.initialize(builder.build());

  PatternLayout layout = PatternLayout.newBuilder()
      .withPattern("[%d{ISO8601}] %5p (%F:%L) - %m%n")
      .withCharset(StandardCharsets.UTF_8)
      .build();

  Appender fileAppender = FileAppender.newBuilder()
      .setName("File")
      .setLayout(layout)
      .withFileName(logFile)
      .withAppend(false)
        .build();
  fileAppender.start();

  Appender textAreaAppender = TextAreaAppender.newBuilder()
      .setName("TextArea")
      .setLayout(layout)
      .build();
  textAreaAppender.start();

  context.getRootLogger().addAppender(fileAppender);
  context.getRootLogger().addAppender(textAreaAppender);
  context.updateLoggers();
}
 
Example 7
Source File: Log4J2LoggerFactory.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private static LoggerContext init() {
  try {
    String fileRef = Boolean.getBoolean(ApplicationProperties.CONSULO_MAVEN_CONSOLE_LOG) ? "/log4j2-console.xml" : "/log4j2-default.xml";

    String text = FileUtil.loadTextAndClose(Log4J2LoggerFactory.class.getResourceAsStream(fileRef));
    text = StringUtil.replace(text, SYSTEM_MACRO, StringUtil.replace(ContainerPathManager.get().getSystemPath(), "\\", "\\\\"));
    text = StringUtil.replace(text, APPLICATION_MACRO, StringUtil.replace(ContainerPathManager.get().getHomePath(), "\\", "\\\\"));
    text = StringUtil.replace(text, LOG_DIR_MACRO, StringUtil.replace(ContainerPathManager.get().getLogPath(), "\\", "\\\\"));

    File file = new File(ContainerPathManager.get().getLogPath());
    if (!file.mkdirs() && !file.exists()) {
      System.err.println("Cannot create log directory: " + file);
    }

    ConfigurationSource source = new ConfigurationSource(new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)));

    return Configurator.initialize(Log4J2LoggerFactory.class.getClassLoader(), source);
  }
  catch (Exception e) {
    e.printStackTrace();
    StartupUtil.showMessage("Consulo", e);
    return null;
  }
}
 
Example 8
Source File: DownloaderApp.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * The main method of the Downloader Application.
 *
 * @param args the command line arguments passed to the program.
 */
@SuppressWarnings("PMD.DoNotCallSystemExit") // Using System.exit is allowed for an actual application to exit.
public static void main(String[] args)
{
    ReturnValue returnValue;
    try
    {
        // Initialize Log4J with the resource. The configuration itself can use "monitorInterval" to have it refresh if it came from a file.
        LoggerContext loggerContext = Configurator.initialize(null, ToolsCommonConstants.LOG4J_CONFIG_LOCATION);

        // For some initialization errors, a null context will be returned.
        if (loggerContext == null)
        {
            // We shouldn't get here since we already checked if the location existed previously.
            throw new IllegalArgumentException("Invalid configuration found at resource location: \"" + ToolsCommonConstants.LOG4J_CONFIG_LOCATION + "\".");
        }

        DownloaderApp downloaderApp = new DownloaderApp();
        returnValue = downloaderApp.go(args);
    }
    catch (Exception e)
    {
        LOGGER.error("Error running herd downloader. {}", e.toString(), e);
        returnValue = ReturnValue.FAILURE;
    }

    // Exit with the return code.
    System.exit(returnValue.getReturnCode());
}
 
Example 9
Source File: RollingFileAppenderUpdateDataTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testClosingLoggerContext() {
    // initial config with indexed rollover
    try (LoggerContext loggerContext1 = Configurator.initialize(buildConfigA().build())) {
        validateAppender(loggerContext1, "target/rolling-update-date/foo.log.%i");
    }

    // rebuild config with date based rollover
    try (LoggerContext loggerContext2 = Configurator.initialize(buildConfigB().build())) {
        validateAppender(loggerContext2, "target/rolling-update-date/foo.log.%d{yyyy-MM-dd-HH:mm:ss}.%i");
    }
}
 
Example 10
Source File: ConsoleAppenderAnsiMessagesMain.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) {
    System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable
    try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
            "target/test-classes/log4j2-console.xml")) {
        LOG.fatal("\u001b[1;35mFatal message.\u001b[0m");
        LOG.error("\u001b[1;31mError message.\u001b[0m");
        LOG.warn("\u001b[0;33mWarning message.\u001b[0m");
        LOG.info("\u001b[0;32mInformation message.\u001b[0m");
        LOG.debug("\u001b[0;36mDebug message.\u001b[0m");
        LOG.trace("\u001b[0;30mTrace message.\u001b[0m");
        LOG.error("\u001b[1;31mError message.\u001b[0m", new IOException("test"));
    }
}
 
Example 11
Source File: LogRolloverTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final File file = new File(CONFIG);
    try (final LoggerContext ctx = Configurator.initialize("LogTest", LogRolloverTest.class.getClassLoader(),
            file.toURI())) {
        final Logger logger = LogManager.getLogger("TestLogger");

        for (long i = 0;; i += 1) {
            logger.debug("Sequence: " + i);
            Thread.sleep(250);
        }
    }
}
 
Example 12
Source File: Log4j2MetricsTest.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Issue("#1466")
@Test
void filterWhenRootLoggerAdditivityIsFalseShouldWork() throws IOException {
    ConfigurationSource source = new ConfigurationSource(getClass().getResourceAsStream("/binder/logging/log4j2-root-logger-additivity-false.xml"));
    Configurator.initialize(null, source);

    Logger logger = LogManager.getLogger(Log4j2MetricsTest.class);

    new Log4j2Metrics().bindTo(registry);

    assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(0);

    logger.info("Hello, world!");
    assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1);
}
 
Example 13
Source File: RollingFileAppenderUpdateDataTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testReconfigure() {
	// initial config with indexed rollover
	loggerContext1 = Configurator.initialize(buildConfigA().build());
	validateAppender(loggerContext1, "target/rolling-update-date/foo.log.%i");

	// rebuild config with date based rollover
	loggerContext1.setConfiguration(buildConfigB().build());
	validateAppender(loggerContext1, "target/rolling-update-date/foo.log.%d{yyyy-MM-dd-HH:mm:ss}.%i");
}
 
Example 14
Source File: LogConfigurator.java    From crate with Apache License 2.0 4 votes vote down vote up
private static void configureStatusLogger() {
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(Level.ERROR);
    Configurator.initialize(builder.build());
}
 
Example 15
Source File: Log4jOverridableConfigurer.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes Log4J from a resource location.
 *
 * @param resourceLocation the resource location.
 *
 * @return true if Log4J was initialized or false if not.
 */
// Using System.out and System.err is okay here because we need a place to output information before logging is initialized.
@SuppressWarnings("PMD.SystemPrintln")
private boolean initializeLog4jFromResourceLocation(String resourceLocation)
{
    // Default the return boolean to false (i.e. we didn't initialize Log4J).
    boolean isInitSuccessful = false;

    // See if an override resource location is configured.
    if (StringUtils.isNotBlank(resourceLocation))
    {
        // Trim the resource location and get a handle to the resource.
        String resourceLocationTrimmed = resourceLocation.trim();
        Resource resource = applicationContext.getResource(resourceLocationTrimmed);

        // If the resource exists, then initialize Log4J with the resource.
        if (resource.exists())
        {
            // Initialize Log4J from the resource location.
            // Write the "good" parameters to System.out since logging hasn't been initialized yet.
            System.out.println("Using Log4J configuration location \"" + resourceLocationTrimmed + "\".");

            // Initialize Log4J with the resource. The configuration itself can use "monitorInterval" to have it refresh if it came from a file.
            loggerContext = Configurator.initialize(null, resourceLocationTrimmed);

            // For some initialization errors, a null context will be returned.
            if (loggerContext == null)
            {
                // We shouldn't get here since we already checked if the location existed previously.
                throw new IllegalArgumentException("Invalid configuration found at resource location: \"" + resourceLocationTrimmed + "\".");
            }

            // Now that Logging has been initialized, log something so we know it's working.
            // Note that it is possible that Log4J didn't initialize properly and didn't let us know. In this case, an error will be displayed on the
            // console by Log4J and the default logging level will be "error". As such, the below logging message won't be displayed.
            LOGGER.info("Logging successfully initialized.");

            // Mark that we successfully initialized Log4J - as much as we're able to.
            isInitSuccessful = true;
        }
    }

    // Return if we successfully initialized Log4J or not.
    return isInitSuccessful;
}
 
Example 16
Source File: Log4jOverridableConfigurer.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes a Log4J configuration based on the specified configuration string.
 *
 * @param xmlConfigurationString the configuration string.
 */
// Using System.out and System.err is okay here because we need a place to output information before logging is initialized.
@SuppressWarnings("PMD.SystemPrintln")
private void initializeConfiguration(String xmlConfigurationString)
{
    try
    {
        // Note whether this is the first time we are creating the configuration based on whether we already created a temp configuration file or not.
        boolean initialConfiguration = tempFile == null;

        // If this is the initial configuration, create a temp file and add a shutdown hook so it will get cleaned up upon JVM exit.
        if (initialConfiguration)
        {
            tempFile = Files.createTempFile("log4jTempConfig", ".xml");
            System.out.println("Created temporary logging configuration file: \"" + tempFile.toString() + "\".");
            Runtime.getRuntime().addShutdownHook(new ShutdownHook(tempFile));
        }

        // Write the Log4J configuration to the temporary file every time.
        try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile.toAbsolutePath().toString()))
        {
            IOUtils.write(xmlConfigurationString, fileOutputStream);
        }

        // Get the refresh interval from the configuration.
        int refreshIntervalSeconds = getRefreshIntervalSeconds(xmlConfigurationString);

        if (initialConfiguration)
        {
            System.out.println("Initial logging refresh interval: " + refreshIntervalSeconds + " second(s).");

            // This is the initial configuration so tell Log4J to do the initialization based on the temporary file we just created.
            // The configuration file itself can use "monitorInterval" to have it refresh if it came from a file. We will let
            // Log4J do it's auto-refresh from the temporary file, but we will update that file ourselves using our watchdog.
            loggerContext = Configurator.initialize(tempFile.toString(), null, tempFile.toUri());

            // Create and start a watchdog thread to monitor the DB configuration and when a change is found, it will call this method again
            // to overwrite the temporary file with the new configuration.
            watchdog = new Log4jDbWatchdog(refreshIntervalSeconds);
            watchdog.start();
        }
        else
        {
            // If this isn't the initial configuration, update the refresh interval (or set it the same value). That way, if a new refresh interval
            // was specified in the configuration file, we will grab it and adjust the watchdog interval.
            watchdog.setRefreshIntervalSeconds(refreshIntervalSeconds);
        }
    }
    catch (IOException ex)
    {
        throw new IllegalStateException("Unable to initialize Log4J with configuration: \"" + xmlConfigurationString + "\".", ex);
    }
}
 
Example 17
Source File: log4j2Test.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
    Configurator.initialize("log4j2", "src/test/resources/log4j2-example.xml");
}
 
Example 18
Source File: CronTriggeringPolicyTest.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
/**
 * Tests LOG4J2-1740 Add CronTriggeringPolicy programmatically leads to NPE
 */
@Test
public void testLoggerContextAndBuilder() {
    Configurator.initialize(configuration);
    testBuilder();
}
 
Example 19
Source File: XmlConigurationSecurity.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 5000L)
public void xmlSecurity() throws IOException {
    final LoggerContext context = Configurator.initialize("XmlConfigurationSecurity", "XmlConfigurationSecurity.xml");
    assertNotNull(context.getConfiguration().getAppender("list"));
}
 
Example 20
Source File: log4j2Test.java    From rocketmq-4.3.0 with Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
    Configurator.initialize("log4j2", "src/test/resources/log4j2-example.xml");
}