org.apache.logging.log4j.core.config.Configurator Java Examples

The following examples show how to use org.apache.logging.log4j.core.config.Configurator. 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: CliClient.java    From bt with Apache License 2.0 6 votes vote down vote up
private void configureLogging(LogLevel logLevel) {
    Level log4jLogLevel;
    switch (Objects.requireNonNull(logLevel)) {
        case NORMAL: {
            log4jLogLevel = Level.INFO;
            break;
        }
        case VERBOSE: {
            log4jLogLevel = Level.DEBUG;
            break;
        }
        case TRACE: {
            log4jLogLevel = Level.TRACE;
            break;
        }
        default: {
            throw new IllegalArgumentException("Unknown log level: " + logLevel.name());
        }
    }
    Configurator.setLevel("bt", log4jLogLevel);
}
 
Example #2
Source File: ConsoleAppenderNoAnsiStyleLayoutMain.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
static void test(final String[] args, final String config) {
    // System.out.println(System.getProperty("java.class.path"));
    try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderNoAnsiStyleLayoutMain.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.");
        logThrowableFromMethod();
        // This will log the stack trace as well:
        final IOException ioException = new IOException("test");
        LOG.error("Error message {}", "Hi", ioException);
        final Throwable t = new IOException("test suppressed");
        t.addSuppressed(new IOException("test suppressed 2", ioException));
        LOG.error("Error message {}, suppressed?", "Hi", t);
        LOG.error("Error message {}, suppressed?", "Hi", new IOException("test", t));
    }
}
 
Example #3
Source File: Log4J2Logger.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Creates new logger with given configuration {@code cfgFile}.
 *
 * @param cfgFile Log4j configuration XML file.
 * @throws IgniteCheckedException Thrown in case logger can't be created.
 */
public Log4J2Logger(File cfgFile) throws IgniteCheckedException {
    if (cfgFile == null)
        throw new IgniteCheckedException("Configuration XML file for Log4j must be specified.");

    if (!cfgFile.exists() || cfgFile.isDirectory())
        throw new IgniteCheckedException("Log4j2 configuration path was not found or is a directory: " + cfgFile);

    final String path = cfgFile.getAbsolutePath();

    addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() {
        @Override public Logger apply(Boolean init) {
            if (init)
                Configurator.initialize(LogManager.ROOT_LOGGER_NAME, path);

            return (Logger)LogManager.getRootLogger();
        }
    });

    quiet = quiet0;
    cfg = cfgFile.getPath();
}
 
Example #4
Source File: Log4jBridgeHandlerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void test5LevelPropSetLevel() {
    String name = "log4j.test.new_logger_level_set";
    Configurator.setLevel(name, org.apache.logging.log4j.Level.DEBUG);
    assertLogLevel(name, java.util.logging.Level.FINE);
    test5LevelPropFromConfigFile();    // the rest should be untouched!

    name = "log4j.Log4jBridgeHandlerTest.propagate1.nested1";
    Configurator.setLevel(name, org.apache.logging.log4j.Level.WARN);
    assertLogLevel(name, java.util.logging.Level.WARNING);
    // the others around should be untouched
    assertLogLevel("log4j.Log4jBridgeHandlerTest.propagate1", java.util.logging.Level.FINE);
    assertLogLevel("log4j.Log4jBridgeHandlerTest.propagate1.nested2.deeplyNested", java.util.logging.Level.WARNING);

    // note: no need to check for the other set[Root]Level() methods, because they all call
    // loggerContext.updateLoggers() which calls firePropertyChangeEvent()
}
 
