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

项目:xsharing-services-router    文件:ControlResource.java   
@PUT
@Path("/log/change-level/{loggerName}/{newLevel}")
public Response changeLogLevel(@PathParam("loggerName") String loggerName,
                               @PathParam("newLevel") String newLevel) {

    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    LoggerConfig loggerConfig = config.getLoggerConfig(loggerName);

    if (loggerConfig.getName().equals(LogManager.ROOT_LOGGER_NAME)) {
        return Response.ok("Not found", MediaType.TEXT_PLAIN).build();
    }

    loggerConfig.setLevel(Level.valueOf(newLevel));
    ctx.updateLoggers();  // This causes all Loggers to refetch information from their LoggerConfig.

    return Response.ok("Done", MediaType.TEXT_PLAIN).build();
}
项目:TSBW4J    文件:Bot.java   
private void toggleCleanLogging() {

    this.cleanLogging = !cleanLogging;
    interactionHandler.sendText("clean logging: " + cleanLogging);
    String appenderToAdd = cleanLogging ? "Clean" : "Console";
    String appenderToRemove = cleanLogging ? "Console" : "Clean";

       final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
       final Configuration config = ctx.getConfiguration();

       for (org.apache.logging.log4j.core.Logger logger : ctx.getLoggers()) {

        logger.removeAppender(config.getAppender(appenderToRemove));
        config.addLoggerAppender(logger, config.getAppender(appenderToAdd));
       }
       ctx.updateLoggers();

}
项目:log4j2-jsonevent-layout    文件:JSONLog4j2Layout.java   
/**
 * Creates the layout.
 *
 * @param locationInfo the location info
 * @param singleLine the single line
 * @param htmlSafe the html safe
 * @param plainContextMap the plain context map
 * @param charset the charset
 * @param userFields the user fields
 * @return the JSON log 4 j 2 layout
 */
@PluginFactory
public static JSONLog4j2Layout createLayout(
    // @formatter:off
        @PluginConfiguration final Configuration config,
        @PluginAttribute("locationInfo") boolean locationInfo,
        @PluginAttribute("singleLine") boolean singleLine,
        @PluginAttribute("htmlSafe") boolean htmlSafe,
        @PluginAttribute("plainContextMap") boolean plainContextMap, 
        @PluginAttribute("charset") Charset charset,
        @PluginElement("UserFields") final UserField[] userFields
    // @formatter:on
    ) {

    if(charset == null){
        charset = Charset.forName("UTF-8");
    }

    LOGGER.debug("Creating JSONLog4j2Layout {}",charset);
    return new JSONLog4j2Layout(locationInfo, singleLine, htmlSafe, plainContextMap, userFields, charset);
}
项目: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();
    }
项目:log4j2-extended-jsonlayout    文件:ExtendedJsonLayout.java   
protected ExtendedJsonLayout(final Configuration config, final boolean locationInfo, final boolean properties,
          final boolean encodeThreadContextAsList,
          final boolean complete, final boolean compact, final boolean eventEol, final String headerPattern,
          final String footerPattern, final Charset charset, final boolean includeStacktrace, final String jsonExtenderClass) {
      super(config, getObjectWriter(encodeThreadContextAsList, includeStacktrace, locationInfo, properties, compact),
              charset, compact, complete, eventEol,
              PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(headerPattern).setDefaultPattern(DEFAULT_HEADER).build(),
              PatternLayout.newSerializerBuilder().setConfiguration(config).setPattern(footerPattern).setDefaultPattern(DEFAULT_FOOTER).build());

      Class<?> clazz;
      Object jsonAdapterobject = null;
try {
    clazz = Class.forName(jsonExtenderClass);
       Constructor<?> ctor = clazz.getConstructor();
       jsonAdapterobject = ctor.newInstance(new Object[] {});
} catch (Exception e) {
    e.printStackTrace();
}

      this.jsonAdapter = (ExtendedJson) jsonAdapterobject;
  }
