protected void initServerSocket() {
    try {
      // this.addConnectionObserver(connObserver);
      // create a listening socket and add it to the select set
      ssocket = ServerSocketChannel.open();
      ssocket.configureBlocking(false);

      InetSocketAddress isa = null;
      if (ipAddress != null) {
        isa = new InetSocketAddress(ipAddress, port);
      } else {
        isa = new InetSocketAddress(port);
      }

      ssocket.socket().bind(isa, this.backlog);
      registerServerChannel(ssocket);

      Level level = log.getLevel();
      log.setLevel(Level.INFO);
      log.info(this.getName() + " listening on " + isa + ".");
      log.setLevel(level);

    } catch (IOException ioe) {
      log.error("Failure listening to socket on port '" + port + "'.", ioe);
      System.err.println("Failure listening to socket on port '" + port + "'.");
      ioe.printStackTrace();
      System.exit(-1);
    }
  }
Example #2
0
  public static void main(String[] args) throws Exception {

    Randomizer.init(14L); // initialize common random seed.

    // turn off debug logs
    Logger orstlog = Logger.getLogger("orst");
    Logger msglog = Logger.getLogger("msglog");
    orstlog.setLevel(Level.OFF);
    msglog.setLevel(Level.OFF);

    // where to write results?
    if (args.length >= 1) {
      dir = args[0];
    }
    System.out.println("Writing result YAML files to '" + dir + "'.");

    String[] gameFiles = {
      "2bases-game.txt", // in stratsim module.
      "the-right-strategy-game.txt", // in stratplan module.
    };
    String[] strategy_sets = {"2012-02-05" /* "atk-dfnd", "synth" */};

    for (String name : strategy_sets) {
      sim_matrix(gameFiles, name);
      System.out.println(name + " strategy set done.");
    }
    System.out.println("Done!");
  }
Example #3
0
 /**
  * Set log level
  *
  * @param cls if null, then rootLogger
  * @param level one of ['TRACE','DEBUG','INFO','WARN','ERROR']
  */
 public static void setLogLevel(String cls, String level) {
   Logger l = null;
   if (Objects.isNullOrEmpty(cls)) l = LogManager.getRootLogger();
   else l = LogManager.getLogger(cls);
   if (level.equalsIgnoreCase("TRACE")) l.setLevel(Level.TRACE);
   else if (level.equalsIgnoreCase("DEBUG")) l.setLevel(Level.DEBUG);
   else if (level.equalsIgnoreCase("INFO")) l.setLevel(Level.INFO);
   else if (level.equalsIgnoreCase("WARN")) l.setLevel(Level.WARN);
   else if (level.equalsIgnoreCase("ERROR")) l.setLevel(Level.ERROR);
 }
Example #4
0
 public ResponseParser() {
   // Setup Logging for ResponseParser
   if (Main.LOGLEVEL.equals("INFO")) {
     logger.setLevel(Level.INFO);
   } else if (Main.LOGLEVEL.equals("ERROR")) {
     logger.setLevel(Level.ERROR);
   } else {
     logger.setLevel(Level.OFF);
   }
 }
 public void shutdown() {
   Level level = log.getLevel();
   log.setLevel(Level.INFO);
   super.shutdown();
   try {
     ssocket.close();
   } catch (IOException e) {
   }
   log.warn(this.getName() + " shutdown completed!");
   log.setLevel(level);
 }
