下面列出了org.apache.logging.log4j.core.LoggerContext#updateLoggers ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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());
}
}
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();
}
}
/**
* 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);
}
/**
* 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();
}
}
@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();
}
@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);
}
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();
}
}
}
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.
}
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);
}
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();
}
/**
* 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();
}
}
/**
* 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);
}
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();
}
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();
}
@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();
}
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();
}
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");
}
private static void setLogLevel(Level logLevel) {
LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
Configuration configuration = loggerContext.getConfiguration();
configuration.getLoggerConfig(LOGGER_NAME).setLevel(logLevel);
loggerContext.updateLoggers();
}
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();
}
}
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();
}