项目:monarch    文件:Configurator.java   
public static LoggerConfig getOrCreateLoggerConfig(String name) {
  LoggerContext context = (LoggerContext) LogManager.getContext(false);
  Configuration config = context.getConfiguration();
  LoggerConfig logConfig = config.getLoggerConfig(name);
  boolean update = false;
  if (!logConfig.getName().equals(name)) {
    List<AppenderRef> appenderRefs = logConfig.getAppenderRefs();
    Map<Property, Boolean> properties = logConfig.getProperties();
    Set<Property> props = properties == null ? null : properties.keySet();
    logConfig = LoggerConfig.createLogger(String.valueOf(logConfig.isAdditive()),
        logConfig.getLevel(), name, String.valueOf(logConfig.isIncludeLocation()),
        appenderRefs == null ? null : appenderRefs.toArray(new AppenderRef[appenderRefs.size()]),
        props == null ? null : props.toArray(new Property[props.size()]), config, null);
    config.addLogger(name, logConfig);
    update = true;
  }
  if (update) {
    context.updateLoggers();
  }
  return logConfig;
}
项目:monarch    文件:Configurator.java   
public static LoggerConfig getOrCreateLoggerConfig(String name, boolean additive,
    boolean forceAdditivity) {
  LoggerContext context = (LoggerContext) LogManager.getContext(false);
  Configuration config = context.getConfiguration();
  LoggerConfig logConfig = config.getLoggerConfig(name);
  boolean update = false;
  if (!logConfig.getName().equals(name)) {
    List<AppenderRef> appenderRefs = logConfig.getAppenderRefs();
    Map<Property, Boolean> properties = logConfig.getProperties();
    Set<Property> props = properties == null ? null : properties.keySet();
    logConfig = LoggerConfig.createLogger(String.valueOf(additive), logConfig.getLevel(), name,
        String.valueOf(logConfig.isIncludeLocation()),
        appenderRefs == null ? null : appenderRefs.toArray(new AppenderRef[appenderRefs.size()]),
        props == null ? null : props.toArray(new Property[props.size()]), config, null);
    config.addLogger(name, logConfig);
    update = true;
  }
  if (forceAdditivity && logConfig.isAdditive() != additive) {
    logConfig.setAdditive(additive);
    update = true;
  }
  if (update) {
    context.updateLoggers();
  }
  return logConfig;
}
项目:monarch    文件:Configurator.java   
public static boolean hasLoggerFilter(final Configuration config) {
  for (LoggerConfig loggerConfig : config.getLoggers().values()) {
    boolean isRoot = loggerConfig.getName().equals("");
    boolean isGemFire = loggerConfig.getName().startsWith(LogService.BASE_LOGGER_NAME);
    boolean hasFilter = loggerConfig.hasFilter();
    boolean isGemFireVerboseFilter =
        hasFilter && (LogService.GEODE_VERBOSE_FILTER.equals(loggerConfig.getFilter().toString())
            || LogService.GEMFIRE_VERBOSE_FILTER.equals(loggerConfig.getFilter().toString()));

    if (isRoot || isGemFire) {
      // check for Logger Filter
      if (hasFilter && !isGemFireVerboseFilter) {
        return true;
      }
    }
  }
  return false;
}
项目:monarch    文件:Configurator.java   
public static boolean hasAppenderRefFilter(final Configuration config) {
  for (LoggerConfig loggerConfig : config.getLoggers().values()) {
    boolean isRoot = loggerConfig.getName().equals("");
    boolean isGemFire = loggerConfig.getName().startsWith(LogService.BASE_LOGGER_NAME);

    if (isRoot || isGemFire) {
      // check for AppenderRef Filter
      for (AppenderRef appenderRef : loggerConfig.getAppenderRefs()) {
        if (appenderRef.getFilter() != null) {
          return true;
        }
      }
    }
  }
  return false;
}
项目:QuantTester    文件:OptimizeMaPsar.java   
public static void main(String[] args) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN);
    ctx.updateLoggers(config);

    final CommonParam cp = ParamManager.getCommonParam("i", TIME_FRAME.MIN15, "20080101 000000", "20160101 170000");

    StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class);
    so.setInstrumentParam(cp.instrument, cp.tf);
    so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date));
    int num = so.setStrategyParamRange(MaPsarStrategy.class, new Integer[]{12, 500, 2}, new String[]{MA.MODE_EMA, MA.MODE_SMMA}, new APPLIED_PRICE[] {APPLIED_PRICE.PRICE_CLOSE, APPLIED_PRICE.PRICE_TYPICAL}, new Float[]{0.01f, 0.02f, 0.01f}, new Float[]{0.1f, 0.2f, 0.02f});
    System.out.println(num);
    so.StartOptimization();
    Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet();
    for (Entry<Object[],Performances> entry : entryset) {
        for (Object obj : entry.getKey()) {
            System.out.print(obj + ",\t");
        }
        System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown);
    }
}
项目:QuantTester    文件:OptimizeChannelBreak.java   
public static void main(String[] args) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN);
    ctx.updateLoggers(config);

    final CommonParam cp = ParamManager.getCommonParam("cu", TIME_FRAME.DAY, "19980101 000000", "20160916 170000");

    StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class);
    so.setInstrumentParam(cp.instrument, cp.tf);
    so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date));
    int num = so.setStrategyParamRange(ChannelBreakStrategy.class, new Integer[]{4, 800, 2});
    System.out.println(num);
    so.StartOptimization();
    Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet();
    for (Entry<Object[],Performances> entry : entryset) {
        for (Object obj : entry.getKey()) {
            System.out.print(obj + ",\t");
        }
        System.out.println("ProfitRatio: " + entry.getValue().ProfitRatio + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown);
    }
}
项目:QuantTester    文件:OptimizeDblMaPsar.java   
public static void main(String[] args) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN);
    ctx.updateLoggers(config);

    final CommonParam cp = ParamManager.getCommonParam("m", TIME_FRAME.MIN60, "19980101 000000", "20160101 170000");

    StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class);
    so.setInstrumentParam(cp.instrument, cp.tf);
    so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date));
    int num = so.setStrategyParamRange(DblMaPsarStrategy.class, new Integer[]{3, 5, 1}, new Integer[]{10, 100, 2}, MA.MA_MODES, new APPLIED_PRICE[] {APPLIED_PRICE.PRICE_CLOSE, APPLIED_PRICE.PRICE_TYPICAL}, new Float[]{0.01f, 0.02f, 0.01f}, new Float[]{0.12f, 0.2f, 0.02f});
    System.out.println(num);
    so.StartOptimization();
    Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet();
    for (Entry<Object[],Performances> entry : entryset) {
        for (Object obj : entry.getKey()) {
            System.out.print(obj + ",\t");
        }
        System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown);
    }
}
项目:QuantTester    文件:OptimizeMABreak.java   
public static void main(String[] args) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN);
    ctx.updateLoggers(config);

    final CommonParam cp = ParamManager.getCommonParam("cu", TIME_FRAME.MIN15, "20080101 000000", "20160101 170000");

    StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class);
    so.setInstrumentParam(cp.instrument, cp.tf);
    so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date));
    int num = so.setStrategyParamRange(MABreakStrategy.class, new Integer[]{8, 800, 2}, MA.MA_MODES);
    System.out.println(num);
    so.StartOptimization();
    Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet();
    for (Entry<Object[],Performances> entry : entryset) {
        for (Object obj : entry.getKey()) {
            System.out.print(obj + ",\t");
        }
        System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown);
    }
}
项目:log4j2-logstash-layout    文件:LogstashLayoutTest.java   
private void checkLogEvent(Configuration config, LogEvent logEvent, String lookupTestKey, String lookupTestVal) throws IOException {
    Set<String> mdcKeys = logEvent.getContextData().toMap().keySet();
    String firstMdcKey = mdcKeys.iterator().next();
    String firstMdcKeyExcludingRegex = mdcKeys.isEmpty() ? null : String.format("^(?!%s).*$", Pattern.quote(firstMdcKey));
    List<String> ndcItems = logEvent.getContextStack().asList();
    String firstNdcItem = ndcItems.get(0);
    String firstNdcItemExcludingRegex = ndcItems.isEmpty() ? null : String.format("^(?!%s).*$", Pattern.quote(firstNdcItem));
    LogstashLayout layout = LogstashLayout
            .newBuilder()
            .setConfiguration(config)
            .setTemplateUri("classpath:LogstashTestLayout.json")
            .setStackTraceEnabled(true)
            .setLocationInfoEnabled(true)
            .setMdcKeyPattern(firstMdcKeyExcludingRegex)
            .setNdcPattern(firstNdcItemExcludingRegex)
            .build();
    String serializedLogEvent = layout.toSerializable(logEvent);
    JsonNode rootNode = OBJECT_MAPPER.readTree(serializedLogEvent);
    checkConstants(rootNode);
    checkBasicFields(logEvent, rootNode);
    checkSource(logEvent, rootNode);
    checkException(logEvent, rootNode);
    checkContextData(logEvent, firstMdcKeyExcludingRegex, rootNode);
    checkContextStack(logEvent, firstNdcItemExcludingRegex, rootNode);
    checkLookupTest(lookupTestKey, lookupTestVal, rootNode);
}
项目:log4j2-elasticsearch    文件:AppenderRefFailoverPolicyTest.java   
@Test
public void deliversToAppenderRef() {

    // given
    Appender appender = mock(Appender.class);
    when(appender.isStarted()).thenReturn(true);
    Configuration configuration = mock(Configuration.class);
    String testAppenderRef = "testAppenderRef";
    when(configuration.getAppender(testAppenderRef)).thenReturn(appender);

    FailoverPolicy<String> failoverPolicy = createTestFailoverPolicy(testAppenderRef, configuration);

    String failedMessage = "test failed message";

    // when
    failoverPolicy.deliver(failedMessage);

    // then
    verify(appender, times(1)).append(any(LogEvent.class));
}
项目:log4j2-elasticsearch    文件:AppenderRefFailoverPolicyTest.java   
@Test
public void resolvesAppenderRefOnlyOnce() {

    // given
    Appender appender = mock(Appender.class);
    when(appender.isStarted()).thenReturn(true);
    Configuration configuration = mock(Configuration.class);
    String testAppenderRef = "testAppenderRef";
    when(configuration.getAppender(testAppenderRef)).thenReturn(appender);

    FailoverPolicy<String> failoverPolicy = createTestFailoverPolicy(testAppenderRef, configuration);

    String failedMessage = "test failed message";

    // when
    failoverPolicy.deliver(failedMessage);
    failoverPolicy.deliver(failedMessage);

    // then
    verify(configuration, times(1)).getAppender(anyString());
    verify(appender, times(2)).append(any(LogEvent.class));
}
项目:log4j2-elasticsearch    文件:AppenderRefFailoverPolicyTest.java   
@Test(expected = ConfigurationException.class)
public void throwsExceptionOnUnresolvedAppender() {

    // given
    Appender appender = mock(Appender.class);
    when(appender.isStarted()).thenReturn(true);
    Configuration configuration = mock(Configuration.class);
    String testAppenderRef = "testAppenderRef";
    when(configuration.getAppender(testAppenderRef)).thenReturn(null);

    FailoverPolicy<String> failoverPolicy = createTestFailoverPolicy(testAppenderRef, configuration);

    String failedMessage = "test failed message";

    // when
    failoverPolicy.deliver(failedMessage);

}
项目:hiervis    文件:HierarchyVisualizer.java   
/**
 * Setup the file logger so that it outputs messages to the appropriately named file,
 * depending on the subtitle of the current program instance.
 */