Example #5
Source File: ShowEnvironmentVariables.java    From iaf with Apache License 2.0 6 votes vote down vote up
private String doPost(IPipeLineSession session) throws PipeRunException {
	Object formLogIntermediaryResultsObject = session.get("logIntermediaryResults");
	boolean formLogIntermediaryResults = ("on".equals((String) formLogIntermediaryResultsObject) ? true : false);
	String formLogLevel = (String) session.get("logLevel");
	Object formLengthLogRecordsObject = session.get("lengthLogRecords");
	int formLengthLogRecords = (formLengthLogRecordsObject != null
			? Integer.parseInt((String) formLengthLogRecordsObject) : -1);

	HttpServletRequest httpServletRequest = (HttpServletRequest) session.get(IPipeLineSession.HTTP_REQUEST_KEY);
	String commandIssuedBy = HttpUtils.getCommandIssuedBy(httpServletRequest);

	String msg = "LogLevel changed from [" + retrieveLogLevel() + "] to [" + formLogLevel
			+ "], logIntermediaryResults from [" + retrieveLogIntermediaryResults() + "] to [" + ""
			+ formLogIntermediaryResults + "]  and logMaxMessageLength from [" + retrieveLengthLogRecords()
			+ "] to [" + "" + formLengthLogRecords + "] by" + commandIssuedBy;
	log.warn(msg);
	secLog.info(msg);

	IbisMaskingLayout.setMaxLength(formLengthLogRecords);

	AppConstants.getInstance().setProperty("log.logIntermediaryResults",
			Boolean.toString(formLogIntermediaryResults));
	Configurator.setLevel(LogUtil.getRootLogger().getName(), Level.toLevel(formLogLevel));

	return retrieveFormInput(session, true);
}
 
Example #6
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void debugChangeLevelsChildLoggers() {
    final org.apache.logging.log4j.Logger loggerChild = context.getLogger(logger.getName() + ".child");
    // Use logger AND loggerChild
    logger.debug("Debug message 1");
    loggerChild.debug("Debug message 1 child");
    assertEventCount(app.getEvents(), 2);
    Configurator.setLevel(logger.getName(), Level.ERROR);
    Configurator.setLevel(loggerChild.getName(), Level.DEBUG);
    logger.debug("Debug message 2");
    loggerChild.debug("Debug message 2 child");
    assertEventCount(app.getEvents(), 3);
    Configurator.setLevel(logger.getName(), Level.DEBUG);
    logger.debug("Debug message 3");
    loggerChild.debug("Debug message 3 child");
    assertEventCount(app.getEvents(), 5);
}
 
Example #7
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void debugChangeLevelsMapChildLoggers() {
    logger.debug("Debug message 1");
    loggerChild.debug("Debug message 1 C");
    loggerGrandchild.debug("Debug message 1 GC");
    assertEventCount(app.getEvents(), 3);
    final Map<String, Level> map = new HashMap<>();
    map.put(logger.getName(), Level.OFF);
    map.put(loggerChild.getName(), Level.DEBUG);
    map.put(loggerGrandchild.getName(), Level.WARN);
    Configurator.setLevel(map);
    logger.debug("Debug message 2");
    loggerChild.debug("Debug message 2 C");
    loggerGrandchild.debug("Debug message 2 GC");
    assertEventCount(app.getEvents(), 4);
    map.put(logger.getName(), Level.DEBUG);
    map.put(loggerChild.getName(), Level.OFF);
    map.put(loggerGrandchild.getName(), Level.DEBUG);
    Configurator.setLevel(map);
    logger.debug("Debug message 3");
    loggerChild.debug("Debug message 3 C");
    loggerGrandchild.debug("Debug message 3 GC");
    assertEventCount(app.getEvents(), 6);
}
 
Example #8
Source File: Log4jWebInitializerImpl.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void initializeNonJndi(final String location) {
    if (this.name == null) {
        this.name = this.servletContext.getServletContextName();
        LOGGER.debug("Using the servlet context name \"{}\".", this.name);
    }
    if (this.name == null) {
        this.name = this.servletContext.getContextPath();
        LOGGER.debug("Using the servlet context context-path \"{}\".", this.name);
    }
    if (this.name == null && location == null) {
        LOGGER.error("No Log4j context configuration provided. This is very unusual.");
        this.name = new SimpleDateFormat("yyyyMMdd_HHmmss.SSS").format(new Date());
    }
    if (location != null && location.contains(",")) {
        final List<URI> uris = getConfigURIs(location);
        this.loggerContext = Configurator.initialize(this.name, this.getClassLoader(), uris, this.servletContext);
        return;
    }

    final URI uri = getConfigURI(location);
    this.loggerContext = Configurator.initialize(this.name, this.getClassLoader(), uri, this.servletContext);
}
 