Example #6
0
 /* (non-Javadoc)
  * @see nl.justobjects.pushlet.util.PushletLogger#setLevel(int)
  */
 public void setLevel(int aLevel) {
   if (aLevel < LOG_LEVEL_FATAL) {
     logger.setLevel(Level.OFF);
   } else {
     switch (aLevel) {
       case LOG_LEVEL_FATAL:
         logger.setLevel(Level.FATAL);
         break;
       case LOG_LEVEL_ERROR:
         logger.setLevel(Level.ERROR);
         break;
       case LOG_LEVEL_WARN:
         logger.setLevel(Level.WARN);
         break;
       case LOG_LEVEL_INFO:
         logger.setLevel(Level.INFO);
         break;
       case LOG_LEVEL_DEBUG:
         logger.setLevel(Level.DEBUG);
         break;
       case LOG_LEVEL_TRACE:
         logger.setLevel(Level.TRACE);
         break;
       default:
         logger.setLevel(Level.INFO);
     }
   }
 }
  /** This method must work for the root category as well. */
  void parseCategory(
      Properties props, Logger logger, String optionKey, String loggerName, String value) {

    LogLog.debug("Parsing for [" + loggerName + "] with value=[" + value + "].");
    // We must skip over ',' but not white space
    StringTokenizer st = new StringTokenizer(value, ",");

    // If value is not in the form ", appender.." or "", then we should set
    // the level of the loggeregory.

    if (!(value.startsWith(",") || value.equals(""))) {

      // just to be on the safe side...
      if (!st.hasMoreTokens()) return;

      String levelStr = st.nextToken();
      LogLog.debug("Level token is [" + levelStr + "].");

      // If the level value is inherited, set category level value to
      // null. We also check that the user has not specified inherited for the
      // root category.
      if (INHERITED.equalsIgnoreCase(levelStr) || NULL.equalsIgnoreCase(levelStr)) {
        if (loggerName.equals(INTERNAL_ROOT_NAME)) {
          LogLog.warn("The root logger cannot be set to null.");
        } else {
          logger.setLevel(null);
        }
      } else {
        logger.setLevel(OptionConverter.toLevel(levelStr, (Level) Level.DEBUG));
      }
      LogLog.debug("Category " + loggerName + " set to " + logger.getLevel());
    }

    // Begin by removing all existing appenders.
    logger.removeAllAppenders();

    Appender appender;
    String appenderName;
    while (st.hasMoreTokens()) {
      appenderName = st.nextToken().trim();
      if (appenderName == null || appenderName.equals(",")) continue;
      LogLog.debug("Parsing appender named \"" + appenderName + "\".");
      appender = parseAppender(props, appenderName);
      if (appender != null) {
        logger.addAppender(appender);
      }
    }
  }
Example #8
0
  /** Test retrieving log events */
  public void testLogging() throws Exception {
    LoggingBean bean = new LoggingBean();

    ((ServerModelImpl) sm).setLogFormat("%m");

    ServerContext serverContext = new ServerContextImpl(bean, sm, new OurHierarchicalRegistry());

    OddjobMBean ojmb =
        new OddjobMBean(
            bean, OddjobMBeanFactory.objectName(0), new OurServerSession(), serverContext);

    Logger testLogger = Logger.getLogger(bean.loggerName());
    testLogger.setLevel(Level.DEBUG);
    testLogger.info("Test");

    LogEvent[] events =
        (LogEvent[])
            ojmb.invoke(
                SharedConstants.RETRIEVE_LOG_EVENTS_METHOD,
                new Object[] {new Long(-1), new Integer(10)},
                new String[] {Long.TYPE.getName(), Integer.TYPE.getName()});

    assertEquals("num events", 1, events.length);
    assertEquals("event 0", "Test", events[0].getMessage());
  }
  @Test
  public void appenderStoresMessages() {
    MemoryAppender appender = new MemoryAppender();
    BasicConfigurator.configure(appender);

    Logger logger = Logger.getLogger(TEST_CATEGORY);
    logger.setLevel(Level.ERROR);

    logger.error(TEST_MESSAGE);

    LinkedList<LoggingEvent> events = appender.getEvents();
    assertEquals(1, events.size());

    LoggingEvent event = events.getFirst();
    assertEquals(Level.ERROR, event.getLevel());
    assertEquals(TEST_CATEGORY, event.getLoggerName());
    assertEquals(TEST_MESSAGE, event.getMessage());
    assertEquals(TEST_LOCATION, event.getLocationInformation().getClassName());

    appender.clear();
    assertEquals(0, events.size());

    logger.error(TEST_MESSAGE);
    assertEquals(1, appender.getEvents().size());
  }
Example #10
0
  @Parameters({"useCloudEnv", "userName", "key", "os", "browser", "browserVersion", "url"})
  @BeforeMethod
  public void setUp(
      @Optional("false") Boolean useCloudEnv,
      @Optional("rashed1") String userName,
      @Optional("2601a7b6-4b39-4712-992a-59ddcd85694c") String key,
      @Optional("Windows 10") String OS,
      @Optional("firefox") String browser,
      @Optional("43.0.1") String browserVersion,
      @Optional("http://www.cigna.com") String url)
      throws IOException {

    if (useCloudEnv == true) {
      // run on cloud
      logger.setLevel(Level.INFO);
      logger.info("Test is running on cloud env");
      getCloudDriver(userName, key, OS, browser, browserVersion);
      System.out.println("Tests is running on Saucelabs, please wait for result");

    } else {
      // run on local
      getLocalDriver(OS, browser, browserVersion);
    }
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
    driver.navigate().to(url);
    driver.manage().window().maximize();
  }
