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

The following examples show how to use org.apache.logging.log4j.core.config.LoggerConfig. 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: CustomConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor to create the default configuration.
 */
public CustomConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
    super(loggerContext, source);

    setName(CONFIG_NAME);
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
            .setPattern(DEFAULT_PATTERN)
            .setConfiguration(this)
            .build();
    final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    appender.start();
    addAppender(appender);
    final LoggerConfig root = getRootLogger();
    root.addAppender(appender, null, null);

    final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL);
    final Level level = levelName != null && Level.valueOf(levelName) != null ?
            Level.valueOf(levelName) : Level.ERROR;
    root.setLevel(level);
}
 
Example #2
Source File: PropertiesConfigurationTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertiesConfiguration() {
    final Configuration config = context.getConfiguration();
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #3
Source File: Log.java    From Openfire with Apache License 2.0 6 votes vote down vote up
private static void setLogLevel() {
    // SLF4J doesn't provide a hook into the logging implementation. We'll have to do this 'direct', bypassing slf4j.
    final org.apache.logging.log4j.Level newLevel;
    if (traceEnabled) {
        newLevel = org.apache.logging.log4j.Level.TRACE;
    } else if (debugEnabled) {
        newLevel = org.apache.logging.log4j.Level.DEBUG;
    } else {
        newLevel = org.apache.logging.log4j.Level.INFO;
    }
    final LoggerContext ctx = (LoggerContext) LogManager.getContext( false );
    final Configuration config = ctx.getConfiguration();
    final LoggerConfig loggerConfig = config.getLoggerConfig( LogManager.ROOT_LOGGER_NAME );
    loggerConfig.setLevel( newLevel );
    ctx.updateLoggers();  // This causes all Loggers to refetch information from their LoggerConfig.
}
 
Example #4
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Captures the given logger at the given level so it can be displayed directly by this controller.
 *
 * @param name the name
 * @param level the level
 * @param append the append
 * @return the response entity
 */
@RequestMapping(value = "capture/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> capture(@PathVariable("name")
final String name, @PathVariable("level")
final Level level, @RequestParam(value = "append", defaultValue = "false") boolean append) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        if (inMemoryAppenderImpl != null) {
            final Configuration config = ctx.getConfiguration();
            //
            if (name.equalsIgnoreCase(config.getLoggerConfig(name).getName())) {
                config.removeLogger(name);
            }
            //
            AppenderRef ref = AppenderRef.createAppenderRef("InMemoryAppenderImplAppenderRef", level, null);
            AppenderRef[] refs = new AppenderRef[] {ref};
            LoggerConfig loggerConfig = LoggerConfig.createLogger(append, level, name, "true", refs, null, config, null);
            loggerConfig.addAppender(inMemoryAppenderImpl, null, null);
            config.addLogger(name, loggerConfig);
            ctx.updateLoggers();
        }
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example #5
Source File: ApplicationSupport.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
public static void configureLogging() {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Properties properties = PropertiesSupport.loadProperties();

    properties.entrySet().stream()
        .filter(entry -> entry.getKey() instanceof String)
        .filter(entry -> entry.getValue() instanceof String)
        .filter(entry -> ((String)entry.getKey()).startsWith(Constants.LOGGING_LEVEL_PREFIX))
        .forEach(entry -> {
            String key = (String)entry.getKey();
            String val = (String)entry.getValue();

            String logger = key.substring(Constants.LOGGING_LEVEL_PREFIX.length());
            Level level = Level.getLevel(val);
            LoggerConfig config = new LoggerConfig(logger, level, true);

            ctx.getConfiguration().addLogger(logger, config);
        }
    );
}
 
Example #6
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Sets the.
 *
 * @param name
 *        the name
 * @param level
 *        the level
 * @return the response entity
 */
@RequestMapping(value = "set/{name}/{level}", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> set(@PathVariable("name")
final String name, @PathVariable("level")
final Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(name);
        if (name.equalsIgnoreCase(loggerConfig.getName())) {
            loggerConfig.setLevel(level);
        } else {
            LoggerConfig newloggerConfig = new LoggerConfig(name, level, true);
            config.addLogger(name, newloggerConfig);
        }
        ctx.updateLoggers();
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example #7
Source File: S2STestService.java    From Openfire with Apache License 2.0 6 votes vote down vote up
String addAppender(final Writer writer) {
    final String name = "openfire-s2s-test-appender-" + StringUtils.randomString( 10 );
    final LoggerContext context = LoggerContext.getContext(false);
    final Configuration config = context.getConfiguration();
    final PatternLayout layout = PatternLayout.createDefaultLayout(config);
    final Appender appender = WriterAppender.createAppender(layout, null, writer, name, false, true);
    appender.start();
    config.addAppender(appender);

    final Level level = null;
    final Filter filter = null;
    for (final LoggerConfig loggerConfig : config.getLoggers().values()) {
        loggerConfig.addAppender(appender, level, filter);
    }
    config.getRootLogger().addAppender(appender, level, filter);
    return name;
}
 
Example #8
Source File: MyServiceUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testProgrammaticConfig() {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();

    PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%d{HH:mm:ss.SSS} %level %msg%n").build();

    Appender appender = FileAppender.newBuilder().setConfiguration(config).withName("programmaticFileAppender").withLayout(layout).withFileName("java.log").build();
    appender.start();
    config.addAppender(appender);
    AppenderRef ref = AppenderRef.createAppenderRef("programmaticFileAppender", null, null);
    AppenderRef[] refs = new AppenderRef[] { ref };

    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "programmaticLogger", "true", refs, null, config, null);

    loggerConfig.addAppender(appender, null, null);
    config.addLogger("programmaticLogger", loggerConfig);
    ctx.updateLoggers();

    Logger pLogger = LogManager.getLogger("programmaticLogger");
    pLogger.info("Programmatic Logger Message");
}
 
Example #9
Source File: AugmentedLRLossTest.java    From pyramid with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception{

        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
        loggerConfig.setLevel(Level.DEBUG);
        ctx.updateLoggers();

        MultiLabelClfDataSet dataSet = TRECFormat.loadMultiLabelClfDataSet(new File(DATASETS, "scene/train"),
                DataSetType.ML_CLF_DENSE, true);
        MultiLabelClfDataSet testSet = TRECFormat.loadMultiLabelClfDataSet(new File(DATASETS, "scene/test"),
                DataSetType.ML_CLF_DENSE, true);
        AugmentedLR augmentedLR = new AugmentedLR(dataSet.getNumFeatures(), 1);
        double[][] gammas = new double[dataSet.getNumDataPoints()][1];
        for (int i=0;i<dataSet.getNumDataPoints();i++){
            gammas[i][0]=1;
        }
        AugmentedLRLoss loss = new AugmentedLRLoss(dataSet, 0, gammas, augmentedLR, 1, 1);
        LBFGS lbfgs = new LBFGS(loss);

        for (int i=0;i<100;i++){
            lbfgs.iterate();
            System.out.println(loss.getValue());
        }

    }
 
Example #10
Source File: RollingFilePropertiesTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertiesConfiguration() {
    final Configuration config = context.getConfiguration();
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 3);
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #11
Source File: PropertiesConfigurationTrailingSpaceOnLevelTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertiesConfiguration() {
    final Configuration config = context.getConfiguration();
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final Logger logger = LogManager.getLogger(getClass());

    assertEquals("Incorrect level " + logger.getLevel(), Level.DEBUG, logger.getLevel());

    logger.debug("Welcome to Log4j!");
}
 
Example #12
Source File: LoggingMixin.java    From picocli with Apache License 2.0 6 votes vote down vote up
/**
 * Configures the Log4j2 console appender(s), using the specified verbosity:
 * <ul>
 *   <li>{@code -vvv} : enable TRACE level</li>
 *   <li>{@code -vv} : enable DEBUG level</li>
 *   <li>{@code -v} : enable INFO level</li>
 *   <li>(not specified) : enable WARN level</li>
 * </ul>
 */
public void configureLoggers() {
    Level level = getTopLevelCommandLoggingMixin(mixee).calcLogLevel();

    LoggerContext loggerContext = LoggerContext.getContext(false);
    LoggerConfig rootConfig = loggerContext.getConfiguration().getRootLogger();
    for (Appender appender : rootConfig.getAppenders().values()) {
        if (appender instanceof ConsoleAppender) {
            rootConfig.removeAppender(appender.getName());
            rootConfig.addAppender(appender, level, null);
        }
    }
    if (rootConfig.getLevel().isMoreSpecificThan(level)) {
        rootConfig.setLevel(level);
    }
    loggerContext.updateLoggers(); // apply the changes
}
 
Example #13
Source File: PropertiesConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void configureRoot(Properties props) {
    String effectiveFrefix = ROOT_LOGGER_PREFIX;
    String value = OptionConverter.findAndSubst(ROOT_LOGGER_PREFIX, props);

    if (value == null) {
        value = OptionConverter.findAndSubst(ROOT_CATEGORY_PREFIX, props);
        effectiveFrefix = ROOT_CATEGORY_PREFIX;
    }

    if (value == null) {
        LOGGER.debug("Could not find root logger information. Is this OK?");
    } else {
        LoggerConfig root = getRootLogger();
        parseLogger(props, root, effectiveFrefix, INTERNAL_ROOT_NAME, value);
    }
}
 
Example #14
Source File: Main.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private static void addFileAppender(String logFilename) throws IOException {
  File logFile = new File(logFilename);
  Object ctx = LogManager.getContext(false);
  if (ctx instanceof LoggerContext) {
    try (LoggerContext context = (LoggerContext) ctx) {
      Configuration configuration = context.getConfiguration();
      LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
      FileAppender fileAppender =
          FileAppender.newBuilder()
              .setName("file")
              .setLayout(
                  PatternLayout.newBuilder()
                      .withPattern("[%d][%-5.-5p][%-14.-14c{1}:%4L] %-22.-22M - %m%n")
                      .build())
              .withFileName(logFile.getCanonicalPath())
              .build();
      configuration.addAppender(fileAppender);
      loggerConfig.addAppender(fileAppender, Level.ERROR, null);
      context.updateLoggers();
    }
  }
}
 
Example #15
Source File: Server.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static void registerLoggerConfigs(final LoggerContext ctx, final MBeanServer mbs, final Executor executor)
        throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException {

    final Map<String, LoggerConfig> map = ctx.getConfiguration().getLoggers();
    for (final String name : map.keySet()) {
        final LoggerConfig cfg = map.get(name);
        final LoggerConfigAdmin mbean = new LoggerConfigAdmin(ctx, cfg);
        register(mbs, mbean, mbean.getObjectName());

        if (cfg instanceof AsyncLoggerConfig) {
            final AsyncLoggerConfig async = (AsyncLoggerConfig) cfg;
            final RingBufferAdmin rbmbean = async.createRingBufferAdmin(ctx.getName());
            register(mbs, rbmbean, rbmbean.getObjectName());
        }
    }
}
 
Example #16
Source File: StartupLoggingUtils.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Dynamically change log4j log level through property solr.log.level
 * @param logLevel String with level, should be one of the supported, e.g. TRACE, DEBUG, INFO, WARN, ERROR...
 * @return true if ok or else false if something happened, e.g. log4j classes were not in classpath
 */
@SuppressForbidden(reason = "Legitimate log4j2 access")
public static boolean changeLogLevel(String logLevel) {
  try {
    if (!isLog4jActive()) {
      logNotSupported("Could not change log level.");
      return false;
    }

    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getRootLogger();
    loggerConfig.setLevel(Level.toLevel(logLevel, Level.INFO));
    ctx.updateLoggers();
    return true;
  } catch (Exception e) {
    logNotSupported("Could not change log level.");
    return false;
  }
}
 
Example #17
Source File: LoggerUpdateTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void resetLevel() {
    final org.apache.logging.log4j.Logger logger = context.getLogger("com.apache.test");
    logger.traceEntry();
    List<LogEvent> events = app.getEvents();
    assertEquals("Incorrect number of events. Expected 1, actual " + events.size(), 1, events.size());
    app.clear();
    final LoggerContext ctx = LoggerContext.getContext(false);
    final Configuration config = ctx.getConfiguration();
    final LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    /* You could also specify the actual logger name as below and it will return the LoggerConfig used by the Logger.
       LoggerConfig loggerConfig = getLoggerConfig("com.apache.test");
    */
    loggerConfig.setLevel(Level.DEBUG);
    ctx.updateLoggers();  // This causes all Loggers to refetch information from their LoggerConfig.
    logger.traceEntry();
    events = app.getEvents();
    assertEquals("Incorrect number of events. Expected 0, actual " + events.size(), 0, events.size());
}
 
Example #18
Source File: LogEventFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public Statement apply(final Statement base, final Description description) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            System.setProperty(Constants.LOG4J_LOG_EVENT_FACTORY, TestLogEventFactory.class.getName());
            resetLogEventFactory(new TestLogEventFactory());
            try {
                base.evaluate();
            } finally {
                System.clearProperty(Constants.LOG4J_LOG_EVENT_FACTORY);
                resetLogEventFactory(new DefaultLogEventFactory());
            }
        }

        private void resetLogEventFactory(final LogEventFactory logEventFactory) throws IllegalAccessException {
            final Field field = FieldUtils.getField(LoggerConfig.class, "LOG_EVENT_FACTORY", true);
            FieldUtils.removeFinalModifier(field, true);
            FieldUtils.writeStaticField(field, logEventFactory, false);
        }
    };
}
 
