Java Code Examples for org.apache.logging.log4j.LogManager#getContext()
The following examples show how to use
org.apache.logging.log4j.LogManager#getContext() .
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: TestFileAuditAppender.java From syncope with Apache License 2.0 | 6 votes |
@Override protected void initTargetAppender() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); // get log file path from existing file appender RollingRandomAccessFileAppender mainFile = (RollingRandomAccessFileAppender) ctx.getConfiguration().getAppender("mainFile"); String pathPrefix = mainFile == null ? System.getProperty("user.dir") + StringUtils.replace("/target/log", "/", File.separator) + File.separator : StringUtils.replace(mainFile.getFileName(), "core.log", StringUtils.EMPTY); targetAppender = FileAppender.newBuilder(). setName(getTargetAppenderName()). withAppend(true). withFileName(pathPrefix + getTargetAppenderName() + ".log"). setLayout(PatternLayout.newBuilder(). withPattern("%d{HH:mm:ss.SSS} %-5level %logger - %msg%n"). build()). build(); }
Example 2
Source File: Log4JController.java From GreenSummer with GNU Lesser General Public License v2.1 | 6 votes |
@RequestMapping(value = "captured", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET, headers = "Accept=application/json") public void captured(HttpServletResponse response) { response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); synchronized (ctx) { if (inMemoryAppenderImpl != null) { inMemoryAppenderImpl.getRegisteredEvents().stream().forEach(line -> { try { response.getWriter().write(line); } catch (Exception e) { log.error("Error showing captured logs. Ironic, huh?", e); } }); } } }
Example 3
Source File: Log4JController.java From GreenSummer with GNU Lesser General Public License v2.1 | 6 votes |
/** * 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 4
Source File: TestLogLevelAnnotations.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Check that the expected log level <em>configurations</em> have been reset after the test * <p> * <b>NOTE:</b> We only validate <code>@LogLevel</code> modifications made at the * {@link #testMethodLogLevels} level, not at the 'class' level, because of the lifecycle of junit * methods: This <code>@AfterClass</code> will run before the <code>SolrTestCaseJ4</code> * <code>@AfterClass</code> method where the 'class' <code>@LogLevel</code> modifications will be reset. * </p> * * @see #checkLogLevelsBeforeClass * @see #testWhiteBoxMethods */ @AfterClass public static void checkLogLevelsAfterClass() { final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final Configuration config = ctx.getConfiguration(); // NOTE: we're checking the CONFIGURATION of the loggers, not the "effective" value of the Logger assertEquals(DEFAULT_LOG_LEVEL, config.getRootLogger().getLevel()); 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(Level.ERROR, config.getLoggerConfig(bogus_logger_prefix + ".ClassLogLevel").getLevel()); assertEquals(Level.WARN, config.getLoggerConfig(bogus_logger_prefix + ".MethodLogLevel").getLevel()); // Now sanity check the EFFECTIVE Level of these loggers... assertEquals(DEFAULT_LOG_LEVEL, LogManager.getRootLogger().getLevel()); assertEquals(DEFAULT_LOG_LEVEL, LogManager.getLogger(bogus_logger_prefix).getLevel()); assertEquals(Level.ERROR, LogManager.getLogger(bogus_logger_prefix + ".ClassLogLevel").getLevel()); assertEquals(Level.WARN, LogManager.getLogger(bogus_logger_prefix + ".MethodLogLevel").getLevel()); }
Example 5
Source File: OutputStreamAppenderTest.java From logging-log4j2 with Apache License 2.0 | 6 votes |
/** * 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 6
Source File: LoggingConfigurator.java From TweetwallFX with MIT License | 6 votes |
/** * Configures Logging in case it has not been configured via this method * before. */ public static void configure() { if (ALREADY_CONFIGURED.compareAndSet(false, true)) { final File log4jFile = new File("log4j2.xml"); if (log4jFile.isFile()) { LoggerContext context = (LoggerContext) LogManager.getContext(false); context.setConfigLocation(log4jFile.toURI()); } else { final Logger logger = LogManager.getLogger(LoggingConfigurator.class); logger.info("log4j configuration file ('" + log4jFile.getAbsolutePath() + "') not found."); } } }
Example 7
Source File: StartupLoggingUtils.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * Disables all log4j2 ConsoleAppender's by modifying log4j configuration dynamically. * Must only be used during early startup * @return true if ok or else false if something happened, e.g. log4j2 classes were not in classpath */ @SuppressForbidden(reason = "Legitimate log4j2 access") public static boolean muteConsole() { try { if (!isLog4jActive()) { logNotSupported("Could not mute logging to console."); return false; } LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); Map<String, Appender> appenders = loggerConfig.getAppenders(); appenders.forEach((name, appender) -> { if (appender instanceof ConsoleAppender) { loggerConfig.removeAppender(name); ctx.updateLoggers(); } }); return true; } catch (Exception e) { logNotSupported("Could not mute logging to console."); return false; } }
Example 8
Source File: CommandCloudServer.java From CloudNet with Apache License 2.0 | 6 votes |
private boolean debug(CommandSender commandSender) { CloudAPI.getInstance().setDebug(!CloudAPI.getInstance().isDebug()); final LoggerContext context = (LoggerContext) LogManager.getContext(false); final Configuration configuration = context.getConfiguration(); final LoggerConfig rootLoggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME); if (CloudAPI.getInstance().isDebug()) { rootLoggerConfig.setLevel(Level.ALL); commandSender.sendMessage("§aDebug output for server has been enabled."); } else { rootLoggerConfig.setLevel(Level.INFO); commandSender.sendMessage("§cDebug output for server has been disabled."); } context.updateLoggers(configuration); return false; }
Example 9
Source File: StartupLoggingUtils.java From lucene-solr with Apache License 2.0 | 6 votes |
/** * This is primarily for tests to insure that log messages don't bleed from one test case to another, see: * SOLR-13268. * * However, if there are situations where we want to insure that all log messages for all loggers are flushed, * this method can be called by anyone. It should _not_ affect Solr in any way except, perhaps, a slight delay * while messages are being flushed. * * Expert, there are rarely good reasons for this to be called outside of the test framework. If you are tempted to * call this for running Solr, you should probably be using synchronous logging. */ @SuppressForbidden(reason = "Legitimate log4j2 access") public static void flushAllLoggers() { if (!isLog4jActive()) { logNotSupported("Not running log4j2, could not call shutdown for async logging."); return; } final LoggerContext logCtx = ((LoggerContext) LogManager.getContext(false)); for (final org.apache.logging.log4j.core.Logger logger : logCtx.getLoggers()) { for (final Appender appender : logger.getAppenders().values()) { if (appender instanceof AbstractOutputStreamAppender) { ((AbstractOutputStreamAppender) appender).getManager().flush(); } } } }
Example 10
Source File: JdbcAuditAppender.java From syncope with Apache License 2.0 | 5 votes |
@Override protected void initTargetAppender() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); ColumnMapping[] columnMappings = { ColumnMapping.newBuilder(). setConfiguration(ctx.getConfiguration()).setName("EVENT_DATE").setType(Timestamp.class).build(), ColumnMapping.newBuilder(). setConfiguration(ctx.getConfiguration()).setName("LOGGER_LEVEL").setPattern("%level").build(), ColumnMapping.newBuilder(). setConfiguration(ctx.getConfiguration()).setName("LOGGER").setPattern("%logger").build(), ColumnMapping.newBuilder(). setConfiguration(ctx.getConfiguration()). setName(LoggerDAO.AUDIT_MESSAGE_COLUMN).setPattern("%message").build(), ColumnMapping.newBuilder(). setConfiguration(ctx.getConfiguration()).setName("THROWABLE").setPattern("%ex{full}").build() }; Appender appender = ctx.getConfiguration().getAppender("audit_for_" + domain); if (appender == null) { appender = JdbcAppender.newBuilder(). setName("audit_for_" + domain). setIgnoreExceptions(false). setConnectionSource(new DataSourceConnectionSource(domain, domainHolder.getDomains().get(domain))). setBufferSize(0). setTableName(LoggerDAO.AUDIT_TABLE). setColumnMappings(columnMappings). build(); appender.start(); ctx.getConfiguration().addAppender(appender); } targetAppender = appender; }
Example 11
Source File: Log4j2Watcher.java From lucene-solr with Apache License 2.0 | 5 votes |
@Override public void setThreshold(String level) { Log4j2Appender app = getAppender(); Level current = app.getThreshold(); app.setThreshold(Level.toLevel(level)); LoggerContext ctx = (LoggerContext) LogManager.getContext(false); LoggerConfig config = getLoggerConfig(ctx, LoggerInfo.ROOT_NAME); config.removeAppender(app.getName()); config.addAppender(app, app.getThreshold(), app.getFilter()); ((LoggerContext)LogManager.getContext(false)).updateLoggers(); if (log.isInfoEnabled()) { log.info("Updated watcher threshold from {} to {} ", current, level); } }
Example 12
Source File: ContextDataProviderTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@BeforeClass public static void beforeClass() { ThreadContextDataInjector.contextDataProviders.add(new TestContextDataProvider()); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "target/test-classes/log4j-contextData.xml"); LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false); logger = loggerContext.getLogger(ContextDataProviderTest.class.getName()); appender = loggerContext.getConfiguration().getAppender("List"); assertNotNull("No List appender", appender); }
Example 13
Source File: SimpleDiagnosticsAppender.java From samza with Apache License 2.0 | 5 votes |
private void attachAppenderToLoggers(Appender appender) { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration config = ctx.getConfiguration(); // ensure appender is attached only once per JVM (regardless of #containers) if (config.getRootLogger().getAppenders().get(SimpleDiagnosticsAppender.class.getName()) == null) { System.out.println("Attaching diagnostics appender to root logger"); appender.start(); config.addAppender(appender); for (final LoggerConfig loggerConfig : config.getLoggers().values()) { loggerConfig.addAppender(appender, null, null); } } }
Example 14
Source File: SpectatorAppender.java From spectator with Apache License 2.0 | 5 votes |
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 15
Source File: AsyncAppenderShutdownTimeoutTest.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Test(timeout = 5000) public void shutdownTest() throws Exception { final LoggerContext ctx = (LoggerContext)LogManager.getContext(false); final Logger logger = ctx.getLogger("Logger"); logger.info("This is a test"); ctx.stop(); }
Example 16
Source File: BHBot.java From BHBot with GNU General Public License v3.0 | 4 votes |
private void reloadLogger() { ConfigurationFactory configFactory = new BHBotConfigurationFactory(); ConfigurationFactory.setConfigurationFactory(configFactory); LoggerContext ctx = (LoggerContext) LogManager.getContext(false); ctx.start(configFactory.getConfiguration(ctx, ConfigurationSource.NULL_SOURCE)); }
Example 17
Source File: MCRWebCLIContainer.java From mycore with GNU General Public License v3.0 | 4 votes |
protected boolean processCommands() throws IOException { final LoggerContext logCtx = (LoggerContext) LogManager.getContext(false); final AbstractConfiguration logConf = (AbstractConfiguration) logCtx.getConfiguration(); LinkedList<String> failedQueue = new LinkedList<>(); logGrabber.grabCurrentThread(); // start grabbing logs of this thread logConf.getRootLogger().addAppender(logGrabber, logConf.getRootLogger().getLevel(), null); // register session to MCRSessionMgr MCRSessionMgr.setCurrentSession(session); Optional<HttpSession> httpSession = Optional .ofNullable((HttpSession) webSocketSession.getUserProperties() .get(MCRWebsocketDefaultConfigurator.HTTP_SESSION)); int sessionTime = httpSession.map(HttpSession::getMaxInactiveInterval).orElse(-1); httpSession.ifPresent(s -> s.setMaxInactiveInterval(-1)); try { while (!commands.isEmpty()) { String command = commands.remove(0); cmdListPublisher.submit(commands); if (!processCommand(command)) { if (!continueIfOneFails) { return false; } failedQueue.add(command); } } if (failedQueue.isEmpty()) { setCurrentCommand(""); return true; } else { saveQueue(null, failedQueue); return false; } } finally { // stop grabbing logs of this thread logGrabber.stop(); logConf.removeAppender(logGrabber.getName()); try { if (webSocketSession.isOpen()) { LogManager.getLogger().info("Close session {}", webSocketSession::getId); webSocketSession.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Done")); } } finally { httpSession.ifPresent(s -> s.setMaxInactiveInterval(sessionTime)); // release session MCRSessionMgr.releaseCurrentSession(); } } }
Example 18
Source File: Log4j2CloudConfigLoggingSystem.java From logging-log4j2 with Apache License 2.0 | 4 votes |
private LoggerContext getLoggerContext() { return (LoggerContext) LogManager.getContext(false); }
Example 19
Source File: DocumentIndexer.java From act with GNU General Public License v3.0 | 4 votes |
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: LoggerContext.java From logging-log4j2 with Apache License 2.0 | 2 votes |
/** * Returns the current LoggerContext. * <p> * Avoids the type cast for: * </p> * * <pre> * (LoggerContext) LogManager.getContext(); * </pre> * * <p> * WARNING - The LoggerContext returned by this method may not be the LoggerContext used to create a Logger for the * calling class. * </p> * * @return The current LoggerContext. * @see LogManager#getContext() */ public static LoggerContext getContext() { return (LoggerContext) LogManager.getContext(); }