Java 类org.apache.logging.log4j.core.appender.ConsoleAppender 实例源码

项目:JukeBot    文件:Log4JConfig.java   
private Configuration createConfiguration(final String name, ConfigurationBuilder<BuiltConfiguration> builder) {

        builder.setConfigurationName(name);
        /* Only internal Log4J2 messages with level ERROR will be logged */
        builder.setStatusLevel(Level.ERROR);
        /* Create appender that logs to System.out */
        AppenderComponentBuilder appenderBuilder = builder.newAppender("STDOUT", "CONSOLE")
                .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
        /* Create pattern for log messages */
        appenderBuilder.add(builder.newLayout("PatternLayout")
                .addAttribute("pattern", "[%d{HH:mm:ss}] (%c{1}) [%level] %msg%n%throwable"));
                                         /*timestamp  logger name  level   log message & optional throwable */
        builder.add(appenderBuilder);
        /* Create logger that uses STDOUT appender */
        builder.add(builder.newLogger("JukeBot", JUKEBOT_LOG_LEVEL)
                .add(builder.newAppenderRef("STDOUT"))
                .addAttribute("additivity", false));

        /* Create root logger--messages not from the above logger will all go through this one */
        builder.add(builder.newRootLogger(LIB_LOG_LEVEL).add(builder.newAppenderRef("STDOUT")));
        return builder.build();
    }
项目:coteafs-logger    文件:ConfigBuilder.java   
private static <T, K extends ComponentBuilder <K>> void addAttributes (final ComponentBuilder <K> appender,
        final Map <String, T> attributes) {
    for (final Entry <String, T> entry : attributes.entrySet ()) {
        final String key = entry.getKey ();
        final T val = entry.getValue ();
        boolean isEnum = false;
        for (final Target target : ConsoleAppender.Target.values ())
            if (target  .name ()
                        .equalsIgnoreCase (val.toString ())) {
                appender.addAttribute (key, Target.valueOf (val.toString ()));
                isEnum = true;
            }
        if (!isEnum) {
            if (val instanceof Status) {
                appender.addAttribute (key, ((Status) val).getStatus ());
            }
            else {
                appender.addAttribute (key, val);
            }
        }
    }
}
项目:logredactor    文件:Log4j2RedactorTest.java   
protected Configuration buildConfiguration() {
  ConfigurationBuilder<BuiltConfiguration> builder = newConfigurationBuilder();
  builder.setConfigurationName(Log4j2RedactorTest.class.getName());
  builder.setStatusLevel(Level.INFO);

  AppenderComponentBuilder appenderBuilder = builder.newAppender("Stderr", "CONSOLE")
      .addAttribute("target", ConsoleAppender.Target.SYSTEM_ERR);
  appenderBuilder.add(builder.newLayout("PatternLayout")
      .addAttribute("pattern", "%msg"));
  builder.add(appenderBuilder);

  AppenderComponentBuilder rewriteBuilder = builder.newAppender("Redactor", "Rewrite")
      .addComponent(builder.newComponent("RedactorPolicy", "RedactorPolicy")
          .addAttribute("rules", resourcePath + getPolicyFilename()))
      .addComponent(builder.newAppenderRef("Stderr"));
  builder.add(rewriteBuilder);

  builder.add(builder.newRootLogger(Level.INFO)
      .add(builder.newAppenderRef("Redactor")));

  return builder.build();
}
项目:homework_tester    文件:Main.java   
private static Logger configureLog4j() {
    LoggerContext context = (LoggerContext) LogManager.getContext();
    Configuration config = context.getConfiguration();

    PatternLayout layout = PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(), false, false, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null);
    appender.start();
    AppenderRef ref = AppenderRef.createAppenderRef("CONSOLE_APPENDER", null, null);
    AppenderRef[] refs = new AppenderRef[]{ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "CONSOLE_LOGGER", "com", refs, null, null, null);
    loggerConfig.addAppender(appender, null, null);

    config.addAppender(appender);
    config.addLogger("Main.class", loggerConfig);
    context.updateLoggers(config);
    return LogManager.getContext().getLogger("Main.class");
}
项目:homework_tester    文件:Main.java   
private static Logger configureLog4j() {
    LoggerContext context = (LoggerContext) LogManager.getContext();
    Configuration config = context.getConfiguration();

    PatternLayout layout = PatternLayout.createLayout("%m%n", null, null, Charset.defaultCharset(), false, false, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null);
    appender.start();
    AppenderRef ref = AppenderRef.createAppenderRef("CONSOLE_APPENDER", null, null);
    AppenderRef[] refs = new AppenderRef[]{ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "CONSOLE_LOGGER", "com", refs, null, null, null);
    loggerConfig.addAppender(appender, null, null);

    config.addAppender(appender);
    config.addLogger("Main.class", loggerConfig);
    context.updateLoggers(config);
    return LogManager.getContext().getLogger("Main.class");
}
项目:iotracah    文件:IOTracah.java   
public static void main(String[] args) throws UnRetriableException{

        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();
        ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(PatternLayout.createDefaultLayout());
        appender.start();
        config.addAppender(appender);
        AppenderRef[] refs = new AppenderRef[] { AppenderRef.createAppenderRef(appender.getName(), null, null) };
        LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null);
        loggerConfig.addAppender(appender, null, null);
        config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig);
        ctx.updateLoggers();


        Runner runner = defaultRunner();
        runner.init();
        runner.start();

    }
项目:iotracah    文件:IOTracah.java   
public static void main(String[] args) throws UnRetriableException {


        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();
        ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(PatternLayout.createDefaultLayout());
        appender.start();
        config.addAppender(appender);
        AppenderRef[] refs = new AppenderRef[] { AppenderRef.createAppenderRef(appender.getName(), null, null) };
        LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.WARN, LogManager.ROOT_LOGGER_NAME, "true", refs, null, config, null);
        loggerConfig.addAppender(appender, null, null);
        config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig);
        ctx.updateLoggers();


        Runner runner = defaultRunner();
        runner.init();
        runner.start();

    }