private static void configureLoggers( String subtitle )
{
    // Remove all characters that are not allowed for Windows filenames.
    subtitle = subtitle.replaceAll( "[\\s" + Pattern.quote( "\\/:*?\"<>|" ) + "]", "" );

    LoggerContext context = (LoggerContext)LogManager.getContext();
    Configuration config = context.getConfiguration();

    PatternLayout layout = PatternLayout.createLayout(
        "%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%throwable%n",
        null, null, null, Charset.defaultCharset(), false, false, null, null
    );

    FileAppender appender = FileAppender.createAppender(
        "logs/log-" + subtitle + ".txt", "false", "false", "LogFile-" + subtitle, "true", "true", "true",
        "8192", layout, null, "false", "", config
    );

    org.apache.logging.log4j.core.Logger rootLogger = (org.apache.logging.log4j.core.Logger)LogManager.getRootLogger();
    rootLogger.addAppender( appender );
    appender.start();
}
项目:TLS-Attacker    文件:GeneralDelegate.java   
@Override
public void applyDelegate(Config config) {
    Security.addProvider(new BouncyCastleProvider());
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration ctxConfig = ctx.getConfiguration();
    LoggerConfig loggerConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    if (isDebug()) {
        loggerConfig.setLevel(Level.DEBUG);
    } else if (isQuiet()) {
        loggerConfig.setLevel(Level.OFF);
    } else if (getLogLevel() != null) {
        loggerConfig.setLevel(getLogLevel());
    }
    ctx.updateLoggers();
    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();
}
项目:meghanada-server    文件:Main.java   
private static void addFileAppender() throws IOException {
  final String tempDir = System.getProperty("java.io.tmpdir");
  final File logFile = new File(tempDir, "meghanada_server.log");
  final LoggerContext context = (LoggerContext) LogManager.getContext(false);
  final Configuration configuration = context.getConfiguration();
  final LoggerConfig loggerConfig = configuration.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
  final FileAppender fileAppender =
      FileAppender.newBuilder()
          .withName("file")
          .withLayout(
              PatternLayout.newBuilder()
                  .withPattern("[%d][%-5.-5p][%-14.-14c{1}:%4L] %-22.-22M - %m%n")
                  .build())
          .withFileName(logFile.getCanonicalPath())
          .build();
  configuration.addAppender(fileAppender);
  loggerConfig.addAppender(fileAppender, Level.ERROR, null);
  context.updateLoggers();
}
项目:microservice-mock    文件:LogManagerTest.java   
/**
 * This test asserts that after re-configuration of the log engine the total appenders are
 * different. The 'comparison' will be done between:
 *
 * - default config (src/main/resources/log4j2.xml)
 * - alternative config (src/test/resources/xml/config-for-LogManagerTest.xml)
 */