Example #19
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 #20
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 #21
Source File: PropertiesConfigurationRootLoggerOnlyTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropertiesConfiguration() {
    final Configuration config = context.getConfiguration();
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 1);
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
 
Example #22
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Used internally to parse the children of a LoggerConfig element.
 */
private void parseChildrenOfLoggerElement(Element catElement, LoggerConfig loggerConfig, boolean isRoot) {

    final PropertySetter propSetter = new PropertySetter(loggerConfig);
    loggerConfig.getAppenderRefs().clear();
    forEachElement(catElement.getChildNodes(), (currentElement) -> {
        switch (currentElement.getTagName()) {
            case APPENDER_REF_TAG: {
                Appender appender = findAppenderByReference(currentElement);
                String refName = subst(currentElement.getAttribute(REF_ATTR));
                if (appender != null) {
                    LOGGER.debug("Adding appender named [{}] to loggerConfig [{}].", refName,
                            loggerConfig.getName());
                    loggerConfig.addAppender(configuration.getAppender(refName), null, null);
                } else {
                    LOGGER.debug("Appender named [{}}] not found.", refName);
                }
                break;
            }
            case LEVEL_TAG: case PRIORITY_TAG: {
                parseLevel(currentElement, loggerConfig, isRoot);
                break;
            }
            case PARAM_TAG: {
                setParameter(currentElement, propSetter);
                break;
            }
            default: {
                quietParseUnrecognizedElement(loggerConfig, currentElement, props);
            }
        }
    });
    propSetter.activate();
}
 
