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

The following examples show how to use org.apache.logging.log4j.core.LoggerContext#updateLoggers() . 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: Log4j2MetricsTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void noDuplicateLoggingCountWhenMultipleNonAdditiveLoggersShareConfig() {
    LoggerContext loggerContext = new LoggerContext("test");

    LoggerConfig loggerConfig = new LoggerConfig("com.test", Level.INFO, false);
    Configuration configuration = loggerContext.getConfiguration();
    configuration.addLogger("com.test", loggerConfig);
    loggerContext.setConfiguration(configuration);
    loggerContext.updateLoggers();

    Logger logger1 = loggerContext.getLogger("com.test.log1");
    loggerContext.getLogger("com.test.log2");

    new Log4j2Metrics(emptyList(), loggerContext).bindTo(registry);

    assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(0);
    logger1.info("Hello, world!");
    assertThat(registry.get("log4j2.events").tags("level", "info").counter().count()).isEqualTo(1);
}
 
Example 3
Source File: Log4j2Watcher.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void registerListener(ListenerConfig cfg) {
  if (history != null)
    throw new IllegalStateException("History already registered");

  history = new CircularList<LogEvent>(cfg.size);

  Level threshold = (cfg.threshold != null) ? Level.toLevel(cfg.threshold) : Level.WARN;
  ThresholdFilter filter = ThresholdFilter.createFilter(threshold, Filter.Result.ACCEPT, Filter.Result.DENY);

  // If there's already an appender like this, remove it
  LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
  LoggerConfig config = getLoggerConfig(ctx, LoggerInfo.ROOT_NAME);

  appender = new Log4j2Appender(this, filter, threshold); // "Log4j2WatcherAppender"

  config.removeAppender(appender.getName());

  if (!appender.isStarted())
    appender.start();

  config.addAppender(appender, threshold, filter);
  ctx.updateLoggers();
}
 
Example 4
Source File: Configurator.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the levels of <code>parentLogger</code> and all 'child' loggers to the given <code>level</code>.
 * @param parentLogger the parent logger
 * @param level the new level
 */
public static void setAllLevels(final String parentLogger, final Level level) {
    // 1) get logger config
    // 2) if exact match, use it, if not, create it.
    // 3) set level on logger config
    // 4) update child logger configs with level
    // 5) update loggers
    final LoggerContext loggerContext = LoggerContext.getContext(false);
    final Configuration config = loggerContext.getConfiguration();
    boolean set = setLevel(parentLogger, level, config);
    for (final Map.Entry<String, LoggerConfig> entry : config.getLoggers().entrySet()) {
        if (entry.getKey().startsWith(parentLogger)) {
            set |= setLevel(entry.getValue(), level);
        }
    }
    if (set) {
        loggerContext.updateLoggers();
    }
}
 
Example 5
Source File: Config.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
private Config() {
  this.c = ConfigFactory.load();
  final String logLevel = c.getString("log-level");
  Level level = Level.toLevel(logLevel);
  final String lowerLevel = logLevel.toLowerCase();

  if (lowerLevel.equals("debug") || lowerLevel.equals("telemetry")) {
    this.debug = true;
  }
  // force change
  Object ctx = LogManager.getContext(false);
  if (ctx instanceof LoggerContext) {
    LoggerContext context = (LoggerContext) ctx;
    Configuration configuration = context.getConfiguration();
    LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(level);
    context.updateLoggers();
  }
}
 
Example 6
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Frees the given logger from the appender used to be displayed directly by this controller.
 *
 * @param name the name
 * @return the response entity
 */
