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

The following examples show how to use org.apache.logging.log4j.core.config.Configurator#setLevel() . 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: 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 2
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 3
Source File: Log4j2MetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void filterWhenLoggerAdditivityIsFalseShouldWork() {
    Logger additivityDisabledLogger = LogManager.getLogger("additivityDisabledLogger");
    Configurator.setLevel("additivityDisabledLogger", Level.INFO);

    LoggerContext loggerContext = (LoggerContext) LogManager.getContext();
    Configuration configuration = loggerContext.getConfiguration();
    LoggerConfig loggerConfig = configuration.getLoggerConfig("additivityDisabledLogger");
    loggerConfig.setAdditive(false);

    new Log4j2Metrics().bindTo(registry);

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

    additivityDisabledLogger.info("Hello, world!");
    assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1);
}
 
Example 4
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 5
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 6
Source File: GhidraFileChooserTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Test
public void testRememberSettings_Size() throws Exception {
	//
	// A place to remember settings like size and the type of view showing
	//

	// Enable tracing to catch odd test failure
	LoggingInitialization.initializeLoggingSystem();
	Logger logger = LogManager.getLogger(GhidraFileChooser.class);
	Configurator.setLevel(logger.getName(), Level.TRACE);

	final JComponent component = chooser.getComponent();
	Dimension originalSize = component.getSize();
	DockingDialog dialog = (DockingDialog) getInstanceField("dialog", chooser);

	final Dimension updatedSize =
		new Dimension(originalSize.width * 2, originalSize.height * 2);
	runSwing(() -> dialog.setSize(updatedSize));

	// close to save the changes
	close();

	// load the saved changes
	show(false);

	final AtomicReference<Dimension> preferredSizeReference = new AtomicReference<>();
	runSwing(() -> {
		Dimension preferredSize = chooser.getDefaultSize();
		preferredSizeReference.set(preferredSize);
	});

	assertEquals("File chooser did not remember last picked size", updatedSize,
		preferredSizeReference.get());
}
 
Example 7
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void debugChangeLevelsMap() {
    logger.debug("Debug message 1");
    assertEventCount(app.getEvents(), 1);
    final Map<String, Level> map = new HashMap<>();
    map.put(logger.getName(), Level.OFF);
    Configurator.setLevel(map);
    logger.debug("Debug message 2");
    assertEventCount(app.getEvents(), 1);
    map.put(logger.getName(), Level.DEBUG);
    Configurator.setLevel(map);
    logger.debug("Debug message 3");
    assertEventCount(app.getEvents(), 2);
}
 
Example 8
Source File: HttpWebConnectionTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts(DEFAULT = "Host",
        IE = {})
public void hostHeaderFirst() throws Exception {
    final Logger logger = (Logger) LogManager.getLogger("org.apache.http.headers");
    final Level oldLevel = logger.getLevel();
    Configurator.setLevel(logger.getName(), Level.DEBUG);

    final StringWriter stringWriter = new StringWriter();
    final PatternLayout layout = PatternLayout.newBuilder().withPattern("%msg%n").build();

    final WriterAppender writerAppender = WriterAppender.newBuilder().setName("writeLogger").setTarget(stringWriter)
            .setLayout(layout).build();
    writerAppender.start();

    logger.addAppender(writerAppender);
    try {
        startWebServer("./");

        final WebClient webClient = getWebClient();
        webClient.getPage(URL_FIRST + "LICENSE.txt");
        final String[] messages = StringUtils.split(stringWriter.toString(), "\n");
        for (int i = 0; i < getExpectedAlerts().length; i++) {
            assertTrue(messages[i + 1].contains(getExpectedAlerts()[i]));
        }
    }
    finally {
        logger.removeAppender(writerAppender);
        Configurator.setLevel(logger.getName(), oldLevel);
    }
}
 