Example #9
Source File: GTaskTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testExceptionInTaskListenerTaskStarted() {

	// disable printing of exception below
	Logger logger = LogManager.getLogger(GTaskManager.class);
	Configurator.setLevel(logger.getName(), Level.OFF);

	gTaskManager.addTaskListener(new GTaskListenerAdapter() {
		@Override
		public void taskStarted(GScheduledTask task) {
			throw new RuntimeException("Test Exception");
		}
	});

	gTaskManager.scheduleTask(new SimpleTask("Task 5"), 20, true);

	// this is testing that the exception does cause the taskManager to timeout still busy
	waitForTaskManager();

	Configurator.setLevel(logger.getName(), Level.DEBUG);
}
 
Example #10
Source File: DynamicThresholdFilterTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfig() {
    try (final LoggerContext ctx = Configurator.initialize("Test1",
            "target/test-classes/log4j2-dynamicfilter.xml")) {
        final Configuration config = ctx.getConfiguration();
        final Filter filter = config.getFilter();
        assertNotNull("No DynamicThresholdFilter", filter);
        assertTrue("Not a DynamicThresholdFilter", filter instanceof DynamicThresholdFilter);
        final DynamicThresholdFilter dynamic = (DynamicThresholdFilter) filter;
        final String key = dynamic.getKey();
        assertNotNull("Key is null", key);
        assertEquals("Incorrect key value", "loginId", key);
        final Map<String, Level> map = dynamic.getLevelMap();
        assertNotNull("Map is null", map);
        assertEquals("Incorrect number of map elements", 1, map.size());
    }
}
 
Example #11
Source File: CopyNumberAnalyser.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
public static void main(@NotNull final String[] args) throws ParseException, SQLException
{
    final Options options = new Options();
    CopyNumberAnalyser.addCmdLineArgs(options);

    final CommandLineParser parser = new DefaultParser();
    final CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption(LOG_DEBUG))
    {
        Configurator.setRootLevel(Level.DEBUG);
    }

    String outputDir = formOutputPath(cmd.getOptionValue(DATA_OUTPUT_DIR));

    final DatabaseAccess dbAccess = cmd.hasOption(DB_URL) ? databaseAccess(cmd) : null;

    CopyNumberAnalyser cnAnalyser = new CopyNumberAnalyser(outputDir, dbAccess);
    cnAnalyser.loadConfig(cmd);

    cnAnalyser.runAnalysis();
    cnAnalyser.close();

    LNX_LOGGER.info("CN analysis complete");
}
 
Example #12
Source File: Log4j2MetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void log4j2LevelMetrics() {
    new Log4j2Metrics().bindTo(registry);

    assertThat(registry.get("log4j2.events").counter().count()).isEqualTo(0.0);

    Logger logger = LogManager.getLogger(Log4j2MetricsTest.class);
    Configurator.setLevel(Log4j2MetricsTest.class.getName(), Level.INFO);
    logger.info("info");
    logger.warn("warn");
    logger.fatal("fatal");
    logger.error("error");
    logger.debug("debug"); // shouldn't record a metric as per log level config
    logger.trace("trace"); // shouldn't record a metric as per log level config

    assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1.0);
    assertThat(registry.get("log4j2.events").tags("level", "warn").counter().count()).isEqualTo(1.0);
    assertThat(registry.get("log4j2.events").tags("level", "fatal").counter().count()).isEqualTo(1.0);
    assertThat(registry.get("log4j2.events").tags("level", "error").counter().count()).isEqualTo(1.0);
    assertThat(registry.get("log4j2.events").tags("level", "debug").counter().count()).isEqualTo(0.0);
    assertThat(registry.get("log4j2.events").tags("level", "trace").counter().count()).isEqualTo(0.0);
}
 