@Test (groups = { GROUP_CHANGE_CONFIG }, description = "Validate the numbers of Appenders associated with the LoggerContext")
public void testLogReconfiguration() {
    LOGGER.debug("About to test re-configuration of the logger context");
    final String pathToAlternativeLogConfig = "src/test/resources/config/log/config-for-LogManagerTest.xml";
    LoggerContext loggerContext = LoggerContext.getContext(false);
    Configuration configuration = loggerContext.getConfiguration();
    Map<String, Appender> appenderMap = configuration.getAppenders();
    Assert.assertTrue(appenderMap.size() == 1, "Expected 1 appender");
    Assert.assertTrue(appenderMap.containsKey("console"));

    LogManager.initializeLogging(pathToAlternativeLogConfig);
    // Refresh reference of configuration as it changed
    configuration = loggerContext.getConfiguration();
    appenderMap = configuration.getAppenders();
    Assert.assertTrue(appenderMap.size() == 2, "Expected 2 appenders");
    Assert.assertTrue(appenderMap.containsKey("console"));
    Assert.assertTrue(appenderMap.containsKey("filterAppender"));
}
项目:ColorConsole    文件:CommonLogInstaller.java   
public static PatternLayout createLayout(String logFormat) throws ReflectiveOperationException {
    try {
        Method builder = PatternLayout.class
                .getDeclaredMethod("createLayout", String.class, Configuration.class, RegexReplacement.class
                        , String.class, String.class);

        return (PatternLayout) builder.invoke(null, logFormat, new DefaultConfiguration(), null
                , Charset.defaultCharset().name(), "true");
    } catch (NoSuchMethodException methodEx) {
        return PatternLayout.newBuilder()
                .withCharset(Charset.defaultCharset())
                .withPattern(logFormat)
                .withConfiguration(new DefaultConfiguration())
                .withAlwaysWriteExceptions(true)
                .build();
    }
}
项目:FoDBugTrackerUtility    文件:RunProcessRunnerFromCLI.java   
/**
 * Update the log configuration based on command line options
 * 
 * @param cl
 */