Example #23
Source File: MyXMLConfiguration.java    From tutorials with MIT License 5 votes vote down vote up
@Override
protected void doConfigure() {
    super.doConfigure();
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig("com");
    final Layout layout = PatternLayout.createLayout("[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n", null, config, null, null, false, false, null, null);
    Appender appender = FileAppender.createAppender("target/test.log", "false", "false", "File", "true", "false", "false", "4000", layout, null, "false", null, config);
    loggerConfig.addAppender(appender, Level.DEBUG, null);
    addAppender(appender);
}
 
Example #24
Source File: LogUtil.java    From fix-orchestra with Apache License 2.0 5 votes vote down vote up
public static Logger initializeDefaultLogger(Level level, Class<?> clazz) {
  final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  final Configuration config = ctx.getConfiguration();
  final ConsoleAppender appender = ConsoleAppender.newBuilder().setName("Console").build();
  config.addAppender(appender);
  final AppenderRef ref = AppenderRef.createAppenderRef("Console", level, null);
  final AppenderRef[] refs = new AppenderRef[] {ref};
  final LoggerConfig loggerConfig =
      LoggerConfig.createLogger(true, level, clazz.getName(), null, refs, null, config, null);
  config.addLogger(clazz.getName(), loggerConfig);
  ctx.updateLoggers();
  return LogManager.getLogger(clazz);
}
 