@RequestMapping(value = "free/{name}/", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> free(@PathVariable("name")
final String name) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        LoggerConfig loggerConfig = config.getLoggerConfig(name);
        if (name.equalsIgnoreCase(loggerConfig.getName())) {
            config.removeLogger(name);
            LoggerConfig newloggerConfig = new LoggerConfig(name, loggerConfig.getLevel(), true);
            config.addLogger(name, newloggerConfig);
        }
        ctx.updateLoggers();
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example 7
Source File: DeployUtil.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void turnLoggingLevelToDebug() {
	LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
	Configuration config = ctx.getConfiguration();
	LoggerConfig loggerConfig = config.getLoggerConfig("rollingFileAppender");
	loggerConfig.setLevel(Level.DEBUG);
	ctx.updateLoggers();
	CONSOLE_LOGGER.info("logging level changed to [DEBUG]");
	CONSOLE_LOGGER.info("Further details can be found in log file");
}
 
Example 8
Source File: BMTrainerTest.java    From pyramid with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(Level.DEBUG);
    ctx.updateLoggers();
    test5();

}
 
Example 9
Source File: LogTestRule.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
@Override
protected void after() {
    if (loggerClass == null) {
        return;
    }

    final LoggerContext ctx = getLoggerContext();
    LoggerConfig loggerConfig = ctx.getConfiguration().getLoggerConfig(loggerClass.getName());
    loggerConfig.setLevel(oldLevel);
    loggerConfig.removeAppender(APPENDER_NAME);
    ctx.updateLoggers();
}
 
Example 10
Source File: RidgeLogisticTrainerTest.java    From pyramid with Apache License 2.0 5 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();
    test1();
}
 
Example 11
Source File: IMLLogisticRegressionTest.java    From pyramid with Apache License 2.0 5 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();
    test1();
}
 
Example 12
Source File: Log4JController.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Unset.
 *
 * @param name
 *        the name
 * @return the response entity
 */
@RequestMapping(value = "unset/{name}/", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET,
    headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<LogResponse> unset(@PathVariable("name")
final String name) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    synchronized (ctx) {
        final Configuration config = ctx.getConfiguration();
        config.removeLogger(name);
        ctx.updateLoggers();
    }
    return new ResponseEntity<>(listLoggers(ctx), HttpStatus.OK);
}
 
Example 13
Source File: Configurator.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Sets logger levels.
 *
 * @param levelMap
 *            a levelMap where keys are level names and values are new
 *            Levels.
 */
public static void setLevel(final Map<String, Level> levelMap) {
    final LoggerContext loggerContext = LoggerContext.getContext(false);
    final Configuration config = loggerContext.getConfiguration();
    boolean set = false;
    for (final Map.Entry<String, Level> entry : levelMap.entrySet()) {
        final String loggerName = entry.getKey();
        final Level level = entry.getValue();
        set |= setLevel(loggerName, level, config);
    }
    if (set) {
        loggerContext.updateLoggers();
    }
}
 
Example 14
Source File: DBConnection.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void setLogLevel(Logger logger, Level level) {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
    loggerConfig.setLevel(level);
    ctx.updateLoggers();
}
 
Example 15
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 16
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 17
Source File: Log4J2Appender.java    From javamelody with Apache License 2.0 5 votes vote down vote up
void deregister() {
	if (LogManager.getContext(false) instanceof LoggerContext) {
		final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
		if (ctx.getConfiguration() instanceof AbstractConfiguration) {
			final AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();
			final Appender appender = getSingleton();
			appender.stop();
			config.removeAppender(appender.getName());
			final Logger rootLogger = LogManager.getRootLogger();
			final LoggerConfig loggerConfig = config.getLoggerConfig(rootLogger.getName());
			loggerConfig.removeAppender(appender.getName());
			ctx.updateLoggers();
		}
	}
}
 