项目:ModJam-4    文件:BloodStains.java   
@Mod.EventHandler
   public void preInit(FMLPreInitializationEvent event)
   {
       // logging stuff.
       if (!FMLForgePlugin.RUNTIME_DEOBF) // not runtime deobf = dev env
       {
           String packageName = this.getClass().getPackage().getName();
           Logger baseLogger = (Logger) LogManager.getLogger(packageName);
           ConsoleAppender appender = ConsoleAppender.createAppender(null, null, Target.SYSTEM_OUT.toString(), "console", "true", "false");
           baseLogger.addAppender(appender);
           baseLogger.setLevel(Level.DEBUG);
           appender.start();

           // testing levels..
           for (Level l : Level.values())
           {
               baseLogger.log(l, "TESTING {} on level {}", baseLogger.getName(), l);
               LogManager.getLogger().log(l, "TESTING {} on level {}", this.getClass().getName(), l);
           }
       }

    Configuration c = new Configuration(event.getSuggestedConfigurationFile());
    OUR_SERVER = c.get("main", "globalbloodstain", 1, "Turn on global bloodstains?0=no, 1=yes").getInt() == 0 ? false : true;
    c.save();
}
项目:log4j2    文件:BaseConfiguration.java   
private void setToDefault() {
    setName(DefaultConfiguration.DEFAULT_NAME);
    final Layout<? extends Serializable> layout =
            PatternLayout.createLayout("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n",
                    null, null, null, null);
    final Appender appender = ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "false",
        "true");
    appender.start();
    addAppender(appender);
    final LoggerConfig root = getRootLogger();
    root.addAppender(appender, null, null);

    final String levelName = PropertiesUtil.getProperties().getStringProperty(DefaultConfiguration.DEFAULT_LEVEL);
    final Level level = levelName != null && Level.valueOf(levelName) != null ?
        Level.valueOf(levelName) : Level.ERROR;
    root.setLevel(level);
}
项目:log4j2    文件:DefaultConfiguration.java   
/**
 * Constructor to create the default configuration.
 */
public DefaultConfiguration() {

    setName(DEFAULT_NAME);
    final Layout<? extends Serializable> layout =
            PatternLayout.createLayout("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n", null, null, null, null);
    final Appender appender =
            ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "false", "true");
    appender.start();
    addAppender(appender);
    final LoggerConfig root = getRootLogger();
    root.addAppender(appender, null, null);

    final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL);
    final Level level = levelName != null && Level.valueOf(levelName) != null ?
        Level.valueOf(levelName) : Level.ERROR;
    root.setLevel(level);
}
项目:logging-log4j2    文件:CustomConfiguration.java   
/**
 * Constructor to create the default configuration.
 */
public CustomConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
    super(loggerContext, source);

    setName(CONFIG_NAME);
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
            .withPattern(DEFAULT_PATTERN)
            .withConfiguration(this)
            .build();
    final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    appender.start();
    addAppender(appender);
    final LoggerConfig root = getRootLogger();
    root.addAppender(appender, null, null);

    final String levelName = PropertiesUtil.getProperties().getStringProperty(DEFAULT_LEVEL);
    final Level level = levelName != null && Level.valueOf(levelName) != null ?
            Level.valueOf(levelName) : Level.ERROR;
    root.setLevel(level);
}
项目:logging-log4j2    文件:AbstractConfiguration.java   
protected void setToDefault() {
    // LOG4J2-1176 facilitate memory leak investigation
    setName(DefaultConfiguration.DEFAULT_NAME + "@" + Integer.toHexString(hashCode()));
    final Layout<? extends Serializable> layout = PatternLayout.newBuilder()
            .withPattern(DefaultConfiguration.DEFAULT_PATTERN)
            .withConfiguration(this)
            .build();
    final Appender appender = ConsoleAppender.createDefaultAppenderForLayout(layout);
    appender.start();
    addAppender(appender);
    final LoggerConfig rootLoggerConfig = getRootLogger();
    rootLoggerConfig.addAppender(appender, null, null);

    final Level defaultLevel = Level.ERROR;
    final String levelName = PropertiesUtil.getProperties().getStringProperty(DefaultConfiguration.DEFAULT_LEVEL,
            defaultLevel.name());
    final Level level = Level.valueOf(levelName);
    rootLoggerConfig.setLevel(level != null ? level : defaultLevel);
}
项目:logging-log4j2    文件:TestConfigurator.java   
@Test
public void testBuilder() throws Exception {
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(Level.ERROR);
    builder.setConfigurationName("BuilderTest");
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
            .addAttribute("level", Level.DEBUG));
    final 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"));
    appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY,
            Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
    builder.add(appenderBuilder);
    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG).
            add(builder.newAppenderRef("Stdout")).
            addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));
    ctx = Configurator.initialize(builder.build());
    final Configuration config = ctx.getConfiguration();
    assertNotNull("No configuration", config);
    assertEquals("Unexpected Configuration", "BuilderTest", config.getName());
    assertThat(config.getAppenders(), hasSize(equalTo(1)));
}
项目:logging-log4j2    文件:ConfigurationBuilderTest.java   
private void addTestFixtures(final String name, final ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    builder.setShutdownTimeout(5000, TimeUnit.MILLISECONDS);
    builder.add(builder.newScriptFile("target/test-classes/scripts/filter.groovy").addIsWatched(true));
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
            .addAttribute("level", Level.DEBUG));

    final 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"));
    appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY,
            Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
    builder.add(appenderBuilder);

    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG, true).
                add(builder.newAppenderRef("Stdout")).
                addAttribute("additivity", false));
    builder.add(builder.newLogger("org.apache.logging.log4j.core").
                add(builder.newAppenderRef("Stdout")));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));

    builder.addProperty("MyKey", "MyValue");
    builder.add(builder.newCustomLevel("Panic", 17));
    builder.setPackages("foo,bar");
}
项目:logging-log4j2    文件:CustomConfigurationFactory.java   
public static Configuration addTestFixtures(final String name, final ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    builder.add(builder.newScriptFile("target/test-classes/scripts/filter.groovy").addIsWatched(true));
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
            .addAttribute("level", Level.DEBUG));

    final 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"));
    appenderBuilder.add(builder.
            newFilter("MarkerFilter", Filter.Result.DENY, Filter.Result.NEUTRAL).
            addAttribute("marker", "FLOW"));
    builder.add(appenderBuilder);

    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG, true).
                add(builder.newAppenderRef("Stdout")).
                addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));

    builder.add(builder.newCustomLevel("Panic", 17));

    return builder.build();
}
项目:logging-log4j2    文件:RollingFileAppenderUpdateDataTest.java   
private ConfigurationBuilder<BuiltConfiguration> buildConfigurationBuilder(final String filePattern) {
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setConfigurationName("LOG4J2-1964 demo");
    builder.setStatusLevel(Level.ERROR);
    // @formatter:off
    builder.add(builder.newAppender("consoleLog", "Console")
        .addAttribute("target", ConsoleAppender.Target.SYSTEM_ERR));
    builder.add(builder.newAppender("fooAppender", "RollingFile")
            .addAttribute("fileName", "target/rolling-update-date/foo.log")
            .addAttribute("filePattern", filePattern)
            .addComponent(builder.newComponent("SizeBasedTriggeringPolicy")
                    .addAttribute("size", "10MB")));
    builder.add(builder.newRootLogger(Level.INFO)
            .add(builder.newAppenderRef("consoleLog"))
            .add(builder.newAppenderRef("fooAppender")));
    // @formatter:on
    return builder;
}
项目:elasticsearch_my    文件:EvilLoggerTests.java   
public void testFindAppender() throws IOException, UserException {
    setupLogging("find_appender");

    final Logger hasConsoleAppender = ESLoggerFactory.getLogger("has_console_appender");

    final Appender testLoggerConsoleAppender = Loggers.findAppender(hasConsoleAppender, ConsoleAppender.class);
    assertNotNull(testLoggerConsoleAppender);
    assertThat(testLoggerConsoleAppender.getName(), equalTo("console"));
    final Logger hasCountingNoOpAppender = ESLoggerFactory.getLogger("has_counting_no_op_appender");
    assertNull(Loggers.findAppender(hasCountingNoOpAppender, ConsoleAppender.class));
    final Appender countingNoOpAppender = Loggers.findAppender(hasCountingNoOpAppender, CountingNoOpAppender.class);
    assertThat(countingNoOpAppender.getName(), equalTo("counting_no_op"));
}
项目:datarouter    文件:Log4j2Configurator.java   
public static ConsoleAppender createConsoleAppender(String name, Target target, String pattern){
    PatternLayout layout = createLayout(pattern);
    return ConsoleAppender.newBuilder()
            .withLayout(layout)
            .setTarget(target)
            .withName(name)
            .build();
}
项目:TLS-Attacker    文件:ExecutionRecorder.java   
private void addFollowConsoleAppender() {
    final LoggerContext context = LoggerContext.getContext(false);
    final Configuration config = context.getConfiguration();
    final PatternLayout layout = PatternLayout.newBuilder().withPattern("%-5level %c{-4} - %msg%n").build();
    Appender appender = ConsoleAppender.newBuilder().setFollow(true).setTarget(ConsoleAppender.Target.SYSTEM_OUT)
            .withName("ExecutionRecorder").withLayout(layout).build();
    appender.start();
    config.addAppender(appender);
    config.getRootLogger().addAppender(appender, logLevel, null);
}
项目: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());
    }