Example #25
Source File: ConfigurationTestUtils.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
static void updateLoggers(final Appender appender, final Configuration config) {
    final Level level = null;
    final Filter filter = null;
    for (final LoggerConfig loggerConfig : config.getLoggers().values()) {
        loggerConfig.addAppender(appender, level, filter);
    }
    config.getRootLogger().addAppender(appender, level, filter);
}
 
Example #26
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Layout<?> testFile(final String configResource) throws Exception {
	final Configuration configuration = getConfiguration(configResource);
	final FileAppender appender = configuration.getAppender("File");
	assertNotNull(appender);
	assertEquals("target/mylog.txt", appender.getFileName());
	//
	final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
	assertNotNull(loggerConfig);
	assertEquals(Level.DEBUG, loggerConfig.getLevel());
	configuration.start();
	configuration.stop();
	return appender.getLayout();
}
 
Example #27
Source File: Log4j2LoggerAdapter.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void setLevel(Level level) {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(toLog4jLevel(level));
    ctx.updateLoggers();
}
 
Example #28
Source File: TestUtil.java    From unleash-client-java with Apache License 2.0 5 votes vote down vote up
public static void setLogLevel(Level level) {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(level);
    ctx.updateLoggers();  // This causes all Loggers to refetch information from their LoggerConfig.
}
 