Example #13
Source File: ConsoleAppenderAnsiStyleJira272Main.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-272.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 #14
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 #15
Source File: ConfigurationAssemblerTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildConfiguration() {
    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 #16
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 #17
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void debugChangeLevelAllChildrenLoggers() {
    // Use logger AND child loggers
    logger.debug("Debug message 1");
    loggerChild.debug("Debug message 1 child");
    loggerGrandchild.debug("Debug message 1 grandchild");
    assertEventCount(app.getEvents(), 3);
    Configurator.setAllLevels(logger.getName(), Level.OFF);
    logger.debug("Debug message 2");
    loggerChild.warn("Warn message 2 child");
    loggerGrandchild.fatal("Fatal message 2 grandchild");
    assertEventCount(app.getEvents(), 3);
    Configurator.setAllLevels(logger.getName(), Level.DEBUG);
    logger.debug("Debug message 3");
    loggerChild.warn("Trace message 3 child");
    loggerGrandchild.trace("Fatal message 3 grandchild");
    assertEventCount(app.getEvents(), 5);
}
 
Example #18
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 #19
Source File: DSWorkbenchSplashScreen.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
public void initializeSuperSpecialDebugFeatures() {
    if (SPECIAL_DEBUG_MODE) {
        return;
    }
    SystrayHelper.showInfoMessage("Switching to debug mode");
    deadlockDetector = new ThreadDeadlockDetector();
    deadlockDetector.addListener(new DefaultDeadlockListener());
    Configurator.setAllLevels(LogManager.getRootLogger().getName(), Level.DEBUG);
    logger.debug("==========================");
    logger.debug("==DEBUG MODE ESTABLISHED==");
    logger.debug("==========================");

    logger.debug("---------System Information---------");
    logger.debug("Operating System: " + System.getProperty("os.name") + " (" + System.getProperty("os.version") + "/" + System.getProperty("os.arch") + ")");
    logger.debug("Java: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + " (" + System.getProperty("java.home") + ")");
    logger.debug("Working Dir: " + System.getProperty("user.dir"));
    logger.debug("------------------------------------");
    SPECIAL_DEBUG_MODE = true;
}
 
Example #20
Source File: MCRLoggingCommands.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param name
 *            the name of the java class or java package to set the log
 *            level for
 * @param logLevelToSet
 *            the log level to set e.g. TRACE, DEBUG, INFO, WARN, ERROR and
 *            FATAL, providing any other value will lead to DEBUG as new log
 *            level
 */
@MCRCommand(syntax = "change log level of {0} to {1}",
    help = "{0} the package or class name for which to change the log level, {1} the log level to set.",
    order = 10)
public static synchronized void changeLogLevel(String name, String logLevelToSet) {
    LOGGER.info("Setting log level for \"{}\" to \"{}\"", name, logLevelToSet);
    Level newLevel = Level.getLevel(logLevelToSet);
    if (newLevel == null) {
        LOGGER.error("Unknown log level \"{}\"", logLevelToSet);
        return;
    }
    Logger log = "ROOT".equals(name) ? LogManager.getRootLogger() : LogManager.getLogger(name);
    if (log == null) {
        LOGGER.error("Could not get logger for \"{}\"", name);
        return;
    }
    LOGGER.info("Change log level from {} to {}", log.getLevel(), newLevel);
    Configurator.setLevel(log.getName(), newLevel);
}
 
Example #21
Source File: ChainFinder.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
private void enableLogVerbose()
{
    if(!mLogVerbose)
        return;

    mLogLevel = LNX_LOGGER.getLevel();
    Configurator.setRootLevel(TRACE);
}
 
Example #22
Source File: PropertiesConfigurationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private LoggerContext configure(String configLocation) throws Exception {
    File file = new File(configLocation);
    InputStream is = new FileInputStream(file);
    ConfigurationSource source = new ConfigurationSource(is, file);
    LoggerContext context = (LoggerContext) org.apache.logging.log4j.LogManager.getContext(false);
    Configuration configuration = new PropertiesConfigurationFactory().getConfiguration(context, source);
    assertNotNull("No configuration created", configuration);
    Configurator.reconfigure(configuration);
    return context;
}
 
Example #23
Source File: SinkApiV3ResourceTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = RestException.class, expectedExceptionsMessageRegExp = "Sink test-sink already exists")
public void testRegisterExistedSink() throws IOException {
    try {
        Configurator.setRootLevel(Level.DEBUG);

        when(mockedManager.containsFunction(eq(tenant), eq(namespace), eq(sink))).thenReturn(true);

        registerDefaultSink();
    } catch (RestException re){
        assertEquals(re.getResponse().getStatusInfo(), Response.Status.BAD_REQUEST);
        throw re;
    }
}
 
Example #24
Source File: DeltaLogging.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
/** Initialize log4j2 from a default (in XML non-strict format) */
private static void defaultLogging() {
    byte b[] = StrUtils.asUTF8bytes(getDefaultString());
    try (InputStream input = new ByteArrayInputStream(b)) {
        ConfigurationSource source = new ConfigurationSource(input);
        ConfigurationFactory factory = ConfigurationFactory.getInstance();
        Configuration configuration = factory.getConfiguration(null, source);
        Configurator.initialize(configuration);
    }
    catch (IOException ex) {
        IOX.exception(ex);
    }
}
 
Example #25
Source File: RetentionExpirationExporterApp.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * The main method of the application.
 *
 * @param args the command line arguments passed to the program.
 *
 * @throws java.io.FileNotFoundException if the logging file couldn't be found.
 */
@SuppressWarnings("PMD.DoNotCallSystemExit") // Using System.exit is allowed for an actual application to exit.
public static void main(String[] args) throws FileNotFoundException
{
    ToolsCommonConstants.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 + "\".");
        }

        RetentionExpirationExporterApp retentionExpirationExporterApp = new RetentionExpirationExporterApp();
        returnValue = retentionExpirationExporterApp.go(args);
    }
    catch (Exception e)
    {
        LOGGER.error("Error running herd retention expiration exporter application. {}", e.toString(), e);
        returnValue = ToolsCommonConstants.ReturnValue.FAILURE;
    }

    // Exit with the return code.
    System.exit(returnValue.getReturnCode());
}
 