Example 9
Source File: DefaultCredentialsProvider2Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that on calling the website twice, only the first time unauthorized response is returned.
 *
 * @throws Exception if an error occurs
 */
@Test
public void basicAuthentication_singleAuthenticaiton() throws Exception {
    final Logger logger = (Logger) LogManager.getLogger("org.apache.http.headers");
    final Level oldLevel = logger.getLevel();
    Configurator.setLevel(logger.getName(), Level.DEBUG);

    final StringWriter stringWriter = new StringWriter();
    final PatternLayout layout = PatternLayout.newBuilder().withPattern("%msg%n").build();

    final WriterAppender writerAppender = WriterAppender.newBuilder().setName("writeLogger").setTarget(stringWriter)
            .setLayout(layout).build();
    writerAppender.start();

    logger.addAppender(writerAppender);
    try {
        ((DefaultCredentialsProvider) getWebClient().getCredentialsProvider()).addCredentials("jetty", "jetty");

        loadPage("Hi There");
        int unauthorizedCount = StringUtils.countMatches(stringWriter.toString(), "HTTP/1.1 401");
        assertEquals(1, unauthorizedCount);

        // and again
        loadPage("Hi There");
        unauthorizedCount = StringUtils.countMatches(stringWriter.toString(), "HTTP/1.1 401");
        assertEquals(1, unauthorizedCount);
    }
    finally {
        logger.removeAppender(writerAppender);
        Configurator.setLevel(logger.getName(), oldLevel);
    }
}
 
Example 10
Source File: SelectionManagerTest.java    From ghidra with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {

	LoggingInitialization.initializeLoggingSystem();
	logger = LogManager.getLogger(SelectionManager.class);
	Configurator.setLevel(logger.getName(), Level.DEBUG);

	logger.trace("\n\nsetUp(): " + testName.getMethodName());

	List<StringRowObject> data = createBasicData();
	model = new NonRowObjectFilterTestTableModel(data);

	// must created the threaded model in the swing thread (it's part of the contract)
	runSwing(() -> threadedModel = new ThreadedTestTableModel());
}
 
Example 11
Source File: LoggerTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void debugChangeLevel() {
    logger.debug("Debug message 1");
    assertEventCount(app.getEvents(), 1);
    Configurator.setLevel(logger.getName(), Level.OFF);
    logger.debug("Debug message 2");
    assertEventCount(app.getEvents(), 1);
    Configurator.setLevel(logger.getName(), Level.DEBUG);
    logger.debug("Debug message 3");
    assertEventCount(app.getEvents(), 2);
}
 
Example 12
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());
	}
}
 
Example 13
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();
}
 
Example 14
Source File: Logging.java    From davos with MIT License 4 votes vote down vote up
@Before
public void before() {
    Configurator.setRootLevel(Level.ERROR);
    Configurator.setLevel("io.linuxserver", Level.ERROR);
}
 
Example 15
Source File: LoggingManager.java    From davos with MIT License 4 votes vote down vote up
public static void enableDebug() {
    Configurator.setLevel("io.linuxserver", Level.DEBUG);
    LOGGER.debug("DEBUG has been enabled");
}
 