protected final void updateLogConfig(CommandLine cl) {
    String logFile = cl.getOptionValue(OPT_LOG_FILE.getLongOpt(), null);
    String logLevel = cl.getOptionValue(OPT_LOG_LEVEL.getLongOpt(), null);
    if (logFile != null || logLevel != null) {
        logFile = logFile != null ? logFile : getDefaultLogFileName();
        logLevel = logLevel != null ? logLevel : DEFAULT_LOG_LEVEL;
        LoggerContext context = (LoggerContext) LogManager.getContext(false);
        Configuration configuration = context.getConfiguration();
        FileAppender appender = FileAppender.newBuilder()
                .withName("File")
                .withFileName(logFile)
                .withLayout(PatternLayout.newBuilder().withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN).build())
                .withAppend(false)
                .build();
        appender.start();
        configuration.getRootLogger().addAppender(appender, Level.getLevel(logLevel), null);
        configuration.getRootLogger().setLevel(Level.getLevel(logLevel));
        context.updateLoggers();
    }
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:ColorConverter.java   
/**
 * Creates a new instance of the class. Required by Log4J2.
 *
 * @param config the configuration
 * @param options the options
 * @return a new instance, or {@code null} if the options are invalid
 */
public static ColorConverter newInstance(Configuration config, String[] options) {
    if (options.length < 1) {
        LOGGER.error("Incorrect number of options on style. "
                + "Expected at least 1, received {}", options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on style");
        return null;
    }
    PatternParser parser = PatternLayout.createPatternParser(config);
    List<PatternFormatter> formatters = parser.parse(options[0]);
    AnsiElement element = (options.length == 1 ? null : ELEMENTS.get(options[1]));
    return new ColorConverter(formatters, element);
}
项目:camel-standalone    文件:Standalone.java   
protected void configureLogging() {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    Layout layout = PatternLayout.createLayout(PatternLayout.SIMPLE_CONVERSION_PATTERN, null, config, null, null,
            true, false, null, null);
    Appender appender = FileAppender.createAppender(workDir + "/logs/camel-standalone.log", "false", "false", "File", "true",
            "false", "false", "4000", layout, null, "false", null, config);
    appender.start();
    config.addAppender(appender);
    AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
    AppenderRef[] refs = new AppenderRef[] {ref};
    LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.INFO, "StandaloneFileLoggerConfig",
            "true", refs, null, config, null );
    loggerConfig.addAppender(appender, null, null);
    config.addLogger("StandaloneFileLoggerConfig", loggerConfig);
    ctx.updateLoggers();
}
项目:QuantTester    文件:OptimizeMaPsar.java   
public static void main(String[] args) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN);
    ctx.updateLoggers(config);

    final CommonParam cp = ParamManager.getCommonParam("i", TIME_FRAME.MIN15, "20080101 000000", "20160101 170000");

    StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class);
    so.setInstrumentParam(cp.instrument, cp.tf);
    so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date));
    int num = so.setStrategyParamRange(MaPsarStrategy.class, new Integer[]{12, 500, 2}, new String[]{MA.MODE_EMA, MA.MODE_SMMA}, new APPLIED_PRICE[] {APPLIED_PRICE.PRICE_CLOSE, APPLIED_PRICE.PRICE_TYPICAL}, new Float[]{0.01f, 0.02f, 0.01f}, new Float[]{0.1f, 0.2f, 0.02f});
    System.out.println(num);
    so.StartOptimization();
    Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet();
    for (Entry<Object[],Performances> entry : entryset) {
        for (Object obj : entry.getKey()) {
            System.out.print(obj + ",\t");
        }
        System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown);
    }
}
项目:QuantTester    文件:OptimizeChannelBreak.java   
public static void main(String[] args) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN);
    ctx.updateLoggers(config);

    final CommonParam cp = ParamManager.getCommonParam("cu", TIME_FRAME.DAY, "19980101 000000", "20160916 170000");

    StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class);
    so.setInstrumentParam(cp.instrument, cp.tf);
    so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date));
    int num = so.setStrategyParamRange(ChannelBreakStrategy.class, new Integer[]{4, 800, 2});
    System.out.println(num);
    so.StartOptimization();
    Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet();
    for (Entry<Object[],Performances> entry : entryset) {
        for (Object obj : entry.getKey()) {
            System.out.print(obj + ",\t");
        }
        System.out.println("ProfitRatio: " + entry.getValue().ProfitRatio + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown);
    }
}
项目:QuantTester    文件:OptimizeDblMaPsar.java   
public static void main(String[] args) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN);
    ctx.updateLoggers(config);

    final CommonParam cp = ParamManager.getCommonParam("m", TIME_FRAME.MIN60, "19980101 000000", "20160101 170000");

    StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class);
    so.setInstrumentParam(cp.instrument, cp.tf);
    so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date));
    int num = so.setStrategyParamRange(DblMaPsarStrategy.class, new Integer[]{3, 5, 1}, new Integer[]{10, 100, 2}, MA.MA_MODES, new APPLIED_PRICE[] {APPLIED_PRICE.PRICE_CLOSE, APPLIED_PRICE.PRICE_TYPICAL}, new Float[]{0.01f, 0.02f, 0.01f}, new Float[]{0.12f, 0.2f, 0.02f});
    System.out.println(num);
    so.StartOptimization();
    Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet();
    for (Entry<Object[],Performances> entry : entryset) {
        for (Object obj : entry.getKey()) {
            System.out.print(obj + ",\t");
        }
        System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown);
    }
}
项目:QuantTester    文件:OptimizeMABreak.java   
public static void main(String[] args) {
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    config.getLoggerConfig(strategy.Portfolio.class.getName()).setLevel(Level.WARN);
    ctx.updateLoggers(config);

    final CommonParam cp = ParamManager.getCommonParam("cu", TIME_FRAME.MIN15, "20080101 000000", "20160101 170000");

    StrategyOptimizer so = new StrategyOptimizer(tester.RealStrategyTester.class);
    so.setInstrumentParam(cp.instrument, cp.tf);
    so.setTestDateRange((int) DateTimeHelper.Ldt2Long(cp.start_date), (int) DateTimeHelper.Ldt2Long(cp.end_date));
    int num = so.setStrategyParamRange(MABreakStrategy.class, new Integer[]{8, 800, 2}, MA.MA_MODES);
    System.out.println(num);
    so.StartOptimization();
    Set<Entry<Object[],Performances>> entryset = so.result_db.entrySet();
    for (Entry<Object[],Performances> entry : entryset) {
        for (Object obj : entry.getKey()) {
            System.out.print(obj + ",\t");
        }
        System.out.println("ProfitRatio: " + String.format("%.5f", entry.getValue().ProfitRatio) + "\tMaxDrawDown: " + entry.getValue().MaxDrawDown);
    }
}
项目:log4j2-simplejson    文件:SimpleJSONLayout.java   
protected SimpleJSONLayout(final Configuration config, final boolean locationInfo,
        final boolean properties, final boolean complete, final boolean eventEol,
        final String headerPattern, final String footerPattern, final Charset charset,
        final KeyValuePair[] additionalFields) {
    super(config, charset, //
            PatternLayout.newSerializerBuilder() //
                    .setConfiguration(config).setReplace(null).setPattern(headerPattern) //
                    .setDefaultPattern(DEFAULT_HEADER) //
                    .setPatternSelector(null).setAlwaysWriteExceptions(false).setNoConsoleNoAnsi(false) //
                    .build(), //
            PatternLayout.newSerializerBuilder() //
                    .setConfiguration(config).setReplace(null).setPattern(footerPattern) //
                    .setDefaultPattern(DEFAULT_FOOTER) //
                    .setPatternSelector(null).setAlwaysWriteExceptions(false).setNoConsoleNoAnsi(false) //
                    .build());
    this.locationInfo = locationInfo;
    this.properties = properties;
    this.complete = complete;
    this.additionalFields = additionalFields;
    this.layoutStartTime = System.currentTimeMillis();
    this.layoutSequence = new AtomicLong();
    this.interpolator = new Interpolator(new MapLookup(getConfiguration().getProperties()),
            getConfiguration().getPluginPackages());
    this.eol = !eventEol ? COMPACT_EOL : DEFAULT_EOL;
}
项目:spring-boot-concourse    文件:ColorConverter.java   
/**
 * Creates a new instance of the class. Required by Log4J2.
 *
 * @param config the configuration
 * @param options the options
 * @return a new instance, or {@code null} if the options are invalid
 */