Example #11
0
  /**
   * set a logger's level
   *
   * @param name the name of the logger
   * @param level the level to set
   */
  public void setLoggerLevel(String name, String level) {
    org.apache.log4j.Logger logger = org.apache.log4j.LogManager.getLogger(name);

    if (logger != null) {
      logger.setLevel(org.apache.log4j.Level.toLevel(level));
    }
  }
  public void accept() throws Exception {

    // set up appender
    Layout layout = new SimpleLayout();
    Appender appender = new FileAppender(layout, ACCEPT_FILE, false);

    // create LevelMatchFilter
    LevelMatchFilter matchFilter = new LevelMatchFilter();

    // attach match filter to appender
    appender.addFilter(matchFilter);

    // attach DenyAllFilter to end of filter chain to deny neutral
    // (non matching) messages
    appender.addFilter(new DenyAllFilter());

    // set appender on root and set level to debug
    root.addAppender(appender);
    root.setLevel(Level.TRACE);

    Level[] levelArray =
        new Level[] {Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL};
    for (int x = 0; x < levelArray.length; x++) {
      // set the level to match
      matchFilter.setLevelToMatch(levelArray[x].toString());
      common("pass " + x + "; filter set to accept only " + levelArray[x].toString() + " msgs");
    }

    Transformer.transform(ACCEPT_FILE, ACCEPT_FILTERED, new LineNumberFilter());
    assertTrue(Compare.compare(ACCEPT_FILTERED, ACCEPT_WITNESS));
  }
  public void deny() throws Exception {

    // set up appender
    Layout layout = new SimpleLayout();
    Appender appender = new FileAppender(layout, DENY_FILE, false);

    // create LevelMatchFilter, set to deny matches
    LevelMatchFilter matchFilter = new LevelMatchFilter();
    matchFilter.setAcceptOnMatch(false);

    // attach match filter to appender
    appender.addFilter(matchFilter);

    // set appender on root and set level to debug
    root.addAppender(appender);
    root.setLevel(Level.TRACE);

    Level[] levelArray =
        new Level[] {Level.TRACE, Level.DEBUG, Level.INFO, Level.WARN, Level.ERROR, Level.FATAL};
    for (int x = 0; x < levelArray.length; x++) {
      // set the level to match
      matchFilter.setLevelToMatch(levelArray[x].toString());
      common("pass " + x + "; filter set to deny only " + levelArray[x].toString() + " msgs");
    }

    Transformer.transform(DENY_FILE, DENY_FILTERED, new LineNumberFilter());
    assertTrue(Compare.compare(DENY_FILTERED, DENY_WITNESS));
  }
  @Test
  public void append_basic() {
    MockLoggingChannel log = new MockLoggingChannel();
    KettleLogChannelAppender appender = new KettleLogChannelAppender(log);
    Logger testLogger = Logger.getLogger(getClass());
    testLogger.setLevel(Level.ALL);
    Layout layout = new Log4jKettleLayout();

    // ALL, INFO, and WARN messages should be interpreted as "basic" messages
    @SuppressWarnings("deprecation")
    LoggingEvent infoEvent =
        new LoggingEvent("org.test", testLogger, Priority.INFO, "Testing Info", null);
    @SuppressWarnings("deprecation")
    LoggingEvent warnEvent =
        new LoggingEvent("org.test", testLogger, Priority.WARN, "Testing Warning", null);
    @SuppressWarnings("deprecation")
    LoggingEvent allEvent =
        new LoggingEvent(
            "org.test", testLogger, Priority.toPriority(Priority.ALL_INT), "Testing All", null);
    appender.doAppend(infoEvent);
    appender.doAppend(warnEvent);
    appender.doAppend(allEvent);

    assertEquals(0, log.getDebugMessages().size());
    assertEquals(0, log.getDetailedMessages().size());
    assertEquals(0, log.getErrorMessages().size());
    assertEquals(0, log.getMinimalMessages().size());
    assertEquals(0, log.getRowLevelMessages().size());

    assertEquals(3, log.getBasicMessages().size());
    assertEquals(layout.format(infoEvent), log.getBasicMessages().get(0).getMessage());
    assertEquals(layout.format(warnEvent), log.getBasicMessages().get(1).getMessage());
    assertEquals(layout.format(allEvent), log.getBasicMessages().get(2).getMessage());
  }
  @Override
  public void analysisProgressed(AnalysisEvent event) {
    // Because BDSTool appends its own logging appender, we want to get rid
    // of it.
    if (!loggersCleaned) {
      cleanUpLoggerAppenders();
    }

    // Since it appends the root logger, it also takes over the level. Set
    // it to the level we care about.
    log.setLevel(level);

    if (counter % STATUS_REPORT_INTERVAL == 0) {
      try {

        Map<String, ?> statusMap = event.status();
        Object compPercent = statusMap.get(COMPLETION_PERCENT);

        if (compPercent instanceof Long) {
          Long compPercentInt = (Long) compPercent;
          if (compPercentInt > 0) {
            log.info("Completion percent: " + compPercentInt + "%");
          }
        }
      } catch (Throwable e) {
        log.warn("Could not get update" + e.getMessage());
      }
    }
    counter++;
  }
