Java Code Examples for org.apache.logging.log4j.core.LoggerContext#getConfiguration()

The following examples show how to use org.apache.logging.log4j.core.LoggerContext#getConfiguration() . 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: 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 2
Source File: TestLogLevelAnnotations.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Directly test the methods in the {@link LogLevel} annotation class
 */
@LogLevel("org.apache.solr.bogus_logger.MethodLogLevel=TRACE")
public void testWhiteBoxMethods() {
  final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  final Configuration config = ctx.getConfiguration();

  final Map<String,Level> oldLevels = LogLevel.Configurer.setLevels(bogus_logger_prefix + "=TRACE");
  //
  assertEquals(oldLevels.toString(), 1, oldLevels.size());
  assertNull(oldLevels.get(bogus_logger_prefix));
  //
  assertEquals(Level.TRACE, config.getLoggerConfig(bogus_logger_prefix).getLevel());
  assertEquals(Level.TRACE, LogManager.getLogger(bogus_logger_prefix).getLevel());
  
  // restore (to 'unset' values)...
  LogLevel.Configurer.restoreLogLevels(oldLevels);
  assertEquals(bogus_logger_prefix
               + " should have had it's config unset; should now return the 'root' LoggerConfig",
               config.getRootLogger(),
               config.getLoggerConfig(bogus_logger_prefix));
  assertEquals(DEFAULT_LOG_LEVEL, LogManager.getLogger(bogus_logger_prefix).getLevel());
  
}
 
Example 3
Source File: OutputStreamAppenderTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that the code pattern we use to add an appender on the fly
 * works with a basic appender that is not the new OutputStream appender or
 * new Writer appender.
 */
@Test
public void testUpdatePatternWithFileAppender() {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    // @formatter:off
    final Appender appender = FileAppender.newBuilder()
        .setFileName("target/" + getClass().getName() + ".log")
        .setAppend(false)
        .setName("File")
        .setIgnoreExceptions(false)
        .setBufferedIo(false)
        .setBufferSize(4000)
        .setConfiguration(config)
        .build();
    // @formatter:on
    appender.start();
    config.addAppender(appender);
    ConfigurationTestUtils.updateLoggers(appender, config);
    LogManager.getLogger().error("FOO MSG");
}
 
Example 4
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 5
Source File: ActorLogger.java    From actor4j-core with Apache License 2.0 5 votes vote down vote up
private ActorLogger() {
	loggerContext = (LoggerContext) LogManager.getContext(LogManager.class.getClassLoader(), false);
	Configuration config = loggerContext.getConfiguration();

	Appender systemConsoleAppender = ConsoleAppender.newBuilder()
		.setName(SYSTEM_CONSOLE_APPENDER_NAME)
		.setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_SYSTEM).build())
		.setConfiguration(config)
		.build();
	systemConsoleAppender.start();
    AppenderRef[] systemAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(SYSTEM_CONSOLE_APPENDER_NAME, null, null)};
    systemLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, SYSTEM_LOGGER_NAME, "true", systemAppenderRefs, null, config, null);
    systemLoggerConfig.addAppender(systemConsoleAppender, null, null);
    
    Appender userConsoleAppender = ConsoleAppender.newBuilder()
		.setName(USER_CONSOLE_APPENDER_NAME)
		.setLayout(PatternLayout.newBuilder().withPattern(LAYOUT_CONSOLE_USER).build())
		.setConfiguration(config)
		.build();
	userConsoleAppender.start();
	AppenderRef[] userAppenderRefs = new AppenderRef[]{AppenderRef.createAppenderRef(USER_CONSOLE_APPENDER_NAME, null, null)};
	userLoggerConfig = LoggerConfig.createLogger(false, Level.DEBUG, USER_LOGGER_NAME, "true", userAppenderRefs, null, config, null);
	userLoggerConfig.addAppender(userConsoleAppender, null, null);

    config.addAppender(systemConsoleAppender);
    config.addAppender(userConsoleAppender);
    config.addLogger(SYSTEM_LOGGER_NAME, systemLoggerConfig);
    config.addLogger(USER_LOGGER_NAME, userLoggerConfig);
	loggerContext.updateLoggers(config);
}
 
Example 6
Source File: Config.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
private void setLogLevel(final String logLevel) {
  Object ctx = LogManager.getContext(false);
  if (ctx instanceof LoggerContext) {
    LoggerContext context = (LoggerContext) ctx;
    Level level = Level.toLevel(logLevel);
    Configuration configuration = context.getConfiguration();
    LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(level);
    context.updateLoggers();
    this.debug = !logLevel.toLowerCase().equals("info");
  }
}
 