Example #29
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Used internally to parse the children of a LoggerConfig element.
 */
private void parseChildrenOfLoggerElement(Element catElement, LoggerConfig loggerConfig, boolean isRoot) {

    final PropertySetter propSetter = new PropertySetter(loggerConfig);
    loggerConfig.getAppenderRefs().clear();
    forEachElement(catElement.getChildNodes(), (currentElement) -> {
        switch (currentElement.getTagName()) {
            case APPENDER_REF_TAG: {
                Appender appender = findAppenderByReference(currentElement);
                String refName = subst(currentElement.getAttribute(REF_ATTR));
                if (appender != null) {
                    LOGGER.debug("Adding appender named [{}] to loggerConfig [{}].", refName,
                            loggerConfig.getName());
                    loggerConfig.addAppender(getAppender(refName), null, null);
                } else {
                    LOGGER.debug("Appender named [{}}] not found.", refName);
                }
                break;
            }
            case LEVEL_TAG: case PRIORITY_TAG: {
                parseLevel(currentElement, loggerConfig, isRoot);
                break;
            }
            case PARAM_TAG: {
                setParameter(currentElement, propSetter);
                break;
            }
            default: {
                quietParseUnrecognizedElement(loggerConfig, currentElement, props);
            }
        }
    });
    propSetter.activate();
}
 
Example #30
Source File: JumbuneAgent.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void turnLoggingLevelToDebug(String verboseMode) {
	LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	Configuration config = ctx.getConfiguration();
	LoggerConfig loggerConfig = config.getLoggerConfig(ROLLING_FILE_APPENDER);
	loggerConfig.setLevel(Level.DEBUG);
	ctx.updateLoggers();
	LOGGER.debug("logging level changed to [DEBUG]");
}