项目:log4j-configuration-builder    文件:ConfigurationBuilder.java   
/**
 * Creates an instance of {@link ConsoleAppender}.
 * 
 * @param layout the {@link PatternLayout} to use
 * @param name the name of the appender
 * @return an instance of {@link ConsoleAppender}
 */
protected static ConsoleAppender createConsoleAppender(PatternLayout layout, String name) {
  Filter filter = null;
  String targetStr = Target.SYSTEM_OUT.toString();
  String follow = Boolean.FALSE.toString();
  String ignore = Boolean.FALSE.toString();
  return ConsoleAppender.createAppender(layout, filter, targetStr, name, follow, ignore);
}
项目:ignite    文件:Log4J2Logger.java   
/**
 * Creates console appender with some reasonable default logging settings.
 *
 * @return Logger with auto configured console appender.
 */
public Logger createConsoleLogger() {
    // from http://logging.apache.org/log4j/2.x/manual/customconfig.html
    final LoggerContext ctx = impl.getContext();

    final Configuration cfg = ctx.getConfiguration();

    PatternLayout.Builder builder = PatternLayout.newBuilder()
        .withPattern("%d{ISO8601}][%-5p][%t][%c{1}] %m%n")
        .withCharset(Charset.defaultCharset())
        .withAlwaysWriteExceptions(false)
        .withNoConsoleNoAnsi(false);

    PatternLayout layout = builder.build();

    ConsoleAppender.Builder consoleAppenderBuilder = ConsoleAppender.newBuilder()
        .withName(CONSOLE_APPENDER)
        .withLayout(layout);

    ConsoleAppender consoleApp = consoleAppenderBuilder.build();

    consoleApp.start();

    cfg.addAppender(consoleApp);
    cfg.getRootLogger().addAppender(consoleApp, Level.TRACE, null);

    ctx.updateLoggers(cfg);

    return ctx.getRootLogger();
}
项目:ldbc_graphalytics    文件:LogUtil.java   
public static void appendSimplifiedConsoleLogger(Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.createLayout("%msg%n", null, config, null, null, true, false, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, ConsoleAppender.Target.SYSTEM_OUT, "stdout", true, true);
    appender.start();

    config.getRootLogger().addAppender(appender, level, null);
    ctx.updateLoggers();
}
项目:ldbc_graphalytics    文件:LogUtil.java   
public static void appendConsoleLogger(Level level) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.createLayout("%highlight{%d{HH:mm} [%-5p] %msg%n}{STYLE=Logback}", null, config, null, null, true, true, null, null);
    Appender appender = ConsoleAppender.createAppender(layout, null, ConsoleAppender.Target.SYSTEM_OUT, "stdout", true, true);
    appender.start();

    config.getRootLogger().addAppender(appender, level, null);
    ctx.updateLoggers();
}
项目:oxCore    文件:LoggingHelper.java   
public static void configureConsoleAppender() {
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    AbstractConfiguration config = (AbstractConfiguration) ctx.getConfiguration();
    ConsoleAppender appender = ConsoleAppender.createDefaultAppenderForLayout(PatternLayout.createDefaultLayout());
    appender.start();
    config.addAppender(appender);
    AppenderRef[] refs = new AppenderRef[] { AppenderRef.createAppenderRef(appender.getName(), null, null) };
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.ALL, LogManager.ROOT_LOGGER_NAME, "true",
            refs, null, config, null);
    loggerConfig.addAppender(appender, null, null);
    config.addLogger(LogManager.ROOT_LOGGER_NAME, loggerConfig);
    ctx.updateLoggers();
}
项目:log4j2    文件:AbstractSocketServerTest.java   
protected void testServer(final String message1, final String message2) throws Exception {
    final Filter socketFilter = new ThreadFilter(Filter.Result.NEUTRAL, Filter.Result.DENY);
    final Filter serverFilter = new ThreadFilter(Filter.Result.DENY, Filter.Result.NEUTRAL);
    final SocketAppender appender = SocketAppender.createAppender("localhost", this.port, this.protocol, "-1", null, "Test", null,
            "false", null, socketFilter, null, null);
    appender.start();
    final ListAppender listApp = new ListAppender("Events", serverFilter, null, false, false);
    listApp.start();
    final PatternLayout layout = PatternLayout.createLayout("%m %ex%n", null, null, null, null);
    final ConsoleAppender console = ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "false", "true");
    final Logger serverLogger = ctx.getLogger(this.getClass().getName());
    serverLogger.addAppender(console);
    serverLogger.setAdditive(false);

    // set appender on root and set level to debug
    root.addAppender(appender);
    root.addAppender(listApp);
    root.setAdditive(false);
    root.setLevel(Level.DEBUG);
    root.debug(message1);
    root.debug(message2);
    Thread.sleep(100);
    final List<LogEvent> events = listApp.getEvents();
    assertNotNull("No event retrieved", events);
    assertTrue("No events retrieved", events.size() > 0);
    assertTrue("Incorrect event", events.get(0).getMessage().getFormattedMessage().equals(message1));
    assertTrue("Incorrect number of events received: " + events.size(), events.size() == 2);
    assertTrue("Incorrect event", events.get(1).getMessage().getFormattedMessage().equals(message2));
}
项目:log4j2    文件:JMSQueueTest.java   
@Test
public void testServer() throws Exception {
    final Filter clientFilter = new MessageFilter(Filter.Result.NEUTRAL, Filter.Result.DENY);
    final Filter serverFilter = new MessageFilter(Filter.Result.DENY, Filter.Result.NEUTRAL);
    final CompositeFilter clientFilters = CompositeFilter.createFilters(new Filter[]{clientFilter});
    final JMSQueueAppender appender = JMSQueueAppender.createAppender("Test", null, null, null, null, null, FACTORY_NAME,
            QUEUE_NAME, null, null, null, clientFilters, "true");
    appender.start();
    final CompositeFilter serverFilters = CompositeFilter.createFilters(new Filter[]{serverFilter});
    final ListAppender listApp = new ListAppender("Events", serverFilters, null, false, false);
    listApp.start();
    final PatternLayout layout = PatternLayout.createLayout("%m %ex%n", null, null, null, null);
    final ConsoleAppender console = ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "false", "true");
    console.start();
    final Logger serverLogger = ctx.getLogger(JMSTopicReceiver.class.getName());
    serverLogger.addAppender(console);
    serverLogger.setAdditive(false);


    // set appender on root and set level to debug
    root.addAppender(listApp);
    root.addAppender(appender);
    root.setAdditive(false);
    root.setLevel(Level.DEBUG);
    root.debug("This is a test message");
    Thread.sleep(100);
    final List<LogEvent> events = listApp.getEvents();
    assertNotNull("No event retrieved", events);
    assertTrue("No events retrieved", events.size() > 0);
    assertTrue("Incorrect event", events.get(0).getMessage().getFormattedMessage().equals("This is a test message"));
}
项目:log4j2    文件:JMSTopicTest.java   
@Test
public void testServer() throws Exception {
    final Filter clientFilter = new MessageFilter(Filter.Result.NEUTRAL, Filter.Result.DENY);
    final Filter serverFilter = new MessageFilter(Filter.Result.DENY, Filter.Result.NEUTRAL);
    final CompositeFilter clientFilters = CompositeFilter.createFilters(new Filter[]{clientFilter});
    final JMSTopicAppender appender = JMSTopicAppender.createAppender("Test", null, null, null, null, null, FACTORY_NAME,
            TOPIC_NAME, null, null, null, clientFilters, "true");
    appender.start();
    final CompositeFilter serverFilters = CompositeFilter.createFilters(new Filter[]{serverFilter});
    final ListAppender listApp = new ListAppender("Events", serverFilters, null, false, false);
    listApp.start();
    final PatternLayout layout = PatternLayout.createLayout("%m %ex%n", null, null, null, null);
    final ConsoleAppender console =
            ConsoleAppender.createAppender(layout, null, "SYSTEM_OUT", "Console", "false", "true");
    console.start();
    final Logger serverLogger = ctx.getLogger(JMSTopicReceiver.class.getName());
    serverLogger.addAppender(console);
    serverLogger.setAdditive(false);


    // set appender on root and set level to debug
    root.addAppender(listApp);
    root.addAppender(appender);
    root.setAdditive(false);
    root.setLevel(Level.DEBUG);
    root.debug("This is a test message");
    Thread.sleep(100);
    final List<LogEvent> events = listApp.getEvents();
    assertNotNull("No event retrieved", events);
    assertTrue("No events retrieved", events.size() > 0);
    assertTrue("Incorrect event", events.get(0).getMessage().getFormattedMessage().equals("This is a test message"));
}
项目:logging-log4j2    文件:Log4j1ConfigurationParser.java   
private void buildConsoleAppender(final String appenderName) {
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(appenderName, ConsoleAppender.PLUGIN_NAME);
    final String targetValue = getLog4jAppenderValue(appenderName, "Target", "System.out");
    if (targetValue != null) {
        final ConsoleAppender.Target target;
        switch (targetValue) {
        case "System.out":
            target = ConsoleAppender.Target.SYSTEM_OUT;
            break;
        case "System.err":
            target = ConsoleAppender.Target.SYSTEM_ERR;
            break;
        default:
            reportWarning("Unknown value for console Target: " + targetValue);
            target = null;
        }
        if (target != null) {
            appenderBuilder.addAttribute("target", target);
        }
    }
    buildAttribute(appenderName, appenderBuilder, "Follow", "follow");
    if (FALSE.equalsIgnoreCase(getLog4jAppenderValue(appenderName, "ImmediateFlush"))) {
        reportWarning("ImmediateFlush=false is not supported on Console appender");
    }
    buildAppenderLayout(appenderName, appenderBuilder);
    builder.add(appenderBuilder);
}
项目:logging-log4j2    文件:Log4j1ConfigurationFactoryTest.java   
private Layout<?> testConsole(final String configResource) throws Exception {
    final Configuration configuration = getConfiguration(configResource);
    final String name = "Console";
    final ConsoleAppender appender = configuration.getAppender(name);
    assertNotNull("Missing appender '" + name + "' in configuration " + configResource + " → " + configuration,
            appender);
    assertEquals(Target.SYSTEM_ERR, appender.getTarget());
    //
    final LoggerConfig loggerConfig = configuration.getLoggerConfig("com.example.foo");
    assertNotNull(loggerConfig);
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    configuration.start();
    configuration.stop();
    return appender.getLayout();
}
项目:logging-log4j2    文件:ConfigurationBuilderTest.java   
private void addTestFixtures(final String name, final ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    builder.setShutdownTimeout(5000, TimeUnit.MILLISECONDS);
    builder.add(builder.newScriptFile("target/test-classes/scripts/filter.groovy").addIsWatched(true));
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
            .addAttribute("level", Level.DEBUG));

    final 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"));
    appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY,
            Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
    builder.add(appenderBuilder);

    final AppenderComponentBuilder appenderBuilder2 = builder.newAppender("Kafka", "Kafka").addAttribute("topic", "my-topic");
    appenderBuilder2.addComponent(builder.newProperty("bootstrap.servers", "localhost:9092"));
    appenderBuilder2.add(builder.newLayout("GelfLayout").
        addAttribute("host", "my-host").
        addComponent(builder.newKeyValuePair("extraField", "extraValue")));
    builder.add(appenderBuilder2);

    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG, true).
                add(builder.newAppenderRef("Stdout")).
                addAttribute("additivity", false));
    builder.add(builder.newLogger("org.apache.logging.log4j.core").
                add(builder.newAppenderRef("Stdout")));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));

    builder.addProperty("MyKey", "MyValue");
    builder.add(builder.newCustomLevel("Panic", 17));
    builder.setPackages("foo,bar");
}
项目:logging-log4j2    文件:CustomConfigurationFactory.java   
static Configuration addTestFixtures(final String name, final ConfigurationBuilder<BuiltConfiguration> builder) {
    builder.setConfigurationName(name);
    builder.setStatusLevel(Level.ERROR);
    builder.add(builder.newScriptFile("target/test-classes/scripts/filter.groovy").addIsWatched(true));
    builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
            .addAttribute("level", Level.DEBUG));

    final 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"));
    appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY,
            Filter.Result.NEUTRAL).addAttribute("marker", "FLOW"));
    builder.add(appenderBuilder);

    final AppenderComponentBuilder appenderBuilder2 = builder.newAppender("Kafka", "Kafka").addAttribute("topic", "my-topic");
    appenderBuilder2.addComponent(builder.newProperty("bootstrap.servers", "localhost:9092"));
    appenderBuilder2.add(builder.newLayout("GelfLayout").
        addAttribute("host", "my-host").
        addComponent(builder.newKeyValuePair("extraField", "extraValue")));
    builder.add(appenderBuilder2);

    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG, true).
                add(builder.newAppenderRef("Stdout")).
                addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));

    builder.add(builder.newCustomLevel("Panic", 17));

    return builder.build();
}
项目:logging-log4j2    文件:CompositeConfigurationTest.java   
@Test
public void compositeLogger() {
    final LoggerContextRule lcr = new LoggerContextRule("classpath:log4j-comp-logger.xml,log4j-comp-logger.json");
    final Statement test = new Statement() {
        @Override
        public void evaluate() throws Throwable {
            final CompositeConfiguration config = (CompositeConfiguration) lcr.getConfiguration();
            Map<String, Appender> appendersMap = config.getLogger("cat1").getAppenders();
            assertEquals("Expected 2 Appender references for cat1 but got " + appendersMap.size(), 2,
                    appendersMap.size());
            assertTrue(appendersMap.get("STDOUT") instanceof ConsoleAppender);

            Filter loggerFilter = config.getLogger("cat1").getFilter();
            assertTrue(loggerFilter instanceof RegexFilter);
            assertEquals(loggerFilter.getOnMatch(), Filter.Result.DENY);

            appendersMap = config.getLogger("cat2").getAppenders();
            assertEquals("Expected 1 Appender reference for cat2 but got " + appendersMap.size(), 1,
                    appendersMap.size());
            assertTrue(appendersMap.get("File") instanceof FileAppender);

            appendersMap = config.getLogger("cat3").getAppenders();
            assertEquals("Expected 1 Appender reference for cat3 but got " + appendersMap.size(), 1,
                    appendersMap.size());
            assertTrue(appendersMap.get("File") instanceof FileAppender);

            appendersMap = config.getRootLogger().getAppenders();
            assertEquals("Expected 2 Appender references for the root logger but got " + appendersMap.size(), 2,
                    appendersMap.size());
            assertTrue(appendersMap.get("File") instanceof FileAppender);
            assertTrue(appendersMap.get("STDOUT") instanceof ConsoleAppender);
        }
    };
    runTest(lcr, test);
}
项目:logging-log4j2    文件:TestConfigurator.java   
@Test
public void testBuilderWithScripts() throws Exception {
    final String script = "if (logEvent.getLoggerName().equals(\"NoLocation\")) {\n" +
            "                return \"NoLocation\";\n" +
            "            } else if (logEvent.getMarker() != null && logEvent.getMarker().isInstanceOf(\"FLOW\")) {\n" +
            "                return \"Flow\";\n" +
            "            } else {\n" +
            "                return null;\n" +
            "            }";
    final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
    builder.setStatusLevel(Level.ERROR);
    builder.setConfigurationName("BuilderTest");
    builder.add(builder.newScriptFile("filter.groovy", "target/test-classes/scripts/filter.groovy").addIsWatched(true));
    final AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE").addAttribute("target",
            ConsoleAppender.Target.SYSTEM_OUT);
    appenderBuilder.add(builder.newLayout("PatternLayout").
            addComponent(builder.newComponent("ScriptPatternSelector")
                    .addAttribute("defaultPattern", "[%-5level] %c{1.} %C{1.}.%M.%L %msg%n")
                    .addComponent(builder.newComponent("PatternMatch").addAttribute("key", "NoLocation")
                            .addAttribute("pattern", "[%-5level] %c{1.} %msg%n"))
                    .addComponent(builder.newComponent("PatternMatch").addAttribute("key", "FLOW")
                            .addAttribute("pattern", "[%-5level] %c{1.} ====== %C{1.}.%M:%L %msg ======%n"))
                    .addComponent(builder.newComponent("selectorScript", "Script", script).addAttribute("language", "beanshell"))));
    appenderBuilder.add(builder.newFilter("ScriptFilter", Filter.Result.DENY,
            Filter.Result.NEUTRAL).addComponent(builder.newComponent("ScriptRef").addAttribute("ref", "filter.groovy")));
    builder.add(appenderBuilder);
    builder.add(builder.newLogger("org.apache.logging.log4j", Level.DEBUG).
            add(builder.newAppenderRef("Stdout")).
            addAttribute("additivity", false));
    builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));
    ctx = Configurator.initialize(builder.build());
    final Configuration config = ctx.getConfiguration();
    assertNotNull("No configuration", config);
    assertEquals("Unexpected Configuration", "BuilderTest", config.getName());
    assertThat(config.getAppenders(), hasSize(equalTo(1)));
    assertNotNull("Filter script not found", config.getScriptManager().getScript("filter.groovy"));
    assertNotNull("pattern selector script not found", config.getScriptManager().getScript("selectorScript"));
}
项目:logging-log4j2    文件:ConfigurationAssemblerTest.java   
private void validate(final Configuration config) {
    assertNotNull(config);
    assertNotNull(config.getName());
    assertFalse(config.getName().isEmpty());
    assertNotNull("No configuration created", config);
    assertEquals("Incorrect State: " + config.getState(), config.getState(), LifeCycle.State.STARTED);
    final Map<String, Appender> appenders = config.getAppenders();
    assertNotNull(appenders);
    assertTrue("Incorrect number of Appenders: " + appenders.size(), appenders.size() == 1);
    final ConsoleAppender consoleAppender = (ConsoleAppender)appenders.get("Stdout");
    final PatternLayout gelfLayout = (PatternLayout)consoleAppender.getLayout();
    final Map<String, LoggerConfig> loggers = config.getLoggers();
    assertNotNull(loggers);
    assertTrue("Incorrect number of LoggerConfigs: " + loggers.size(), loggers.size() == 2);
    final LoggerConfig rootLoggerConfig = loggers.get("");
    assertEquals(Level.ERROR, rootLoggerConfig.getLevel());
    assertFalse(rootLoggerConfig.isIncludeLocation());
    final LoggerConfig loggerConfig = loggers.get("org.apache.logging.log4j");
    assertEquals(Level.DEBUG, loggerConfig.getLevel());
    assertTrue(loggerConfig.isIncludeLocation());
    final Filter filter = config.getFilter();
    assertNotNull("No Filter", filter);
    assertTrue("Not a Threshold Filter", filter instanceof ThresholdFilter);
    final List<CustomLevelConfig> customLevels = config.getCustomLevels();
    assertNotNull("No CustomLevels", filter);
    assertEquals(1, customLevels.size());
    final CustomLevelConfig customLevel = customLevels.get(0);
    assertEquals("Panic", customLevel.getLevelName());
    assertEquals(17, customLevel.getIntLevel());
    final Logger logger = LogManager.getLogger(getClass());
    logger.info("Welcome to Log4j!");
}
项目:logging-log4j2    文件:LookupTest.java   
@Test
public void testHostname() {
    final ConsoleAppender app = context.getRequiredAppender("console", ConsoleAppender.class);
    final Layout<?> layout = app.getLayout();
    assertNotNull("No Layout", layout);
    assertTrue("Layout is not a PatternLayout", layout instanceof PatternLayout);
    final String pattern = ((PatternLayout) layout).getConversionPattern();
    assertNotNull("No conversion pattern", pattern);
    assertTrue("No filters", pattern.contains("org.junit,org.apache.maven,org.eclipse,sun.reflect,java.lang.reflect"));
}
项目:NoMoreOversleeps    文件:Logging.java   
public static void initialize()
{
    // REDIRECT JAVA UTIL LOGGER TO LOG4J2 (MUST BE BEFORE ALL LOG4J2 CALLS)
    System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");

    // STARTING CONFIGURATION
    final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    org.apache.logging.log4j.core.config.Configuration configuration = loggerContext.getConfiguration();
    LoggerConfig rootLogger = configuration.getLoggerConfig("");
    rootLogger.setLevel(Level.ALL);

    // PATTERNS
    PatternLayout consolePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger{1}]: %msg%n", configuration, null, null, true, false, null, null);
    PatternLayout logfilePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger]: %msg%n", configuration, null, null, true, false, null, null);

    // LOG FILE STRINGS
    String logName = "NoMoreOversleeps";
    String logFilePrefix = PlatformData.installationDirectory.getAbsolutePath().replace("\\", "/") + "/logs/" + WordUtils.capitalizeFully(logName, new char[] { '_', '-', ' ' }).replaceAll("_", "").replaceAll("_", "").replaceAll("-", "").replaceAll(" ", "");

    // CLIENT LOG FILE APPENDER (ROLLING)
    RollingRandomAccessFileAppender clientInfoLogFile = RollingRandomAccessFileAppender.createAppender(logFilePrefix + "-0.log", logFilePrefix + "-%i.log", null, "InfoFile", null, null, OnStartupTriggeringPolicy.createPolicy(), DefaultRolloverStrategy.createStrategy("2", "1", "min", null, configuration), logfilePattern, null, null, null, null, configuration);
    clientInfoLogFile.start();
    configuration.addAppender(clientInfoLogFile);
    rootLogger.addAppender(clientInfoLogFile, Level.INFO, null);

    /*
    // FINER DETAIL LOG FILE (REPLACED ON EACH RUN)
    RandomAccessFileAppender detailLogFile = RandomAccessFileAppender.createAppender(logFilePrefix + "-latest-fine.log", "false", "DetailFile", null, null, null, logfilePattern, null, null, null, configuration);
    detailLogFile.start();
    configuration.addAppender(detailLogFile);
    rootLogger.addAppender(detailLogFile, Level.ALL, null);
    */

    // CONSOLE APPENDER
    ConsoleAppender console = ConsoleAppender.createAppender(consolePattern, null, "SYSTEM_OUT", "Console", null, null); // must be named "Console" to work correctly
    console.start();
    configuration.addAppender(console);
    rootLogger.addAppender(console, Level.INFO, null);

    // UPDATE LOGGERS
    loggerContext.updateLoggers();

    // REDIRECT STDOUT AND STDERR TO LOG4J2
    System.setOut(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.out"), Level.INFO)));
    System.setErr(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.err"), Level.ERROR)));

    // set main engine log
    log = LogManager.getLogger();

    // print opening header
    log.info("===============================================================================================================");
    log.info(" NoMoreOversleeps v" + Main.VERSION);
    log.info(" (c) Robert James Dennington, " + Math.max(Calendar.getInstance().get(Calendar.YEAR), minCopyrightYear));
    log.info("===============================================================================================================");
    log.debug("The system log manager is " + System.getProperty("java.util.logging.manager"));
    log.info("Install path: " + PlatformData.installationDirectory.getAbsolutePath());
    log.info("Computer name: " + PlatformData.computerName);
    log.info("Platform: " + PlatformData.platformName);
}
项目:NapBot    文件:Logging.java   
public static void initialize(Application application)
{
    // STORE APPLICATION FOR LATER USE
    Logging.application = application;

    // REDIRECT JAVA UTIL LOGGER TO LOG4J2 (MUST BE BEFORE ALL LOG4J2 CALLS)
    System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");

    // STARTING CONFIGURATION
    final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    org.apache.logging.log4j.core.config.Configuration configuration = loggerContext.getConfiguration();
    LoggerConfig rootLogger = configuration.getLoggerConfig("");
    rootLogger.setLevel(Level.ALL);

    // PATTERNS
    PatternLayout consolePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger{1}]: %msg%n", null, configuration, null, null, true, false, null, null);
    PatternLayout logfilePattern = PatternLayout.createLayout("%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger]: %msg%n", null, configuration, null, null, true, false, null, null);

    // LOG FILE STRINGS
    String logFilePrefix = PlatformData.installationDirectory.getAbsolutePath().replace("\\", "/") + "/logs/" + WordUtils.capitalizeFully(application.getName(), new char[] { '_', '-', ' ' }).replaceAll("_", "").replaceAll("_", "").replaceAll("-", "").replaceAll(" ", "");

    // CLIENT LOG FILE APPENDER (ROLLING)
    RollingRandomAccessFileAppender clientInfoLogFile = RollingRandomAccessFileAppender.createAppender(logFilePrefix + "-0.log", logFilePrefix + "-%i.log", null, "InfoFile", null, null, OnStartupTriggeringPolicy.createPolicy(), DefaultRolloverStrategy.createStrategy("2", "1", "min", null, null, false, configuration), logfilePattern, null, null, null, null, configuration);
    clientInfoLogFile.start();
    configuration.addAppender(clientInfoLogFile);
    rootLogger.addAppender(clientInfoLogFile, Level.INFO, null);

    // FINER DETAIL LOG FILE (REPLACED ON EACH RUN)
    RandomAccessFileAppender detailLogFile = RandomAccessFileAppender.createAppender(logFilePrefix + "-latest-fine.log", "false", "DetailFile", null, null, null, logfilePattern, null, null, null, configuration);
    detailLogFile.start();
    configuration.addAppender(detailLogFile);
    rootLogger.addAppender(detailLogFile, Level.ALL, null);

    // CONSOLE APPENDER
    ConsoleAppender console = ConsoleAppender.createAppender(consolePattern, null, Target.SYSTEM_OUT, "Console", false, true); // must be named "Console" to work correctly
    console.start();
    configuration.addAppender(console);
    rootLogger.addAppender(console, Level.INFO, null);

    // UPDATE LOGGERS
    loggerContext.updateLoggers();

    // REDIRECT STDOUT AND STDERR TO LOG4J2
    System.setOut(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.out"), Level.INFO)));
    System.setErr(new PrintStream(new StdOutErrOutputStream(LogManager.getLogger("java.lang.System.err"), Level.ERROR)));

    // set main engine log
    log = LogManager.getLogger();

    // print opening header
    log.info("===============================================================================================================");
    log.info(" " + application.getName() + " v" + application.getVersion());
    log.info(" (c) Robert James Dennington, " + Math.max(Calendar.getInstance().get(Calendar.YEAR), minCopyrightYear));
    log.info("===============================================================================================================");
    log.debug("The system log manager is " + System.getProperty("java.util.logging.manager"));
    log.info("Install path: " + PlatformData.installationDirectory.getAbsolutePath());
    log.info("Computer name: " + PlatformData.computerName);
    log.info("Platform: " + PlatformData.platformName);
}
项目:LiquidFortressPacketAnalyzer    文件:LoggerFactory.java   
/**
 * Get the logger used for output
 *
 * @param validatedArgs with output file, silent, and verbose options that
 *                      are used to configure the logger
 * @return Logger with dynamically-generated configuration
 */
public static Logger getLogger(ValidatedArgs validatedArgs) {
    // This approach is ugly, but it circumvents the need for multiple log4j
    // configuration files and simplifies writing results to the console and the output file
    // Silence StatusLogger
    System.setProperty("org.apache.logging.log4j.simplelog.StatusLogger.level", "FATAL");
    // Setup context
    LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    Configuration configuration = loggerContext.getConfiguration();
    // Define layout
    PatternLayout patternLayout = PatternLayout.newBuilder()
            .withConfiguration(configuration)
            // uncomment this pattern for debugging
            //.withPattern("%d{ISO8601} [%level] [%F:%L] %msg%n")
            .build();
    // Add appenders
    AppenderRef[] appenderRefs;
    //// Create console appender unless silent
    ConsoleAppender consoleAppender = null;
    AppenderRef consoleAppenderRef = null;
    if (!validatedArgs.silent) {
        consoleAppender = ConsoleAppender.newBuilder()
                .setConfiguration(configuration)
                .withLayout(patternLayout)
                .withName(CONSOLE_APPENDER)
                .build();
        consoleAppender.start();
        configuration.addAppender(consoleAppender);
        consoleAppenderRef = AppenderRef.createAppenderRef(CONSOLE_APPENDER, null, null);
    }
    //// Create file appender if output file specified
    FileAppender fileAppender = null;
    AppenderRef fileAppenderRef = null;
    if (validatedArgs.outputFile != null) {
        fileAppender = FileAppender.newBuilder()
                .setConfiguration(configuration)
                .withLayout(patternLayout)
                .withName(FILE_APPENDER)
                .withFileName(validatedArgs.outputFile.getAbsolutePath())
                .build();
        fileAppender.start();
        configuration.addAppender(fileAppender);
        fileAppenderRef = AppenderRef.createAppenderRef(FILE_APPENDER, null, null);
    }
    if ((consoleAppenderRef != null) && (fileAppenderRef != null)) {
        appenderRefs = new AppenderRef[]{consoleAppenderRef, fileAppenderRef};
    } else if (consoleAppenderRef != null) {
        appenderRefs = new AppenderRef[]{consoleAppenderRef};
    } else if (fileAppenderRef != null) {
        appenderRefs = new AppenderRef[]{fileAppenderRef};
    } else {
        throw new IllegalStateException("At least one appender must be configured to provide output!");
    }
    // Build and update the LoggerConfig
    Level levelToUse = validatedArgs.verbose ? VERBOSE_LEVEL : DEFAULT_LEVEL;
    LoggerConfig loggerConfig = LoggerConfig.createLogger(false, levelToUse, LOGGER_NAME, "true", appenderRefs, null, configuration, null);
    if (consoleAppender != null) {
        loggerConfig.addAppender(consoleAppender, null, null);
    }
    if (fileAppender != null) {
        loggerConfig.addAppender(fileAppender, null, null);
    }
    configuration.addLogger(LOGGER_NAME, loggerConfig);
    loggerContext.updateLoggers();
    return (Logger) LogManager.getLogger(LOGGER_NAME);
}
项目:zebra    文件:LoggerLoader.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
public static synchronized void init() {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.newBuilder().withPattern("%d{yyyy-MM-dd HH:mm:ss}:%p %t %c - %m%n")
            .withConfiguration(config).withRegexReplacement(null).withCharset(null).withAlwaysWriteExceptions(true)
            .withNoConsoleNoAnsi(false).withHeader(null).withFooter(null).build();

    // file info
    Filter fileInfoFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.ACCEPT);
    Appender fileInfoAppender = RollingFileAppender.createAppender(LOG_ROOT + "/zebra.log",
            LOG_ROOT + "/zebra.log.%d{yyyy-MM-dd}.gz", "true", "FileInfo", "true", "4000", "true",
            TimeBasedTriggeringPolicy.createPolicy("1", "true"),
            ZebraRolloverStrategy.createStrategy("30", "1", null, Deflater.DEFAULT_COMPRESSION + "", config),
            layout, fileInfoFilter, "false", null, null, config);
    config.addAppender(fileInfoAppender);
    fileInfoAppender.start();
    AppenderRef fileInfoRef = AppenderRef.createAppenderRef("FileInfo", null, fileInfoFilter);

    // console error
    Appender consoleErrorAppender = ConsoleAppender.createAppender(layout, null, "SYSTEM_ERR", "ConsoleError",
            "false", "false");
    config.addAppender(consoleErrorAppender);
    consoleErrorAppender.start();

    // console info
    Filter consoleWarnFilter = ThresholdFilter.createFilter(Level.ERROR, Result.DENY, Result.NEUTRAL);
    Appender consoleWarnAppender = ConsoleAppender.createAppender(layout, consoleWarnFilter, "SYSTEM_OUT",
            "ConsoleWarn", "false", "false");
    config.addAppender(consoleWarnAppender);
    consoleWarnAppender.start();
    AppenderRef consoleWarnAppenderRef = AppenderRef.createAppenderRef("ConsoleWarn", Level.WARN,
            consoleWarnFilter);
    AppenderRef consoleErrorAppenderRef = AppenderRef.createAppenderRef("ConsoleError", Level.WARN, null);

    AppenderRef[] refs = new AppenderRef[] { consoleErrorAppenderRef, consoleWarnAppenderRef, fileInfoRef };

    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "com.dianping.zebra", "true", refs,
            null, config, null);
    loggerConfig.addAppender(consoleErrorAppender, Level.ERROR, null);
    loggerConfig.addAppender(consoleWarnAppender, Level.INFO, null);
    loggerConfig.addAppender(fileInfoAppender, Level.INFO, null);

    config.addLogger("com.dianping.zebra", loggerConfig);

    ctx.updateLoggers();

    context = ctx;
}