Example 7
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
private LogResponse listLoggers(final LoggerContext ctx) {
    LogResponse logResponse = new LogResponse();
    List<LogSpecification> result = new ArrayList<>();
    logResponse.setSpecs(result);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        config.getLoggers().forEach(
            (name, configuration) -> result.add(new LogSpecification(StringUtils.hasText(name) ? name : "Root", configuration.getLevel().name(),
                configuration.getAppenderRefs().stream().map(AppenderRef::getRef).collect(Collectors.toList()))));
    }
    return logResponse;

}
 
Example 8
Source File: SpectatorAppender.java    From spectator with Apache License 2.0 5 votes vote down vote up
private static void addToRootLogger(final Appender appender) {
  LoggerContext context = (LoggerContext) LogManager.getContext(false);
  Configuration config = context.getConfiguration();
  LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
  loggerConfig.addAppender(appender, Level.ALL, null);
  context.updateLoggers(config);
}
 
Example 9
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]");
}
 
Example 10
Source File: MonitoringModule.java    From curiostack with MIT License 5 votes vote down vote up
private static void configureLogMetrics() {
  InstrumentedAppender appender = InstrumentedAppender.createAppender("PROMETHEUS");
  appender.start();
  LoggerContext context = (LoggerContext) LogManager.getContext(false);
  Configuration config = context.getConfiguration();
  config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).addAppender(appender, null, null);
  context.updateLoggers(config);
}
 
Example 11
Source File: LoggingUtils.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void setLog4JLoggingLevel(Log.LogLevel verbosity) {
    // Now establish the logging level used by log4j by propagating the requested
    // logging level to all loggers associated with our logging configuration.
    final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    final Configuration loggerContextConfig = loggerContext.getConfiguration();
    final String contextClassName = LoggingUtils.class.getName();
    final LoggerConfig loggerConfig = loggerContextConfig.getLoggerConfig(contextClassName);

    loggerConfig.setLevel(levelToLog4jLevel(verbosity));
    loggerContext.updateLoggers();
}
 
Example 12
Source File: XmlConfigurationPropsTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithConfigProp() {
    System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, CONFIG);
    System.setProperty("log4j.level", "warn");
    try {
        final LoggerContext ctx = LoggerContext.getContext();
        ctx.reconfigure();
        final Configuration config = ctx.getConfiguration();
        assertTrue("Configuration is not an XmlConfiguration", config instanceof XmlConfiguration);
    } finally {
        System.clearProperty("log4j.level");

    }
}
 