Example #16
0
    /* (non-Javadoc)
     * @see org.apache.hadoop.mapreduce.Mapper#setup(org.apache.hadoop.mapreduce.Mapper.Context)
     */
    protected void setup(Context context) throws IOException, InterruptedException {
      Configuration conf = context.getConfiguration();
      if (conf.getBoolean("debug.on", false)) {
        LOG.setLevel(Level.DEBUG);
        System.out.println("in debug mode");
      }

      fieldDelim = conf.get("field.delim", ",");
      subFieldDelim = conf.get("sub.field.delim", ":");
      String ratingFilePrefix = conf.get("utp.rating.file.prefix", "rating");
      isRatingFileSplit =
          ((FileSplit) context.getInputSplit()).getPath().getName().startsWith(ratingFilePrefix);
      String ratingStatFilePrefix = conf.get("utp.rating.stat.file.prefix", "stat");
      isRatingStatFileSplit =
          ((FileSplit) context.getInputSplit())
              .getPath()
              .getName()
              .startsWith(ratingStatFilePrefix);

      linearCorrelation = conf.getBoolean("utp.correlation.linear", true);
      int ratingTimeWindow = conf.getInt("utp.rating.time.window.hour", -1);
      ratingTimeCutoff =
          ratingTimeWindow > 0
              ? System.currentTimeMillis() / 1000 - ratingTimeWindow * 60L * 60L
              : -1;

      minInputRating = conf.getInt("utp.min.input.rating", -1);
      minCorrelation = conf.getInt("utp.min.correlation", -1);

      userRatingWithContext = conf.getBoolean("utp.user.rating.with.context", false);
      LOG.info("isRatingFileSplit:" + isRatingFileSplit);
    }
Example #17
0
  /**
   * Extract a simple mime type
   *
   * @param content
   * @return
   */
  public String transform(String content) {

    logger.setLevel(Level.DEBUG);

    // no dot
    if (content.lastIndexOf(".") < 0) {
      logger.debug("No dot found for " + content);
      return MimeTypeExtractor.MIME_DEFAULT;
    }

    String extension = content.substring(content.lastIndexOf(".") + 1);
    logger.debug("Extension is " + extension);
    if (MIME_DOC_LIST.contains(extension)) {
      logger.info("Found mime " + MIME_DOC + " for " + content);
      return MIME_DOC;
    }
    if (MIME_EXCEL_LIST.contains(extension)) {
      logger.info("Found mime " + MIME_EXCEL + " for " + content);
      return MIME_EXCEL;
    }
    if (MIME_POWERPOINT_LIST.contains(extension)) {
      logger.info("Found mime " + MIME_POWERPOINT + " for " + content);
      return MIME_POWERPOINT;
    }
    if (MIME_IMAGE_LIST.contains(extension)) {
      logger.info("Found mime " + MIME_IMAGE + " for " + content);
      return MIME_IMAGE;
    }
    if (MIME_PDF_LIST.contains(extension)) {
      logger.info("Found mime " + MIME_PDF + " for " + content);
      return MIME_PDF;
    }
    logger.info("No suitable extension found for " + content);
    return MimeTypeExtractor.MIME_DEFAULT;
  }