Example 16
Source File: ServerStatistics.java    From iaf with Apache License 2.0 4 votes vote down vote up
@PUT
@RolesAllowed({"IbisAdmin", "IbisTester"})
@Path("/server/log")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateLogConfiguration(LinkedHashMap<String, Object> json) throws ApiException {

	Level loglevel = null;
	Boolean logIntermediaryResults = true;
	int maxMessageLength = -1;
	Boolean enableDebugger = null;
	StringBuilder msg = new StringBuilder();

	Logger rootLogger = LogUtil.getRootLogger();

	for (Entry<String, Object> entry : json.entrySet()) {
		String key = entry.getKey();
		Object value = entry.getValue();
		if(key.equalsIgnoreCase("loglevel")) {
			loglevel = Level.toLevel(""+value);
		}
		else if(key.equalsIgnoreCase("logIntermediaryResults")) {
			logIntermediaryResults = Boolean.parseBoolean(""+value);
		}
		else if(key.equalsIgnoreCase("maxMessageLength")) {
			maxMessageLength = Integer.parseInt(""+value);
		}
		else if(key.equalsIgnoreCase("enableDebugger")) {
			enableDebugger = Boolean.parseBoolean(""+value);
		}
	}

	if(loglevel != null && rootLogger.getLevel() != loglevel) {
		Configurator.setLevel(rootLogger.getName(), loglevel);
		msg.append("LogLevel changed from [" + rootLogger.getLevel() + "] to [" + loglevel +"]");
	}

	boolean logIntermediary = AppConstants.getInstance().getBoolean("log.logIntermediaryResults", true);
	if(logIntermediary != logIntermediaryResults) {
		AppConstants.getInstance().put("log.logIntermediaryResults", "" + logIntermediaryResults);

		if(msg.length() > 0)
			msg.append(", logIntermediaryResults from [" + logIntermediary+ "] to [" + logIntermediaryResults + "]");
		else
			msg.append("logIntermediaryResults changed from [" + logIntermediary+ "] to [" + logIntermediaryResults + "]");
	}

	if (maxMessageLength != IbisMaskingLayout.getMaxLength()) {
		if(msg.length() > 0)
			msg.append(", logMaxMessageLength from [" + IbisMaskingLayout.getMaxLength() + "] to [" + maxMessageLength + "]");
		else
			msg.append("logMaxMessageLength changed from [" + IbisMaskingLayout.getMaxLength() + "] to [" + maxMessageLength + "]");
		IbisMaskingLayout.setMaxLength(maxMessageLength);
	}

	if (enableDebugger!=null) {
		boolean testtoolEnabled=AppConstants.getInstance().getBoolean("testtool.enabled", true);
		if (testtoolEnabled!=enableDebugger) {
			AppConstants.getInstance().put("testtool.enabled", "" + enableDebugger);
			DebuggerStatusChangedEvent event = new DebuggerStatusChangedEvent(this, enableDebugger);
			ApplicationEventPublisher applicationEventPublisher = getIbisManager().getApplicationEventPublisher();
			if (applicationEventPublisher!=null) {
				log.info("setting debugger enabled ["+enableDebugger+"]");
				applicationEventPublisher.publishEvent(event);
			} else {
				log.warn("no applicationEventPublisher, cannot set debugger enabled ["+enableDebugger+"]");
			}
		}
		}
	
	
	if(msg.length() > 0) {
		log.warn(msg.toString());
		LogUtil.getLogger("SEC").info(msg.toString());
	}

	return Response.status(Response.Status.NO_CONTENT).build();
}
 
Example 17
Source File: LoggingManager.java    From davos with MIT License 4 votes vote down vote up
public static void setLogLevel(Level level) {
    LOGGER.info("Logging level now set at {}", level);
    Configurator.setLevel("io.linuxserver", level);
}
 
Example 18
Source File: Log4j2LoggingHelper.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public void setLogLevel(String loggerName, LogLevel logLevel)
{
    Configurator.setLevel(loggerName, genericLogLevelToLog4j(logLevel));
}
 
Example 19
Source File: L4jLogProvider.java    From studio with GNU General Public License v3.0 2 votes vote down vote up
/**
 * set a logger's level
 * @param name the name of the logger
 * @param level the level to set
 */
public void setLoggerLevel(String name, String level) {
	Configurator.setLevel(name, Level.valueOf(level));
}
 
Example 20
Source File: LogConfiguration.java    From wekaDeeplearning4j with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Update the log level of a specific logger.
 *
 * @param loggerName Logger name
 * @param level Log level
 */
protected void updateLogLevel(String loggerName, LogLevel level) {
  Configurator.setLevel(loggerName, level.getLevel());
}