Example 18
Source File: PatentScorer.java    From act with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  System.out.println("Starting up...");
  System.out.flush();
  Options opts = new Options();
  opts.addOption(Option.builder("i").
      longOpt("input").hasArg().required().desc("Input file or directory to score").build());
  opts.addOption(Option.builder("o").
      longOpt("output").hasArg().required().desc("Output file to which to write score JSON").build());
  opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
  opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

  HelpFormatter helpFormatter = new HelpFormatter();
  CommandLineParser cmdLineParser = new DefaultParser();
  CommandLine cmdLine = null;
  try {
    cmdLine = cmdLineParser.parse(opts, args);
  } catch (ParseException e) {
    System.out.println("Caught exception when parsing command line: " + e.getMessage());
    helpFormatter.printHelp("DocumentIndexer", opts);
    System.exit(1);
  }

  if (cmdLine.hasOption("help")) {
    helpFormatter.printHelp("DocumentIndexer", opts);
    System.exit(0);
  }

  if (cmdLine.hasOption("verbose")) {
    // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration ctxConfig = ctx.getConfiguration();
    LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    logConfig.setLevel(Level.DEBUG);

    ctx.updateLoggers();
    LOGGER.debug("Verbose logging enabled");
  }

  String inputFileOrDir = cmdLine.getOptionValue("input");
  File splitFileOrDir = new File(inputFileOrDir);
  if (!(splitFileOrDir.exists())) {
    LOGGER.error("Unable to find directory at " + inputFileOrDir);
    System.exit(1);
  }

  try (FileWriter writer = new FileWriter(cmdLine.getOptionValue("output"))) {
    PatentScorer scorer = new PatentScorer(PatentModel.getModel(), writer);
    PatentCorpusReader corpusReader = new PatentCorpusReader(scorer, splitFileOrDir);
    corpusReader.readPatentCorpus();
  }
}
 
Example 19
Source File: DocumentIndexer.java    From act with GNU General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  System.out.println("Starting up...");
  System.out.flush();
  Options opts = new Options();
  opts.addOption(Option.builder("i").
      longOpt("input").hasArg().required().desc("Input file or directory to index").build());
  opts.addOption(Option.builder("x").
      longOpt("index").hasArg().required().desc("Path to index file to generate").build());
  opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
  opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

  HelpFormatter helpFormatter = new HelpFormatter();
  CommandLineParser cmdLineParser = new DefaultParser();
  CommandLine cmdLine = null;
  try {
    cmdLine = cmdLineParser.parse(opts, args);
  } catch (ParseException e) {
    System.out.println("Caught exception when parsing command line: " + e.getMessage());
    helpFormatter.printHelp("DocumentIndexer", opts);
    System.exit(1);
  }

  if (cmdLine.hasOption("help")) {
    helpFormatter.printHelp("DocumentIndexer", opts);
    System.exit(0);
  }

  if (cmdLine.hasOption("verbose")) {
    // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration ctxConfig = ctx.getConfiguration();
    LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    logConfig.setLevel(Level.DEBUG);

    ctx.updateLoggers();
    LOGGER.debug("Verbose logging enabled");
  }

  LOGGER.info("Opening index at " + cmdLine.getOptionValue("index"));
  Directory indexDir = FSDirectory.open(new File(cmdLine.getOptionValue("index")).toPath());

  /* The standard analyzer is too aggressive with chemical entities (it strips structural annotations, for one
   * thing), and the whitespace analyzer doesn't do any case normalization or stop word elimination.  This custom
   * analyzer appears to treat chemical entities better than the standard analyzer without admitting too much
   * cruft to the index. */
  Analyzer analyzer = CustomAnalyzer.builder().
      withTokenizer("whitespace").
      addTokenFilter("lowercase").
      addTokenFilter("stop").
      build();

  IndexWriterConfig writerConfig = new IndexWriterConfig(analyzer);
  writerConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
  writerConfig.setRAMBufferSizeMB(1 << 10);
  IndexWriter indexWriter = new IndexWriter(indexDir, writerConfig);

  String inputFileOrDir = cmdLine.getOptionValue("input");
  File splitFileOrDir = new File(inputFileOrDir);
  if (!(splitFileOrDir.exists())) {
    LOGGER.error("Unable to find directory at " + inputFileOrDir);
    System.exit(1);
  }

  DocumentIndexer indexer = new DocumentIndexer(indexWriter);
  PatentCorpusReader corpusReader = new PatentCorpusReader(indexer, splitFileOrDir);
  corpusReader.readPatentCorpus();
  indexer.commitAndClose();
}
 
Example 20
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();
}