public static ColorConverter newInstance(Configuration config, String[] options) {
    if (options.length < 1) {
        LOGGER.error("Incorrect number of options on style. "
                + "Expected at least 1, received {}", options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on style");
        return null;
    }
    PatternParser parser = PatternLayout.createPatternParser(config);
    List<PatternFormatter> formatters = parser.parse(options[0]);
    AnsiElement element = (options.length == 1 ? null : ELEMENTS.get(options[1]));
    return new ColorConverter(formatters, element);
}
项目: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();
}
项目:contestparser    文件:ColorConverter.java   
/**
 * Creates a new instance of the class. Required by Log4J2.
 *
 * @param config the configuration
 * @param options the options
 * @return a new instance, or {@code null} if the options are invalid
 */
public static ColorConverter newInstance(Configuration config, String[] options) {
    if (options.length < 1) {
        LOGGER.error("Incorrect number of options on style. "
                + "Expected at least 1, received {}", options.length);
        return null;
    }
    if (options[0] == null) {
        LOGGER.error("No pattern supplied on style");
        return null;
    }
    PatternParser parser = PatternLayout.createPatternParser(config);
    List<PatternFormatter> formatters = parser.parse(options[0]);
    AnsiElement element = (options.length == 1 ? null : ELEMENTS.get(options[1]));
    return new ColorConverter(formatters, element);
}
项目:herd    文件:Log4j2LoggingHelper.java   
@Override
public StringWriter addLoggingWriterAppender(String appenderName)
{
    // Get the configuration
    final LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    final Configuration configuration = loggerContext.getConfiguration();

    // Create a string writer as part of the appender so logging will be written to it.
    StringWriter stringWriter = new StringWriter();

    // Create and start the appender with the string writer.
    Appender appender = WriterAppender.createAppender(null, null, stringWriter, appenderName, false, true);
    appender.start();

    // Add the appender to the root logger.
    configuration.getRootLogger().addAppender(appender, null, null);

    // Return the string writer.
    return stringWriter;
}
项目: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");
}
项目:ballin-happiness    文件:DecoupledInputStreamTestCase.java   
/**
 * Tests that {@link oc.io.base.DecoupledInputStream#read()} terminates
 * normally when IOException is thrown in wrapped InputStream
 * 
 * @throws IOException
 */
