private void configureLogging(LogLevel logLevel) { Level log4jLogLevel; switch (Objects.requireNonNull(logLevel)) { case NORMAL: { log4jLogLevel = Level.INFO; break; } case VERBOSE: { log4jLogLevel = Level.DEBUG; break; } case TRACE: { log4jLogLevel = Level.TRACE; break; } default: { throw new IllegalArgumentException("Unknown log level: " + logLevel.name()); } } Configurator.setLevel("bt", log4jLogLevel); }
private static void initLog4j() { String log4jConfigFolderPath = System.getProperty("motu-config-dir"); if (log4jConfigFolderPath != null && log4jConfigFolderPath.length() > 0) { if (!log4jConfigFolderPath.endsWith("/")) { log4jConfigFolderPath += "/"; } } else { System.err.println("Error while initializing log4j. Property is not set motu-config-dir or has a bad value"); } // Do not use system property to avoid conflicts with other tomcat webapps // System.setProperty("log4j.configurationFile", log4jConfigFolderPath + "log4j.xml"); try { ConfigurationSource source = new ConfigurationSource(new FileInputStream(log4jConfigFolderPath + "log4j.xml")); Configurator.initialize(null, source); } catch (IOException e) { System.err.println("Error while initializing log4j from file: " + log4jConfigFolderPath + "log4j.xml"); e.printStackTrace(); } }
@Before public void setUp() throws Exception { Configurator .initialize("FastMQ", Thread.currentThread().getContextClassLoader(), "log4j2.xml"); Log log = new Log(); LogSegment logSegment = new LogSegment(); logSegment.setLedgerId(ledgerId); logSegment.setTimestamp(System.currentTimeMillis()); log.setSegments(Collections.singletonList(logSegment)); when(logInfoStorage.getLogInfo(any())).thenReturn(log); CuratorFramework curatorFramework = CuratorFrameworkFactory .newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3)); curatorFramework.start(); asyncCuratorFramework = AsyncCuratorFramework.wrap(curatorFramework); offsetStorage = new ZkOffsetStorageImpl(logInfoStorage, asyncCuratorFramework); }
/** * Build logger context logger context. * * @param environment the environment * @param resourceLoader the resource loader * @return the logger context */ public static Pair<Resource, LoggerContext> buildLoggerContext(final Environment environment, final ResourceLoader resourceLoader) { try { final String logFile = environment.getProperty("logging.config", "classpath:/log4j2.xml"); LOGGER.debug("Located logging configuration reference in the environment as [{}]", logFile); if (ResourceUtils.doesResourceExist(logFile, resourceLoader)) { final Resource logConfigurationFile = resourceLoader.getResource(logFile); LOGGER.debug("Loaded logging configuration resource [{}]. Initializing logger context...", logConfigurationFile); final LoggerContext loggerContext = Configurator.initialize("CAS", null, logConfigurationFile.getURI()); LOGGER.debug("Installing log configuration listener to detect changes and update"); loggerContext.getConfiguration().addListener(reconfigurable -> loggerContext.updateLoggers(reconfigurable.reconfigure())); return Pair.of(logConfigurationFile, loggerContext); } LOGGER.warn("Logging configuration cannot be found in the environment settings"); } catch (final Exception e) { throw Throwables.propagate(e); } return null; }
public ServiceCollector( Application csapApplication, OsManager osManager, int intervalSeconds, boolean publishSummary ) { super( csapApplication, osManager, intervalSeconds, publishSummary ); httpCollector = new HttpCollector( csapApplication, this ); if ( Application.isRunningOnDesktop() && !csapApplication.isJunit() ) { System.err.println( "\n ============= DESKTOP detected - setting logs to ERROR " ); Configurator.setLevel( ServiceCollector.class.getName(), Level.ERROR ); } timeStampArray_m = jacksonMapper.createArrayNode(); totalCpuArray = jacksonMapper.createArrayNode(); setMaxCollectionAllowedInMs( csapApplication .lifeCycleSettings() .getMaxJmxCollectionMs() ); scheduleCollection( this ); }
@Override public void applyDelegate(Config config) { Security.addProvider(new BouncyCastleProvider()); if (isDebug()) { setLogLevel(Level.DEBUG); } Configurator.setRootLevel(getLogLevel()); Configurator.setAllLevels("de.rub.nds.modifiablevariable", Level.FATAL); if (getLogLevel() == Level.ALL) { Configurator.setAllLevels("de.rub.nds.tlsattacker.core", Level.ALL); Configurator.setAllLevels("de.rub.nds.tlsattacker.transport", Level.DEBUG); } else if (getLogLevel() == Level.TRACE) { Configurator.setAllLevels("de.rub.nds.tlsattacker.core", Level.DEBUG); Configurator.setAllLevels("de.rub.nds.tlsattacker.transport", Level.DEBUG); } else { Configurator.setAllLevels("de.rub.nds.tlsattacker.core", Level.OFF); } LOGGER.debug("Using the following security providers"); for (Provider p : Security.getProviders()) { LOGGER.debug("Provider {}, version, {}", p.getName(), p.getVersion()); } // remove stupid Oracle JDK security restriction (otherwise, it is not // possible to use strong crypto with Oracle JDK) UnlimitedStrengthEnabler.enable(); }
/** * @param name * the name of the java class or java package to set the log * level for * @param logLevelToSet * the log level to set e.g. TRACE, DEBUG, INFO, WARN, ERROR and * FATAL, providing any other value will lead to DEBUG as new log * level */ @MCRCommand(syntax = "change log level of {0} to {1}", help = "{0} the package or class name for which to change the log level, {1} the log level to set.", order = 10) public static synchronized void changeLogLevel(String name, String logLevelToSet) { LOGGER.info("Setting log level for \"{}\" to \"{}\"", name, logLevelToSet); Level newLevel = Level.getLevel(logLevelToSet); if (newLevel == null) { LOGGER.error("Unknown log level \"{}\"", logLevelToSet); return; } Logger log = "ROOT".equals(name) ? LogManager.getRootLogger() : LogManager.getLogger(name); if (log == null) { LOGGER.error("Could not get logger for \"{}\"", name); return; } LOGGER.info("Change log level from {} to {}", log.getLevel(), newLevel); Configurator.setLevel(log.getName(), newLevel); }
/** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { Configurator.initialize("CocaRMQBenchmark", Thread.currentThread().getContextClassLoader(), "rmq-log4j2.xml"); // init coca CocaSample sub = new CocaSample("appSub", "syncGroup"); sub.initCoca(CONF); int warmCount = CocaRMQBenchmark.warmCount; int writeCount = CocaRMQBenchmark.writeCount; int total = warmCount + writeCount; long s0 = System.currentTimeMillis(); while (true) { if (sub.countSub() >= total) { break; } LOG.info("total-{} sub-{}", total, sub.countSub()); Thread.sleep(5000L); } long s1 = System.currentTimeMillis(); sub.close(); LOG.info("sub-{} time-{}", sub.countSub() - warmCount, s1 - s0); }
/** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // System.setProperty("log4j.configurationFile", ""); Configurator.initialize("SampleMain", Thread.currentThread().getContextClassLoader(), "simple-log4j2.xml"); // initialize coca instance CocaSample app1 = new CocaSample("app1", "syncGroup"); app1.initCoca(CONF); CocaSample app2 = new CocaSample("app2", "syncGroup"); app2.initCoca(CONF); // testRead(app1, app2); testShareWrite(app1, app2); // close app1.close(); app2.close(); }
/** * Creates new logger with given configuration {@code path}. * * @param path Path to log4j2 configuration XML file. * @throws IgniteCheckedException Thrown in case logger can't be created. */ public Log4J2Logger(String path) throws IgniteCheckedException { if (path == null) throw new IgniteCheckedException("Configuration XML file for Log4j2 must be specified."); final URL cfgUrl = U.resolveIgniteUrl(path); if (cfgUrl == null) throw new IgniteCheckedException("Log4j2 configuration path was not found: " + path); addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() { @Override public Logger apply(Boolean init) { if (init) Configurator.initialize(LogManager.ROOT_LOGGER_NAME, cfgUrl.toString()); return (Logger)LogManager.getRootLogger(); } }); quiet = quiet0; cfg = path; }
/** * Creates new logger with given configuration {@code cfgFile}. * * @param cfgFile Log4j configuration XML file. * @throws IgniteCheckedException Thrown in case logger can't be created. */ public Log4J2Logger(File cfgFile) throws IgniteCheckedException { if (cfgFile == null) throw new IgniteCheckedException("Configuration XML file for Log4j must be specified."); if (!cfgFile.exists() || cfgFile.isDirectory()) throw new IgniteCheckedException("Log4j2 configuration path was not found or is a directory: " + cfgFile); final String path = cfgFile.getAbsolutePath(); addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() { @Override public Logger apply(Boolean init) { if (init) Configurator.initialize(LogManager.ROOT_LOGGER_NAME, path); return (Logger)LogManager.getRootLogger(); } }); quiet = quiet0; cfg = cfgFile.getPath(); }
/** * Creates new logger with given configuration {@code cfgUrl}. * * @param cfgUrl URL for Log4j configuration XML file. * @throws IgniteCheckedException Thrown in case logger can't be created. */ public Log4J2Logger(final URL cfgUrl) throws IgniteCheckedException { if (cfgUrl == null) throw new IgniteCheckedException("Configuration XML file for Log4j must be specified."); addConsoleAppenderIfNeeded(new C1<Boolean, Logger>() { @Override public Logger apply(Boolean init) { if (init) Configurator.initialize(LogManager.ROOT_LOGGER_NAME, cfgUrl.toString()); return (Logger)LogManager.getRootLogger(); } }); quiet = quiet0; cfg = cfgUrl.getPath(); }
public static void main(String[] args) throws Exception { ServerChannelManager.getInstance().startUp(); ClientChannelManager.getInstance().startUp(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { ClientChannelManager.getInstance().shutdown(); ServerChannelManager.getInstance().shutdown(); // Disables the "shutdownHook" attribute of the configuration element inside the log4j2.xml and manually shutdowns Log4j system // Refer to http://stackoverflow.com/questions/17400136/how-to-log-within-shutdown-hooks-with-log4j2 Configurator.shutdown((LoggerContext) LogManager.getContext()); } }); }
@Test public void testInitialize() throws Exception { final String log4jConfigString = "<Configuration name=\"ConfigTest\" status=\"debug\" >" + "<Appenders>" + " <Console name=\"STDOUT\">" + " <PatternLayout pattern=\"%m%n\"/>" + " </Console>" + "</Appenders>" + "<Loggers>" + " <Root level=\"error\">" + " <AppenderRef ref=\"STDOUT\"/>" + " </Root>" + "</Loggers>" + "</Configuration>"; final InputStream is = new ByteArrayInputStream(log4jConfigString.getBytes()); final ConfigurationFactory.ConfigurationSource source = new ConfigurationFactory.ConfigurationSource(is); final long begin = System.currentTimeMillis(); Configurator.initialize(null, source); final long tookForInit = System.currentTimeMillis() - begin; System.out.println("log4j 2.0 initialization took " + tookForInit + "ms"); }
public static void main(final String[] args) { // System.out.println(System.getProperty("java.class.path")); String config = args.length == 0 ? "target/test-classes/log4j2-319.xml" : args[0]; final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config); try { LOG.fatal("Fatal message."); LOG.error("Error message."); LOG.warn("Warning message."); LOG.info("Information message."); LOG.debug("Debug message."); LOG.trace("Trace message."); try { throw new NullPointerException(); } catch (Exception e) { LOG.error("Error message.", e); LOG.catching(Level.ERROR, e); } LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?"); LOG.info("Information message."); } finally { Configurator.shutdown(ctx); } }
public static void main(final String[] args) { // System.out.println(System.getProperty("java.class.path")); String config = args.length == 0 ? "target/test-classes/log4j2-180.xml" : args[0]; final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config); try { LOG.fatal("Fatal message."); LOG.error("Error message."); LOG.warn("Warning message."); LOG.info("Information message."); LOG.debug("Debug message."); LOG.trace("Trace message."); try { throw new NullPointerException(); } catch (Exception e) { LOG.error("Error message.", e); LOG.catching(Level.ERROR, e); } } finally { Configurator.shutdown(ctx); } }
public static void main(final String[] args) { // System.out.println(System.getProperty("java.class.path")); String config = args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml" : args[0]; final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config); try { LOG.fatal("Fatal message."); LOG.error("Error message."); LOG.warn("Warning message."); LOG.info("Information message."); LOG.debug("Debug message."); LOG.trace("Trace message."); LOG.error("Error message.", new IOException("test")); } finally { Configurator.shutdown(ctx); } }
public static void main(final String[] args) { // System.out.println(System.getProperty("java.class.path")); String config = args.length == 0 ? "target/test-classes/log4j2-272.xml" : args[0]; final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config); try { LOG.fatal("Fatal message."); LOG.error("Error message."); LOG.warn("Warning message."); LOG.info("Information message."); LOG.debug("Debug message."); LOG.trace("Trace message."); try { throw new NullPointerException(); } catch (Exception e) { LOG.error("Error message.", e); LOG.catching(Level.ERROR, e); } LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?"); LOG.info("Information message."); } finally { Configurator.shutdown(ctx); } }
@Test public void testConfig() { final LoggerContext ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-sdfilter.xml"); final Configuration config = ctx.getConfiguration(); final Filter filter = config.getFilter(); assertNotNull("No StructuredDataFilter", filter); assertTrue("Not a StructuredDataFilter", filter instanceof StructuredDataFilter); final StructuredDataFilter sdFilter = (StructuredDataFilter) filter; assertFalse("Should not be And filter", sdFilter.isAnd()); final Map<String, List<String>> map = sdFilter.getMap(); assertNotNull("No Map", map); assertTrue("No elements in Map", map.size() != 0); assertTrue("Incorrect number of elements in Map", map.size() == 1); assertTrue("Map does not contain key eventId", map.containsKey("eventId")); assertTrue("List does not contain 2 elements", map.get("eventId").size() == 2); }
@Test public void testBuildConfiguration() throws Exception { try { System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"); final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory .newConfigurationBuilder(); CustomConfigurationFactory.addTestFixtures("config name", builder); final Configuration configuration = builder.build(); try (LoggerContext ctx = Configurator.initialize(configuration)) { validate(configuration); } } finally { System.getProperties().remove(Constants.LOG4J_CONTEXT_SELECTOR); } }
private void initializeNonJndi(final String location) { if (this.name == null) { this.name = this.servletContext.getServletContextName(); LOGGER.debug("Using the servlet context name \"{}\".", this.name); } if (this.name == null) { this.name = this.servletContext.getContextPath(); LOGGER.debug("Using the servlet context context-path \"{}\".", this.name); } if (this.name == null && location == null) { LOGGER.error("No Log4j context configuration provided. This is very unusual."); this.name = new SimpleDateFormat("yyyyMMdd_HHmmss.SSS").format(new Date()); } final URI uri = getConfigURI(location); this.loggerContext = Configurator.initialize(this.name, this.getClassLoader(), uri, this.servletContext); }
public static void main(final String[] args) { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable // System.out.println(System.getProperty("java.class.path")); final String config = args.length == 0 ? "target/test-classes/log4j2-319.xml" : args[0]; try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) { LOG.fatal("Fatal message."); LOG.error("Error message."); LOG.warn("Warning message."); LOG.info("Information message."); LOG.debug("Debug message."); LOG.trace("Trace message."); try { throw new NullPointerException(); } catch (final Exception e) { LOG.error("Error message.", e); LOG.catching(Level.ERROR, e); } LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?"); LOG.info("Information message."); } }
public static void main(final String[] args) { // src/test/resources/log4j2-console-progress.xml // target/test-classes/log4j2-progress-console.xml try (final LoggerContext ctx = Configurator.initialize(ProgressConsoleTest.class.getName(), "target/test-classes/log4j2-progress-console.xml")) { for (double i = 0; i <= 1; i = i + 0.05) { updateProgress(i); try { Thread.sleep(100); } catch (final InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
public void test(final String[] args) { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable // System.out.println(System.getProperty("java.class.path")); final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-xex-ansi.xml" : args[0]; final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config); final Logger logger = LogManager.getLogger(ConsoleAppenderJAnsiXExceptionMain.class); try { Files.getFileStore(Paths.get("?BOGUS?")); } catch (final Exception e) { final IllegalArgumentException logE = new IllegalArgumentException("Bad argument foo", e); logger.error("Gotcha!", logE); } finally { Configurator.shutdown(ctx); } }
public static void main(final String[] args) { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable // System.out.println(System.getProperty("java.class.path")); final String config = args.length == 0 ? "target/test-classes/log4j2-180.xml" : args[0]; try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) { LOG.fatal("Fatal message."); LOG.error("Error message."); LOG.warn("Warning message."); LOG.info("Information message."); LOG.debug("Debug message."); LOG.trace("Trace message."); try { throw new NullPointerException(); } catch (final Exception e) { LOG.error("Error message.", e); LOG.catching(Level.ERROR, e); } } }
static void test(final String[] args, final String config) { // System.out.println(System.getProperty("java.class.path")); try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderNoAnsiStyleLayoutMain.class.getName(), config)) { LOG.fatal("Fatal message."); LOG.error("Error message."); LOG.warn("Warning message."); LOG.info("Information message."); LOG.debug("Debug message."); LOG.trace("Trace message."); logThrowableFromMethod(); // This will log the stack trace as well: final IOException ioException = new IOException("test"); LOG.error("Error message {}", "Hi", ioException); final Throwable t = new IOException("test suppressed"); t.addSuppressed(new IOException("test suppressed 2", ioException)); LOG.error("Error message {}, suppressed?", "Hi", t); LOG.error("Error message {}, suppressed?", "Hi", new IOException("test", t)); } }
public void test(final String[] args) { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable // System.out.println(System.getProperty("java.class.path")); final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-msg-ansi.xml" : args[0]; try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) { final Logger logger = LogManager.getLogger(ConsoleAppenderJAnsiMessageMain.class); logger.info(ansi().fg(RED).a("Hello").fg(CYAN).a(" World").reset()); // JAnsi format: // logger.info("@|red Hello|@ @|cyan World|@"); for (final Entry<Object, Object> entry : System.getProperties().entrySet()) { logger.info("@|KeyStyle {}|@ = @|ValueStyle {}|@", entry.getKey(), entry.getValue()); } } }
public void test(final String[] args) { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable // System.out.println(System.getProperty("java.class.path")); final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml" : args[0]; try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) { final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class); logger.fatal("Fatal message."); logger.error("Error message."); logger.warn("Warning message."); logger.info("Information message."); logger.debug("Debug message."); logger.trace("Trace message."); logger.error("Error message.", new IOException("test")); } }
public static void main(final String[] args) { System.setProperty("log4j.skipJansi", "false"); // LOG4J2-2087: explicitly enable // System.out.println(System.getProperty("java.class.path")); final String config = args.length == 0 ? "target/test-classes/log4j2-272.xml" : args[0]; try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) { LOG.fatal("Fatal message."); LOG.error("Error message."); LOG.warn("Warning message."); LOG.info("Information message."); LOG.debug("Debug message."); LOG.trace("Trace message."); try { throw new NullPointerException(); } catch (final Exception e) { LOG.error("Error message.", e); LOG.catching(Level.ERROR, e); } LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?"); LOG.info("Information message."); } }
@Test public void testConfig() { try (final LoggerContext ctx = Configurator.initialize("Test1", "target/test-classes/log4j2-dynamicfilter.xml")) { final Configuration config = ctx.getConfiguration(); final Filter filter = config.getFilter(); assertNotNull("No DynamicThresholdFilter", filter); assertTrue("Not a DynamicThresholdFilter", filter instanceof DynamicThresholdFilter); final DynamicThresholdFilter dynamic = (DynamicThresholdFilter) filter; final String key = dynamic.getKey(); assertNotNull("Key is null", key); assertEquals("Incorrect key value", "loginId", key); final Map<String, Level> map = dynamic.getLevelMap(); assertNotNull("Map is null", map); assertEquals("Incorrect number of map elements", 1, map.size()); } }
@Test public void debugChangeLevelAllChildrenLoggers() { // Use logger AND child loggers logger.debug("Debug message 1"); loggerChild.debug("Debug message 1 child"); loggerGrandchild.debug("Debug message 1 grandchild"); final List<LogEvent> events = app.getEvents(); assertEventCount(events, 3); Configurator.setAllLevels(logger.getName(), Level.OFF); logger.debug("Debug message 2"); loggerChild.warn("Warn message 2 child"); loggerGrandchild.fatal("Fatal message 2 grandchild"); assertEventCount(events, 3); Configurator.setAllLevels(logger.getName(), Level.DEBUG); logger.debug("Debug message 3"); loggerChild.warn("Trace message 3 child"); loggerGrandchild.trace("Fatal message 3 grandchild"); assertEventCount(events, 5); }
@Test public void debugChangeLevelChildLogger() { // Use logger AND child loggers logger.debug("Debug message 1"); loggerChild.debug("Debug message 1 child"); loggerGrandchild.debug("Debug message 1 grandchild"); final List<LogEvent> events = app.getEvents(); assertEventCount(events, 3); Configurator.setLevel(logger.getName(), Level.OFF); logger.debug("Debug message 2"); loggerChild.debug("Debug message 2 child"); loggerGrandchild.debug("Debug message 2 grandchild"); assertEventCount(events, 3); Configurator.setLevel(logger.getName(), Level.DEBUG); logger.debug("Debug message 3"); loggerChild.debug("Debug message 3 child"); loggerGrandchild.debug("Debug message 3 grandchild"); assertEventCount(events, 6); }
@Test public void debugChangeLevelsChildLoggers() { final org.apache.logging.log4j.Logger loggerChild = context.getLogger(logger.getName() + ".child"); // Use logger AND loggerChild logger.debug("Debug message 1"); loggerChild.debug("Debug message 1 child"); final List<LogEvent> events = app.getEvents(); assertEventCount(events, 2); Configurator.setLevel(logger.getName(), Level.ERROR); Configurator.setLevel(loggerChild.getName(), Level.DEBUG); logger.debug("Debug message 2"); loggerChild.debug("Debug message 2 child"); assertEventCount(events, 3); Configurator.setLevel(logger.getName(), Level.DEBUG); logger.debug("Debug message 3"); loggerChild.debug("Debug message 3 child"); assertEventCount(events, 5); }
@Test public void debugChangeLevelsMapChildLoggers() { logger.debug("Debug message 1"); loggerChild.debug("Debug message 1 C"); loggerGrandchild.debug("Debug message 1 GC"); final List<LogEvent> events = app.getEvents(); assertEventCount(events, 3); final Map<String, Level> map = new HashMap<>(); map.put(logger.getName(), Level.OFF); map.put(loggerChild.getName(), Level.DEBUG); map.put(loggerGrandchild.getName(), Level.WARN); Configurator.setLevel(map); logger.debug("Debug message 2"); loggerChild.debug("Debug message 2 C"); loggerGrandchild.debug("Debug message 2 GC"); assertEventCount(events, 4); map.put(logger.getName(), Level.DEBUG); map.put(loggerChild.getName(), Level.OFF); map.put(loggerGrandchild.getName(), Level.DEBUG); Configurator.setLevel(map); logger.debug("Debug message 3"); loggerChild.debug("Debug message 3 C"); loggerGrandchild.debug("Debug message 3 GC"); assertEventCount(events, 6); }
@Before public void setUp() throws Exception { Configurator .initialize("FastMQ", Thread.currentThread().getContextClassLoader(), "log4j2.xml"); CountDownLatch initLatch = new CountDownLatch(1); CuratorFramework curatorFramework = CuratorFrameworkFactory .newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3)); curatorFramework.start(); AsyncCuratorFramework asyncCuratorFramework = AsyncCuratorFramework.wrap(curatorFramework); when(offsetStorage.queryOffset(any())).thenReturn(new Offset()); ledgerManager = new LogManagerImpl("ledger-manager-read-test-name", new BookKeeperConfig(), new BookKeeper("127.0.0.1:2181"), asyncCuratorFramework, new LogInfoStorageImpl(asyncCuratorFramework), this.offsetStorage); ledgerManager.init(new CommonCallback<Void, LedgerStorageException>() { @Override public void onCompleted(Void data, Version version) { initLatch.countDown(); } @Override public void onThrowable(LedgerStorageException throwable) { throwable.printStackTrace(); initLatch.countDown(); } }); initLatch.await(); }
/** * When the user changes the log level and new {@link Runnable} command is added to {@link Settings}. * <p> * Command run when the user applies the change in setting. * * @param event action event */ @FXML public void onLogLevelChanged(final ActionEvent event) { settings.addRunnable(() -> { final String logLevel = choiceBox.getSelectionModel().getSelectedItem(); final Logger logger = LogManager.getRootLogger(); Configurator.setLevel(logger.getName(), Level.toLevel(logLevel)); LOGGER.info("Log level was set to: " + Level.toLevel(logLevel)); }); event.consume(); }
/** * Gets the test logger and assign the appender to it * * @param appender the name of the appender * @return the logger */ private Logger getLogger(String appender) { final LoggerContext loggerContext = Configurator.initialize(getUniqueMarker(), CONFIG_LOCATION); Logger logger = loggerContext.getLogger(appender); logger.getAppenders().clear(); logger.addAppender(loggerContext.getConfiguration().getAppenders().get(appender)); return logger; }
private static void registerShutdownHooks() { Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (LogManager.getContext() instanceof LoggerContext) { Configurator.shutdown((LoggerContext) LogManager.getContext()); } })); }
private static void registerLog4jShutdownHook() { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if( LogManager.getContext() instanceof LoggerContext) { Configurator.shutdown((LoggerContext)LogManager.getContext()); } } }); }
/** * 初始化日志配置 */ public static void initLog4j2WithoutConfigFile() { System.out.println("no local log4j2.xml file found,init logContext"); ConfigurationBuilder< BuiltConfiguration > builder = ConfigurationBuilderFactory.newConfigurationBuilder(); builder.setStatusLevel( Level.ERROR); builder.setConfigurationName("RollingBuilder"); // create the console appender AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT); appenderBuilder.add(builder.newLayout("PatternLayout"). addAttribute("pattern", "%d [%t] %-5level: %msg%n%throwable")); builder.add( appenderBuilder ); // LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout") // .addAttribute("pattern", "%d [%t] %-5level: %msg%n"); // ComponentBuilder triggeringPolicy = builder.newComponent("Policies") // .addComponent(builder.newComponent("CronTriggeringPolicy").addAttribute("schedule", "0 0 0 * * ?")) // .addComponent(builder.newComponent("SizeBasedTriggeringPolicy").addAttribute("size", "100M")); // appenderBuilder = builder.newAppender("rolling", "RollingFile") // .addAttribute("fileName", "target/rolling.log") // .addAttribute("filePattern", "target/archive/rolling-%d{MM-dd-yy}.log.gz") // .add(layoutBuilder) // .addComponent(triggeringPolicy); // builder.add(appenderBuilder); builder.add(builder.newRootLogger(Level.INFO).add(builder.newAppenderRef("Stdout"))); builder.add(builder.newLogger("com.jeesuite", Level.TRACE).add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false)); Configurator.initialize(builder.build()); }