Example #18
0
    public void configure(JobConf job) {
      sLogger.setLevel(Level.INFO);
      srcLang = job.get("fLang");
      mJob = job;
      pwsimMapping = new HMapIV<ArrayListOfIntsWritable>();
      valOut = new PairOfIntString();
      keyOut = new PairOfInts();

      // read doc ids of sample into vectors
      String samplesFile = job.get("Ivory.SampleFile");
      if (samplesFile != null) {
        try {
          samplesMap = readSamplesFromCache(getFilename(samplesFile), job);
        } catch (NumberFormatException e) {
          e.printStackTrace();
          throw new RuntimeException("Incorrect format in " + samplesFile);
        } catch (IOException e) {
          e.printStackTrace();
          throw new RuntimeException("I/O error in " + samplesFile);
        } catch (Exception e) {
          e.printStackTrace();
          throw new RuntimeException("Error reading sample file: " + samplesFile);
        }
      }
    }
  static {
    new SystemEnvironment().setProperty(GoConstants.USE_COMPRESSED_JAVASCRIPT, "false");
    Logger rootLogger = Logger.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    try {
      Filter filter =
          new Filter() {
            @Override
            public int decide(LoggingEvent loggingEvent) {
              return loggingEvent.getLoggerName().startsWith("com.thoughtworks.go.util.PerfTimer")
                      || loggingEvent
                          .getLoggerName()
                          .startsWith(
                              "com.thoughtworks.go.server.service.PipelineConfigServicePerformanceTest")
                  ? 0
                  : -1;
            }
          };
      ConsoleAppender consoleAppender =
          new ConsoleAppender(new PatternLayout("%d [%p|%c|%C{1}] %m%n"));
      consoleAppender.addFilter(filter);
      consoleAppender.setName(consoleAppenderForPerformanceTest);

      RollingFileAppender rollingFileAppender =
          new RollingFileAppender(
              new PatternLayout("%d [%p|%c|%C{1}] %m%n"), "/tmp/config-save-perf.log", false);
      rollingFileAppender.addFilter(filter);
      rollingFileAppender.setName(rollingFileAppenderForPerformanceTest);
      rootLogger.addAppender(rollingFileAppender);
      rootLogger.addAppender(consoleAppender);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 /**
  * AsWriterTask writes data into Aerospike server. In processLine() function using column
  * definition and each record in list format of bins it maps the bin name to its value. After
  * processing it writes the data to Aerospike server using writeToAS().
  *
  * @param fileName Name of the data file
  * @param lineNumber Line number in the file fileName
  * @param lineSize Size of the line to keep track of record processed
  * @param columns List of column separated entries in this lineNumber
  * @param metadataColumnDefs Column Definitions for special columns like key,set
  * @param binColumnDefs Column Definitions for bin columns
  * @param client Aerospike client
  * @param params User given parameters
  * @param counters Counter for stats
  */
 public AsWriterTask(
     String fileName,
     int lineNumber,
     int lineSize,
     List<String> columns,
     List<ColumnDefinition> metadataColumnDefs,
     List<ColumnDefinition> binColumnDefs,
     AerospikeClient client,
     Parameters params,
     Counter counters) {
   this.columns = columns;
   this.client = client;
   this.writePolicy = params.writePolicy;
   this.writePolicy.expiration = params.ttl;
   this.timeZoneOffset = params.timeZoneOffset;
   this.nameSpace = params.namespace;
   this.set = params.set;
   this.metadataMapping = metadataColumnDefs;
   this.binMapping = binColumnDefs;
   this.counters = counters;
   this.fileName = fileName;
   this.abortErrorCount = params.abortErrorCount;
   this.lineNumber = lineNumber;
   this.lineSize = lineSize;
   if (params.verbose) {
     log.setLevel(Level.DEBUG);
   }
 }
Example #21
0
 public static void setLevel(Logger logger, Level level, String... allLoggers) {
   Appender app = Logger.getLogger("jrds").getAppender(JrdsLoggerConfiguration.APPENDERNAME);
   // The system property override the code log level
   if (System.getProperty("jrds.testloglevel") != null) {
     level = Level.toLevel(System.getProperty("jrds.testloglevel"));
     logger.setLevel(level);
   }
   logger.setLevel(level);
   for (String loggerName : allLoggers) {
     Logger l = Logger.getLogger(loggerName);
     l.setLevel(level);
     if (l.getAppender(JrdsLoggerConfiguration.APPENDERNAME) != null) {
       l.addAppender(app);
     }
   }
 }
 /**
  * Sets the Luntbuild HTML log.
  *
  * @param installDir the luntbuild installation directory
  * @throws IOException from {@link FileAppender#FileAppender(org.apache.log4j.Layout,
  *     java.lang.String, boolean)}
  */
 public final void setLuntbuildHtmlLog(Appender app) {
   if (app != null) {
     ((FileAppender) app)
         .setFile(
             new File(Luntbuild.installDir + "/logs/" + Luntbuild.log4jFileName)
                 .getAbsolutePath());
     ((FileAppender) app).activateOptions();
   } else {
     logger.warn("Can not find luntbuild_logfile appender, creating...");
     HTMLLayout layout = new HTMLLayout();
     layout.setTitle("Luntbuild System Log");
     layout.setLocationInfo(true);
     try {
       app =
           new FileAppender(
               layout,
               new File(Luntbuild.installDir + "/logs/" + Luntbuild.log4jFileName)
                   .getAbsolutePath(),
               true);
       ((FileAppender) app).setAppend(false);
       Logger log = LogManager.getLogger("com.luntsys.luntbuild");
       log.setLevel(Level.INFO);
       log.addAppender(app);
       ((FileAppender) app).activateOptions();
     } catch (Exception e) {
       logger.error("Can not create luntbuild_logfile appender");
     }
   }
 }
 /**
  * Sets the Luntbuild text log.
  *
  * @param installDir the luntbuild installation directory
  * @throws IOException from {@link FileAppender#FileAppender(org.apache.log4j.Layout,
  *     java.lang.String, boolean)}
  */
 public final void setLuntbuildTextLog(Appender app) {
   if (app != null) {
     ((FileAppender) app)
         .setFile(
             new File(Luntbuild.installDir + "/logs/" + Luntbuild.log4jFileNameTxt)
                 .getAbsolutePath());
     ((FileAppender) app).activateOptions();
   } else {
     logger.warn("Can not find luntbuild_txt_logfile appender, creating...");
     Layout layout = new PatternLayout("%5p [%t] (%F:%L) - %m%n");
     try {
       app =
           new FileAppender(
               layout,
               new File(Luntbuild.installDir + "/logs/" + Luntbuild.log4jFileNameTxt)
                   .getAbsolutePath(),
               true);
       Logger log = LogManager.getLogger("com.luntsys.luntbuild");
       log.setLevel(Level.INFO);
       log.addAppender(app);
       ((FileAppender) app).activateOptions();
     } catch (Exception e) {
       logger.error("Can not create luntbuild_txt_logfile appender");
     }
   }
 }
Example #24
0
  /**
   * setLogLevel
   *
   * <p>Set the logging level for a named logger associated with this resource. If a callback
   * listener is assigned to the resource then invoke the listener to handle the assignment
   *
   * @param int value of a CF::LogLevels enumeration
   */
  public void setLogLevel(String logger_id, int newLogLevel) throws UnknownIdentifier {

    if (this.logListener != null) {
      if (logger_id == logName) {
        this.logLevel = newLogLevel;
      }

      this.logListener.logLevelChanged(logger_id, newLogLevel);
    } else {
      Level tlevel = Level.INFO;
      tlevel = logging.ConvertToLog4Level(newLogLevel);

      if (logger_id != null) {
        Logger logger = Logger.getLogger(logger_id);
        if (logger != null) {
          logger.setLevel(tlevel);
          if (logger_id == logName) {
            logLevel = newLogLevel;
          }
        }
      } else {
        Logger.getRootLogger().setLevel(tlevel);
      }
    }
  }
Example #25
0
  public void testOverflowHandling() throws Exception {
    Logger logger = Logger.getLogger("AppenderTest.overflowTest");
    AsyncCoalescingStatisticsAppender appender = new AsyncCoalescingStatisticsAppender();
    appender.setName("overflowTestAppender");
    appender.setTimeSlice(1000);
    appender.setQueueSize(2); // set low queue size so we overflow
    logger.addAppender(appender);
    logger.setAdditivity(false);
    logger.setLevel(Level.INFO);
    appender.activateOptions();

    for (int i = 0; i < 1000; i++) {
      StopWatch stopWatch = new StopWatch("testOverflow");
      Math
          .random(); // this should happen super fast, faster than the appender's Dispatcher thread
                     // can drain
      logger.info(stopWatch.stop());
    }

    // again close the appender
    appender.close();
    assertTrue(
        "Expected some stop watch messages to get discarded",
        appender.getNumDiscardedMessages() > 0);
  }
Example #26
0
  @BeforeClass
  public static void configure() throws Exception {
    Tools.configure();

    logger.setLevel(Level.TRACE);
    Tools.setLevel(
        new String[] {StarterNode.class.toString(), Starter.class.toString()}, logger.getLevel());
  }
Example #27
0
 /**
  * 结束Trace. 提升项目默认Logger的级别回到原来的值, 同时关闭traceAppender的阀值到Off. 需要先注入项目默认Logger名称及traceAppender名称.
  */
 @ManagedOperation(description = "Stop trace")
 public void stopTrace() {
   AssertUtils.hasText(traceAppenderName);
   Logger logger = Logger.getLogger(projectLoggerName);
   logger.setLevel(projectLoggerOrgLevel);
   setTraceAppenderThreshold(logger, Level.OFF);
   mbeanLogger.info("Stop trace");
 }
Example #28
0
 public SeleniumXml() throws IOException {
   this.map = FastMap.newInstance();
   if (props == null) {
     props = new Properties();
     initConfig();
   }
   logger.setLevel(Level.DEBUG);
 }
Example #29
0
  public static void main(String[] args) {
    // A JDBCIDHandler
    MyIDHandler idhandler = new MyIDHandler();

    // A JDBCColumnHandler
    MyColumnHandler colHandler = new MyColumnHandler();

    // Ensure to have all necessary drivers installed !
    try {
      Driver d = (Driver) (Class.forName("oracle.jdbc.driver.OracleDriver").newInstance());
      DriverManager.registerDriver(d);
    } catch (Exception e) {
      e.printStackTrace();
    }

    // Set the priority which messages have to be logged
    logger.setLevel(Level.INFO);

    // Create a new instance of JDBCAppender
    JDBCAppender ja = new JDBCAppender();

    // Set options with method setOption()
    ja.setConnector("org.apache.log4j.jdbcplus.examples.OracleConnectionHandler");
    ja.setUrl(
        "jdbc:oracle:thin:@"
            + "(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 62.52.100.41)(PORT = 1521)))"
            + "(CONNECT_DATA = (SERVICE_NAME = oracle8i)))");
    ja.setUsername("danko");
    ja.setPassword("danko");

    ja.setTable("logtest");

    ja.setColumn("id", JDBCLogType.ID, idhandler, "INTEGER", Types.INTEGER);
    ja.setColumn("prio", JDBCLogType.PRIO, "", "VARCHAR", Types.VARCHAR);
    ja.setColumn("cat", JDBCLogType.CAT, "", "VARCHAR", Types.VARCHAR);
    ja.setColumn("msg", JDBCLogType.MSG, "", "VARCHAR", Types.VARCHAR);
    ja.setColumn("info", JDBCLogType.DYNAMIC, colHandler, "VARCHAR", Types.VARCHAR);
    ja.setColumn("addon", JDBCLogType.EMPTY, "", "VARCHAR", Types.VARCHAR);
    ja.setColumn("the_timestamp", JDBCLogType.TIMESTAMP, "", "TIMESTAMP", Types.TIMESTAMP);
    ja.setColumn("created_by", JDBCLogType.STATIC, "ME", "VARCHAR", Types.VARCHAR);

    // other options
    // ja.setBuffer("1");
    // ja.setCommit("Y");

    // Add the appender to a category
    logger.addAppender(ja);

    // These messages with Priority >= setted priority will be logged to the database.
    logger.debug("debug");
    logger.info("info");
    logger.error("error");
    logger.fatal("fatal");

    // not required
    logger.removeAppender(ja);
  }
Example #30
0
 public static void setLevel(String type) {
   BasicConfigurator.configure();
   Level lvl = null;
   if (type == "info") lvl = Level.INFO;
   else if (type == "warning") lvl = Level.WARN;
   else if (type == "debug") lvl = Level.DEBUG;
   else lvl = Level.INFO;
   logger.setLevel(lvl);
 }