@Test
public void testReadException() throws IOException {
    final byte b[] = new byte[1];

    // Temporary disable logging for avoiding annoying Exception trace
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    final LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    final Level currentLevel = loggerConfig.getLevel();
    loggerConfig.setLevel(Level.FATAL);
    ctx.updateLoggers();

    final TestInputStream testInputStream = new TestInputStream(new IOException(
            "This exception is thrown due to a test scenario. This is expected behaviour"));
    final DecoupledInputStream decInputStream = new DecoupledInputStream(testInputStream);
    assertEquals(-1, decInputStream.read(b));
    decInputStream.close();

    loggerConfig.setLevel(currentLevel);
    ctx.updateLoggers();
}
项目:core-ng-project    文件:ESLoggerConfigFactory.java   
public static void bindLogger() {
    LoggerContext context = (LoggerContext) LogManager.getContext(false);
    Configuration config = context.getConfiguration();

    Map<String, ESLogger> loggers = Maps.newConcurrentHashMap();
    Appender appender = new AbstractAppender("", null, null) {
        @Override
        public void append(LogEvent event) {
            String name = event.getLoggerName();
            ESLogger logger = loggers.computeIfAbsent(name, key -> new ESLogger(key, null, (LoggerImpl) LoggerFactory.getLogger(key)));
            logger.log(event.getLevel(), event.getMarker(), event.getMessage(), event.getThrown());
        }
    };
    appender.start();
    config.addAppender(appender);

    LoggerConfig loggerConfig = new LoggerConfig("", Level.ALL, false);
    loggerConfig.addAppender(appender, null, null);
    config.addLogger("", loggerConfig);
    context.updateLoggers();
}
项目:Log4j-StaticShutdown    文件:Log4jShutdownTest.java   
@Before
public void setUpAppender() throws IOException {
    file = folder.newFile();

    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = ctx.getConfiguration();
    final LoggerConfig root = ((AbstractConfiguration) config).getRootLogger();

    PatternLayout layout = PatternLayout.createLayout("[%p] %m%n", config, null, null, true, false, null, null);
    FileAppender appender = FileAppender.createAppender(file.getAbsolutePath(), "true", "false", "TestLogFile", "true", "false", "false", "8192", layout, null, "false", null, config);

    appender.start();
    config.addAppender(appender);

    root.addAppender(appender, null, null);
    ctx.updateLoggers();
}
项目:wsman    文件:WSManCli.java   
private void setupLogging() {
    Level level = Level.getLevel(logLevel.name());
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    // Setup the root logger to the requested log level
    LoggerConfig loggerConfig = config.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
    loggerConfig.setLevel(level);
    // Dump the requests/responses when requested
    if (logRequests) {
        loggerConfig = config.getLoggerConfig("org.apache.cxf.services");
        if (level.isLessSpecificThan(Level.INFO)) {
            loggerConfig.setLevel(level);
        } else {
            loggerConfig.setLevel(Level.INFO);
        }
    }
    ctx.updateLoggers();
}