Java 类org.apache.logging.log4j.core.config.Configurator 实例源码

项目:bt    文件:CliClient.java   
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);
}
项目:motu    文件:MotuWebEngineContextListener.java   
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();
    }
}
项目:fastmq    文件:ZkOffsetStorageImplTest.java   
@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);
}
项目:cas-5.1.0    文件:ControllerUtils.java   
/**
 * 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;
}
项目:csap-core    文件:ServiceCollector.java   
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 );
}
项目:TLS-Attacker    文件:GeneralAttackDelegate.java   
@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();
}
项目:mycore    文件:MCRLoggingCommands.java   
/**
 * @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);
}
项目:coca    文件:CocaRMQSub.java   
/**
 * @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);
}
项目:coca    文件:SampleMain.java   
/**
 * @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();
}
项目:ignite    文件:Log4J2Logger.java   
/**
 * 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;
}
项目:ignite    文件:Log4J2Logger.java   
/**
 * 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();
}
项目:ignite    文件:Log4J2Logger.java   
/**
 * 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();
}
项目:remote-procedure-call    文件:Main.java   
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());
        }
    });
}
项目:log4j2    文件:Log4jInitPerformance.java   
@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");
}
项目:log4j2    文件:ConsoleAppenderAnsiStyleJira319Main.java   
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);
    }
}
项目:log4j2    文件:ConsoleAppenderAnsiStyleJira180Main.java   
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);
    }
}
项目:log4j2    文件:ConsoleAppenderAnsiStyleLayoutMain.java   
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);
    }
}
项目:log4j2    文件:ConsoleAppenderAnsiStyleJira272Main.java   
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);
    }
}
项目:log4j2    文件:StructuredDataFilterTest.java   
@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);
}
项目:logging-log4j2    文件:ConfigurationAssemblerTest.java   
@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);
    }
}
项目:logging-log4j2    文件:Log4jWebInitializerImpl.java   
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);
}
项目:logging-log4j2    文件:ConsoleAppenderAnsiStyleJira319Main.java   
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.");
    }
}
项目:logging-log4j2    文件:ProgressConsoleTest.java   
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();
            }
        }
    }
}
项目:logging-log4j2    文件:ConsoleAppenderJAnsiXExceptionMain.java   
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);
    }
}
项目:logging-log4j2    文件:ConsoleAppenderAnsiStyleJira180Main.java   
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);
        }
    }
}
项目:logging-log4j2    文件:ConsoleAppenderNoAnsiStyleLayoutMain.java   
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));
    }
}
项目:logging-log4j2    文件:ConsoleAppenderJAnsiMessageMain.java   
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());
        }
    }
}
项目:logging-log4j2    文件:ConsoleAppenderAnsiStyleLayoutMain.java   
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"));
    }
}
项目:logging-log4j2    文件:ConsoleAppenderAnsiStyleJira272Main.java   
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.");
    }
}
项目:logging-log4j2    文件:DynamicThresholdFilterTest.java   
@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());
    }
}
项目:logging-log4j2    文件:LoggerTest.java   
@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);
}
项目:logging-log4j2    文件:LoggerTest.java   
@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);
}
项目:logging-log4j2    文件:LoggerTest.java   
@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);
}
项目:logging-log4j2    文件:LoggerTest.java   
@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);
}
项目:fastmq    文件:LogManagerImplTest.java   
@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();
}
项目:hygene    文件:LoggingSettingsViewController.java   
/**
 * 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();
}
项目:es-log4j2-appender    文件:ElasticSearchRestAppenderTest.java   
/**
 * 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;
}
项目:Biliomi    文件:BiliomiContainer.java   
private static void registerShutdownHooks() {
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    if (LogManager.getContext() instanceof LoggerContext) {
      Configurator.shutdown((LoggerContext) LogManager.getContext());
    }
  }));
}
项目:bt    文件:CliClient.java   
private static void registerLog4jShutdownHook() {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if( LogManager.getContext() instanceof LoggerContext) {
                Configurator.shutdown((LoggerContext)LogManager.getContext());
            }
        }
    });
}
项目:jeesuite-libs    文件:LogContextInitializer.java   
/**
     * 初始化日志配置
     */
    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());
    }