Example #26
Source File: XmlCompactFileAppenderValidationTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void validateXmlSchema() throws Exception {
    final File file = new File("target", "XmlCompactFileAppenderValidationTest.log.xml");
    file.delete();
    final Logger log = LogManager.getLogger("com.foo.Bar");
    log.warn("Message 1");
    log.info("Message 2");
    log.debug("Message 3");
    Configurator.shutdown(this.loggerContext);
    this.validateXmlSchema(file);
}
 
Example #27
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 #28
Source File: ChainFinder.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
private void disableLogVerbose()
{
    if(!mLogVerbose)
        return;

    // restore logging
    Configurator.setRootLevel(mLogLevel);
}
 
Example #29
Source File: CliClient.java    From bt with Apache License 2.0 5 votes vote down vote up
private static void registerLog4jShutdownHook() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if( LogManager.getContext() instanceof LoggerContext) {
                Configurator.shutdown((LoggerContext)LogManager.getContext());
            }
        }
    });
}
 
Example #30
Source File: XsltErrorTestBase.java    From iaf with Apache License 2.0 5 votes vote down vote up
@After
public void finalChecks() {
	TestAppender.removeAppender(testAppender);
	Configurator.setLevel("nl.nn.adapterframework", Level.DEBUG);
	if (testForEmptyOutputStream) {
		// Xslt processing should not log to stderr
		System.setErr(prevStdErr);
		System.err.println("ErrorStream:"+errorOutputStream);
		assertThat(errorOutputStream.toString(), isEmptyString());
	}
}