Example 13
Source File: Nukkit.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public static void setLogLevel(Level level) {
    Preconditions.checkNotNull(level, "level");
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration log4jConfig = ctx.getConfiguration();
    LoggerConfig loggerConfig = log4jConfig.getLoggerConfig(org.apache.logging.log4j.LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(level);
    ctx.updateLoggers();
}
 
Example 14
Source File: The5zigMod.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
/**
 * Configures the main logger.
 */
private static void setupLogger() {
	LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	org.apache.logging.log4j.core.config.Configuration config = ctx.getConfiguration();
	LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
	if (DEBUG) {
		loggerConfig.setLevel(Level.DEBUG);
	}
	ctx.updateLoggers();
	logger.debug("Debug Mode ENABLED!");
}
 
Example 15
Source File: LoggerTest.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
private static void setLogLevel(Level logLevel) {
  LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
  Configuration configuration = loggerContext.getConfiguration();
  configuration.getLoggerConfig(LOGGER_NAME).setLevel(logLevel);
  loggerContext.updateLoggers();
}
 
Example 16
Source File: Main.java    From TweetwallFX with MIT License 4 votes vote down vote up
@Override
public void start(Stage primaryStage) {
    BorderPane borderPane = new BorderPane();
    Scene scene = new Scene(borderPane, 1920, 1280);
    borderPane.getStyleClass().add("splash");

    final TweetwallSettings tweetwallSettings
            = Configuration.getInstance().getConfigTyped(TweetwallSettings.CONFIG_KEY, TweetwallSettings.class);

    Optional.ofNullable(tweetwallSettings.getStylesheetResource())
            .map(ClassLoader.getSystemClassLoader()::getResource)
            .map(java.net.URL::toExternalForm)
            .ifPresent(scene.getStylesheets()::add);
    Optional.ofNullable(tweetwallSettings.getStylesheetFile())
            .ifPresent(scene.getStylesheets()::add);

    StringPropertyAppender spa = new StringPropertyAppender();

    LoggerContext context = LoggerContext.getContext(false);
    org.apache.logging.log4j.core.config.Configuration config = context.getConfiguration();
    spa.start();
    LoggerConfig slc = config.getLoggerConfig(LOGGER.getName());
    slc.setLevel(Level.TRACE);
    slc.addAppender(spa, Level.TRACE, null);

    HBox statusLineHost = new HBox();
    Text statusLineText = new Text();
    statusLineText.getStyleClass().addAll("statusline");
    statusLineText.textProperty().bind(spa.stringProperty());
    statusLineHost.getChildren().add(statusLineText);

    final TagTweets tweetsTask = new TagTweets(borderPane);
    Platform.runLater(tweetsTask::start);

    scene.setOnKeyTyped((KeyEvent event) -> {
        if (event.isMetaDown() && event.getCharacter().equals("d")) {
            if (null == statusLineHost.getParent()) {
                borderPane.setBottom(statusLineHost);
            } else {
                borderPane.getChildren().remove(statusLineHost);
            }
        }
    });

    primaryStage.setTitle(tweetwallSettings.getTitle());
    primaryStage.setScene(scene);

    primaryStage.show();
    primaryStage.setFullScreen(!Boolean.getBoolean("org.tweetwallfx.disable-full-screen"));
}
 
Example 17
Source File: CloudStorageLoggerFactory.java    From ambari-logsearch with Apache License 2.0 4 votes vote down vote up
public static Logger createLogger(Input input, LoggerContext loggerContext, LogFeederProps logFeederProps) {
  boolean useJsonFormat = logFeederProps.isCloudStorageUseFilters();
  String type = input.getLogType().replace(LogFeederConstants.CLOUD_PREFIX, "");
  String uniqueThreadName = input.getThread().getName();
  Configuration config = loggerContext.getConfiguration();
  String baseDir = logFeederProps.getRolloverConfig().getRolloverArchiveBaseDir();
  String destination = logFeederProps.getCloudStorageDestination().getText();
  String clusterHostnameBaseDir = Paths.get(baseDir, destination, logFeederProps.getClusterName(), LogFeederUtil.hostName).toFile().getAbsolutePath();
  String activeLogDir = Paths.get(clusterHostnameBaseDir, ACTIVE_FOLDER, type).toFile().getAbsolutePath();
  String archiveLogDir = Paths.get(clusterHostnameBaseDir, ARCHIVED_FOLDER, type).toFile().getAbsolutePath();

  boolean useGzip = logFeederProps.getRolloverConfig().isUseGzip();
  final String archiveFilePattern;
  if (useJsonFormat) {
    archiveFilePattern = useGzip ? JSON_DATE_PATTERN_SUFFIX_GZ : JSON_DATE_PATTERN_SUFFIX;
  } else {
    archiveFilePattern = useGzip ? DATE_PATTERN_SUFFIX_GZ : DATE_PATTERN_SUFFIX;
  }

  String logSuffix = useJsonFormat ? ".json" : ".log";
  String fileName = String.join(File.separator, activeLogDir, type + logSuffix);
  String filePattern = String.join(File.separator, archiveLogDir, type + archiveFilePattern);
  PatternLayout layout = PatternLayout.newBuilder()
    .withPattern(PatternLayout.DEFAULT_CONVERSION_PATTERN).build();

  String rolloverSize = logFeederProps.getRolloverConfig().getRolloverSize().toString() + logFeederProps.getRolloverConfig().getRolloverSizeFormat();
  SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy.createPolicy(rolloverSize);

  final Integer thresholdMin = logFeederProps.getRolloverConfig().getRolloverThresholdTimeMins();
  final Integer thresholdInterval = thresholdMin * 60000; // 1 min = 60000 milliseconds

  TimeBasedTriggeringPolicy timeBasedTriggeringPolicy = TimeBasedTriggeringPolicy.newBuilder()
    .withInterval(thresholdInterval)
    .build();

  final CompositeTriggeringPolicy compositeTriggeringPolicy;

  if (logFeederProps.getRolloverConfig().isRolloverOnStartup()) {
    OnStartupTriggeringPolicy onStartupTriggeringPolicy = OnStartupTriggeringPolicy.createPolicy(1);
    compositeTriggeringPolicy = CompositeTriggeringPolicy
      .createPolicy(sizeBasedTriggeringPolicy, timeBasedTriggeringPolicy, onStartupTriggeringPolicy);
  } else {
    compositeTriggeringPolicy = CompositeTriggeringPolicy
      .createPolicy(sizeBasedTriggeringPolicy, timeBasedTriggeringPolicy);
  }

  DefaultRolloverStrategy defaultRolloverStrategy = DefaultRolloverStrategy.newBuilder()
    .withMax(String.valueOf(logFeederProps.getRolloverConfig().getRolloverMaxBackupFiles()))
    .build();

  boolean immediateFlush = logFeederProps.getRolloverConfig().isImmediateFlush();
  RollingFileAppender appender = RollingFileAppender.newBuilder()
    .withFileName(fileName)
    .withFilePattern(filePattern)
    .withLayout(layout)
    .withName(type)
    .withPolicy(compositeTriggeringPolicy)
    .withStrategy(defaultRolloverStrategy)
    .withImmediateFlush(immediateFlush)
    .build();

  appender.start();
  config.addAppender(appender);

  AppenderRef ref = AppenderRef.createAppenderRef(type, null, null);
  AppenderRef[] refs = new AppenderRef[] {ref};

  LoggerConfig loggerConfig = LoggerConfig
    .createLogger(false, Level.ALL, input.getThread().getName(),
      "true", refs, null, config, null);
  loggerConfig.addAppender(appender, null, null);
  config.addLogger(uniqueThreadName, loggerConfig);
  loggerContext.updateLoggers();
  return loggerContext.getLogger(uniqueThreadName);
}
 
Example 18
Source File: CLogOut.java    From TweetwallFX with MIT License 4 votes vote down vote up
private CLogOut() {
    final ByteArrayOutputStream stdStream = new ByteArrayOutputStream() {
        @Override
        public synchronized void flush() throws IOException {
            String theString = toString("UTF-8");

            /* OK:
             Establishing connection.
             Twitter Stream consumer-1[Establishing connection]
             Connection established.
             Receiving status stream.
             Twitter Stream consumer-1[Receiving stream]
             *Received:{...}
             Twitter Stream consumer-1[Disposing thread]

             */

            /* WRONG:
             Establishing connection.
             Twitter Stream consumer-1[Establishing connection]
             Exceeded connection limit for user
             420
             Waiting for 10000 milliseconds
             Twitter Stream consumer-1[Disposing thread]

             */
            Platform.runLater(() -> {
                if (theString.startsWith("Establishing connection")) {
                    message.set("Establishing connection...\n Please, wait a few seconds");
                } else if (theString.startsWith("Receiving status stream")) {
                    message.set("Receiving tweets!! \n Press stop button to stop the search");
                } else if (theString.startsWith("Exceeded connection limit")) {
                    message.set("Exceeded connection limit...");
                } else if (theString.startsWith("Waiting for ")) {
                    message.set(theString + " or press stop button to stop the search");
                } else if (theString.contains("Disposing thread")) {
                    message.set("The search has finished");
                }
            });
            System.out.print("***** " + theString);
            reset();
        }
    };

    LoggerContext context = LoggerContext.getContext(false);
    Configuration config = context.getConfiguration();
    PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%m%n").build();
    Appender appender = WriterAppender.newBuilder().setLayout(layout).setTarget(new OutputStreamWriter(stdStream, StandardCharsets.UTF_8)).build();
    appender.start();
    config.addAppender(appender);

    updateLoggers(appender, config);
}
 
Example 19
Source File: LoggerTest.java    From feign-reactive with Apache License 2.0 4 votes vote down vote up
private static LoggerConfig getLoggerConfig() {
  LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
  Configuration configuration = loggerContext.getConfiguration();
  configuration.addLogger(LOGGER_NAME, new LoggerConfig());
  return configuration.getLoggerConfig(LOGGER_NAME);
}
 
Example 20
Source File: JiraLog4j2_2134Test.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testRefreshDeprecatedApis() {
	Logger log = LogManager.getLogger(this.getClass());
	final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	final Configuration config = ctx.getConfiguration();
	PatternLayout layout = PatternLayout.newBuilder()
	        .setPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN)
	        .setPatternSelector(null)
	        .setConfiguration(config)
	        .setRegexReplacement(null)
	        .setCharset(null)
	        .setAlwaysWriteExceptions(false)
	        .setNoConsoleNoAnsi(false)
	        .setHeader(null)
	        .setFooter(null)
	        .build();
	// @formatter:off
	Appender appender = FileAppender.newBuilder()
	        .setFileName("target/test.log")
	        .setAppend(false)
	        .setLocking(false)
	        .setName("File")
	        .setImmediateFlush(true)
	        .setIgnoreExceptions(false)
	        .setBufferedIo(false)
	        .setBufferSize(4000)
	        .setLayout(layout)
	        .setAdvertise(false)
	        .setConfiguration(config)
	        .build();
       // @formatter:on
	appender.start();
	config.addAppender(appender);
	AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
	AppenderRef[] refs = new AppenderRef[] { ref };
	LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "testlog4j2refresh", "true", refs,
			null, config, null);
	loggerConfig.addAppender(appender, null, null);
	config.addLogger("testlog4j2refresh", loggerConfig);
	ctx.stop();
	ctx.start(config);

	log.error("Info message");
}