@Override
  public void init(Map params, File configDir) throws DataProviderException {
    String logConfig = (String) params.get("log_config");
    if (logConfig != null) {
      File logConfigFile = new File(configDir, logConfig);
      String logRefresh = (String) params.get("log_config_refresh_seconds");
      if (logRefresh != null) {
        DOMConfigurator.configureAndWatch(
            logConfigFile.getAbsolutePath(), Integer.parseInt(logRefresh) * 1000);
      } else {
        DOMConfigurator.configure(logConfigFile.getAbsolutePath());
      }
    } // else the bridge to logback is expected

    logger = Logger.getLogger(Constants.LOGGER_CAT);

    logger.info("Adapter Logger start.");

    // Read the Adapter Set name, which is supplied by the Server as a parameter
    String adapterSetId = (String) params.get("adapters_conf.id");

    // Put a reference to this instance on a static map
    // to be read by the Metadata Adapter
    feedMap.put(adapterSetId, this);

    logger.info("DartDataAdapter ready");
  }
示例#2
0
  // http://jira.codehaus.org/browse/PERFFORJ-21
  public void testAppendersTimesliceOver() throws Exception {
    // need to do immediateflush on the fileappender since close will not be called
    DOMConfigurator.configure(getClass().getResource("log4j-timeslicebug.xml"));

    AsyncCoalescingStatisticsAppender appender =
        (AsyncCoalescingStatisticsAppender)
            Logger.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");

    // log from a bunch of threads
    TestLoggingThread[] testThreads = new TestLoggingThread[10];
    for (int i = 0; i < testThreads.length; i++) {
      testThreads[i] = new TestLoggingThread();
      testThreads[i].start();
    }

    for (TestLoggingThread testThread : testThreads) {
      testThread.join();
    }

    // we should see all the logging after waiting this long
    Thread.sleep(2 * appender.getTimeSlice());

    // simple verification ensures that the total number of logged messages is correct.
    // tagName  avg           min     max     std dev       count, which is group 1
    String regex = "tag\\d+\\s*\\d+\\.\\d\\s*\\d+\\s*\\d+\\s*\\d+\\.\\d\\s*(\\d+)";
    Pattern statLinePattern = Pattern.compile(regex);
    Scanner scanner = new Scanner(new File("target/statisticsLog-timeslicebug.log"));

    int totalCount = 0;
    while (scanner.findWithinHorizon(statLinePattern, 0) != null) {
      totalCount += Integer.parseInt(scanner.match().group(1));
    }
    assertEquals(testThreads.length * TestLoggingThread.STOP_WATCH_COUNT, totalCount);
  }
示例#3
0
 /**
  * Initialize log4j logging using the Tolven appender specification.
  *
  * <p>Note: This method should <i>not</i> be called within an environment such as JBoss that has a
  * separate log4j configuration. In that case, the TolvenLogger will use the appender
  * configuration supplied by that environment.
  *
  * @param log4jConfiguration The name of the file containing the log4j configuration. If null, the
  *     a file named tolven-log4j.xml on the classpath will be used.
  * @param logFilename The name of the log file. This file will be created if it does not already
  *     exist. If null, a default file named <code>${user.dir}/tolven.log</code> will be used.
  */
 public static void initialize(String log4jConfiguration, String logFilename) {
   try {
     File logFile;
     if (logFilename != null) {
       logFile = new File(logFilename);
     } else {
       logFile = new File(DEFAULT_LOG_FILE);
     }
     System.setProperty(LOG_FILE_PROPERTY, logFile.getAbsolutePath());
     logFile.getParentFile().mkdirs();
     logFile.createNewFile();
     defaultInitialize();
     Logger.getRootLogger()
         .info(
             "Start log4j - Configuration: "
                 + log4jConfiguration
                 + ", logFileName: "
                 + logFile.getAbsolutePath());
     BasicConfigurator.resetConfiguration();
     URL configURL;
     try {
       configURL = new URL(log4jConfiguration);
     } catch (Exception e) {
       configURL = Loader.getResource(log4jConfiguration);
     }
     DOMConfigurator.configure(configURL);
   } catch (Exception e) {
     throw new RuntimeException(
         "Exception while initializing Tolven log4j. log4jConfiguration: "
             + log4jConfiguration
             + " logFilename: "
             + logFilename,
         e);
   }
 }
示例#4
0
  public void testAppenders() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4j.xml"));

    AsyncCoalescingStatisticsAppender appender =
        (AsyncCoalescingStatisticsAppender)
            Logger.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");

    // log from a bunch of threads
    TestLoggingThread[] testThreads = new TestLoggingThread[10];
    for (int i = 0; i < testThreads.length; i++) {
      testThreads[i] = new TestLoggingThread();
      testThreads[i].start();
    }

    for (TestLoggingThread testThread : testThreads) {
      testThread.join();
    }

    // close the output appender, which prevents us from returning until this method completes.
    appender.close();

    // simple verification ensures that the total number of logged messages is correct.
    // tagName  avg           min     max     std dev       count, which is group 1
    String regex = "tag\\d\\s*\\d+\\.\\d\\s*\\d+\\s*\\d+\\s*\\d+\\.\\d\\s*(\\d+)";
    Pattern statLinePattern = Pattern.compile(regex);
    Scanner scanner = new Scanner(new File("target/statisticsLog.log"));

    int totalCount = 0;
    while (scanner.findWithinHorizon(statLinePattern, 0) != null) {
      totalCount += Integer.parseInt(scanner.match().group(1));
    }
    assertEquals(testThreads.length * TestLoggingThread.STOP_WATCH_COUNT, totalCount);
  }
示例#5
0
  public void testDomConfigurator() throws Exception {

    // Configuration with configuration-file
    DOMConfigurator.configure("./src/org/apache/log4j/jdbcplus/examples/test/log4j_test.xml");

    this.doLogging();
  }
示例#6
0
  public static void initCore() throws InitializationFailedException {
    java.security.Security.setProperty("networkaddress.cache.ttl", "0");
    if (System.getProperty("unicorn.home") == null) {
      try {
        URL frameworkDir = Framework.class.getResource("Framework.class");
        if (frameworkDir.getProtocol() != "jar") {
          File unicornHome = new File(frameworkDir.toURI());
          for (int i = 0; i < 6; i++) unicornHome = unicornHome.getParentFile();
          System.setProperty("unicorn.home", unicornHome.getAbsolutePath());
        }
      } catch (URISyntaxException e) {
        throw new InitializationFailedException(e.getMessage(), e);
      }
    }

    // Log4j initialization attempt
    URL log4jURL = Framework.class.getResource("/unicorn_log4j.xml");
    if (log4jURL != null) {
      DOMConfigurator.configure(log4jURL);
      logger.info("OK - Log4j successfully initialized");
      logger.debug("> Used log4j.xml file: " + log4jURL.toString());
    } else {
      logger.warn("Log4j config file \"log4j.xml\" could not be found in classpath.");
      logger.warn("Log4j will not be initialized");
    }
  }
  @Test
  public void run01() {

    DOMConfigurator.configure("log4j.xml");

    Log.startTestCase("VerifyMenuLinks_01");

    Samples_Page SamplesPage = new Samples_Page(null);
    SamplesPage.getSamplesPage();

    Log.info("Page Title : " + Wrapper.getTitle("Samples - SPI"));
    Log.info("Page url : " + Wrapper.getURL());

    Icons_Page IconsPage = new Icons_Page(null);
    IconsPage.getIconsPage();

    Log.info("Page Title : " + Wrapper.getTitle("Icons - SPI"));
    Log.info("Page url : " + Wrapper.getURL());

    Iris_Page IrisPage = new Iris_Page(null);
    IrisPage.getIrisPage();

    Log.info("Page Title : " + Wrapper.getTitle("Sources - SPI"));
    Log.info("Page url : " + Wrapper.getURL());

    Home_Page homepage = new Home_Page(null);
    homepage.getHomePage();

    Log.info("Page Title : " + Wrapper.getTitle("SPI"));
    Log.info("Page url : " + Wrapper.getURL());

    Log.endTestCase("VerifyMenuLinks_01");
  }
  static {
    String logfile = System.getProperty("gov.nih.nci.evs.browser.NCImlog4jProperties");
    System.out.println("NCIM Logger prop file = [" + logfile + "]");

    InputStream log4JConfig = null;
    try {
      log4JConfig = new FileInputStream(logfile);
      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(log4JConfig);

      DOMConfigurator.configure(doc.getDocumentElement());
      isInit = true;
    } catch (ParserConfigurationException e) {
      System.out.println("*** Error: Failed to parse log4j configuration file!");
      e.printStackTrace();
    } catch (SAXException e) {
      System.out.println("*** SAX Error: Failed to parse log4j configuration file!");
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println("*** IO Error: log4j configuration file!");
      e.printStackTrace();
    } finally {
      try {
        log4JConfig.close();
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
示例#9
0
  // test for http://jira.codehaus.org/browse/PERFFORJ-22
  public void testFlushOnShutdown() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4j-shutdownbug.xml"));

    // make a bunch of logs, but not enough to go over the timeslice.
    for (int i = 0; i < 5; i++) {
      StopWatch stopWatch = new Log4JStopWatch("tag1");
      Thread.sleep(10 * i);
      stopWatch.stop();
    }

    // at this point none of the file appenders will have written anything because they haven't been
    // flushed
    assertEquals("", FileUtils.readFileToString(new File("target/stats-shutdownbug.log")));
    assertEquals("", FileUtils.readFileToString(new File("target/graphs-shutdownbug.log")));

    // now, to simulate shutdown, get the async appender and run the shutdown hook. We need to use
    // reflection
    // because the shutdown hook is private.
    AsyncCoalescingStatisticsAppender appender =
        (AsyncCoalescingStatisticsAppender)
            Logger.getLogger(StopWatch.DEFAULT_LOGGER_NAME).getAppender("coalescingStatistics");
    Field shutdownField = appender.getClass().getDeclaredField("shutdownHook");
    shutdownField.setAccessible(true);
    Thread shutdownHook = (Thread) shutdownField.get(appender);
    shutdownHook.run();

    // now there should be data in the files
    assertFalse("".equals(FileUtils.readFileToString(new File("target/stats-shutdownbug.log"))));
    assertFalse("".equals(FileUtils.readFileToString(new File("target/graphs-shutdownbug.log"))));
  }
示例#10
0
 /**
  * The main method responsible for starting the coadunation base.
  *
  * @param args the command line arguments
  */
 public static void main() {
   try {
     String logFile = System.getProperty("Log.File");
     if (logFile.endsWith("properties")) {
       System.out.println("Initing the log file from properties.");
       PropertyConfigurator.configure(logFile);
     } else if (logFile.endsWith("xml")) {
       System.out.println("Initing the log file from xml.");
       DOMConfigurator.configure(logFile);
     } else {
       System.out.println("Using the basic configuration.");
       BasicConfigurator.configure();
     }
     System.out.println("Start");
     Runner runner = new Runner();
     ShutdownHook shutdownHook = new ShutdownHook();
     Runtime.getRuntime().addShutdownHook(shutdownHook);
     System.out.println("Core initialization complete");
     System.out.println("Waiting for deployment to complete");
     shutdownHook.monitor();
     runner.shutdown();
     shutdownHook.notifyOfCompletion();
     log.info("Shut down complete");
   } catch (Exception ex) {
     System.out.println("Failed to run the Coadunation base [" + ex.getMessage() + "]");
     ex.printStackTrace(System.out);
     System.exit(-1);
   }
 }
示例#11
0
  protected void setUp() throws Exception {
    if (!isConfigured()) {
      DOMConfigurator.configure("log4j.xml");
      iConfigured = true;
    }
    configProperties = new Properties();
    try {
      configProperties.load(
          TestBase.class.getClassLoader().getResourceAsStream("config.properties"));
    } catch (IOException e) {
      e.printStackTrace();
    }

    useRemote = Boolean.parseBoolean(configProperties.getProperty("use_remote"));

    bro = configProperties.getProperty("browser");
    chromeDriver = configProperties.getProperty("chromedriver");
    ieDriver = configProperties.getProperty("iedriver");

    if (useRemote) {
      File profileDir = new File(getClass().getResource("/seleniumProfile").getFile());
      FirefoxProfile profile = new FirefoxProfile(profileDir);
      DesiredCapabilities capabilities = DesiredCapabilities.firefox();
      capabilities.setCapability(FirefoxDriver.PROFILE, profile);
      capabilities.setCapability("binary", "/usr/bin/firefox");
      String remoteUrl = configProperties.getProperty("selenium_remote_url");
      driver = new RemoteWebDriver(new URL(remoteUrl), capabilities);
      ((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
    } else {
      if (bro.toLowerCase().equals("firefox")) {

        File profileDir = null;
        profileDir = new File(getClass().getResource("/seleniumProfile").getFile());
        FirefoxProfile profile = new FirefoxProfile(profileDir);
        driver = new FirefoxDriver(profile);
      }
      if (bro.toLowerCase().equals("chrome")) {
        System.setProperty("webdriver.chrome.driver", chromeDriver);
        Map<String, Object> prefs = new HashMap<String, Object>();
        prefs.put("download.default_directory", "target");
        DesiredCapabilities caps = DesiredCapabilities.chrome();
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", prefs);
        caps.setCapability(ChromeOptions.CAPABILITY, options);
        driver = new ChromeDriver(caps);
      }
      if (bro.toLowerCase().equals("ie")) {
        DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
        capabilities.setCapability(
            InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
        System.setProperty("webdriver.ie.driver", ieDriver);
        capabilities.setCapability("ignoreZoomSetting", true);
        capabilities.setCapability("nativeEvents", false);
        driver = new InternetExplorerDriver(capabilities);
      }
    }
    int timeout = Integer.parseInt(configProperties.getProperty("driver_timeout"));
    driver.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
  }
 static {
   try {
     DOMConfigurator.configure(PathUtils.getRealPath("classpath:log4j.xml"));
     CONFIGS.load(new FileInputStream(PathUtils.getRealPath("classpath:sstk.properties")));
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
示例#13
0
  public void testAsync() throws Exception {
    // Configuration with configuration-file
    DOMConfigurator.configure("./src/org/apache/log4j/jdbcplus/examples/test/log4j_async.xml");

    for (int i = 0; i < 1; i++) {
      this.doLogging();
    }
  }
示例#14
0
 /** Class constructor. Initialise variables: MaxHits = 3; similarityMinScore = 1.0; */
 public DBpediaLookup() {
   DOMConfigurator.configure("logger.xml");
   MaxHits = 3;
   similarityMinScore = 1.0;
   similartityAlgorithm = new Levenshtein();
   doubleCheckSimilarity = false;
   obligatoryClass = false;
 }
 @BeforeClass
 public static void initH2() {
   try {
     DeleteDbFiles.execute("", "JPADroolsFlow", true);
     h2Server = Server.createTcpServer(new String[0]);
     h2Server.start();
   } catch (final SQLException e) {
     throw new RuntimeException("can't start h2 server db", e);
   }
   DOMConfigurator.configure(SingleSessionCommandServiceTest.class.getResource("/log4j.xml"));
 }
示例#16
0
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		if (args.length < 2) {
			System.err
					.println("Usage: <program> -<input-method> [input-parameters] -<output-method> [output-parameters]");
		} else {
			DOMConfigurator.configure(DecathlonCalculator.class.getResource("log4j.xml"));
			DecathlonCalculator c = new DecathlonCalculator(args);
			c.process();
		}

	}
 @BeforeClass
 public static void init() throws IOException {
   File propertyFile =
       new File("src/test/config/bes_media_file_log_batch_update_unittest.properties");
   FileInputStream in = new FileInputStream(propertyFile);
   properties = new Properties();
   properties.load(in);
   in.close();
   System.getProperties().put("log4j.defaultInitOverride", "true");
   DOMConfigurator.configure(properties.getProperty("log4j.config.file.path"));
 }
示例#18
0
 /**
  * Initialize logs
  *
  * @since 5.4.2
  */
 public void initLogs() {
   File logFile = getLogConfFile();
   try {
     System.out.println("Try to configure logs with " + logFile);
     System.setProperty(org.nuxeo.common.Environment.NUXEO_LOG_DIR, getLogDir().getPath());
     DOMConfigurator.configure(logFile.toURI().toURL());
     log.info("Logs successfully configured.");
   } catch (MalformedURLException e) {
     log.error("Could not initialize logs with " + logFile, e);
   }
 }
示例#19
0
文件: Main.java 项目: cawka/DSMS_NBC
  public static void main(String[] args)
      throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
    DOMConfigurator.configure("logger.xml");

    Configuration conf = new Configuration();
    conf.configure(new File("configuation.xml"));
    conf.getEngineDefaults().getThreading().setListenerDispatchPreserveOrder(false);

    conf.addEventTypeAutoName(Main.class.getPackage().getName());

    init(conf);

    EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(conf);
    String statement = "CREATE WINDOW trainSet.win:length(1000) as select * from InputTuple";
    epService.getEPAdministrator().createEPL(statement);

    statement = "INSERT INTO trainSet SELECT * FROM InputTuple";
    epService.getEPAdministrator().createEPL(statement);

    ////////// TASK 1. Performing Naive Bayes Classification over a data stream

    StreamClassifier classifier = new StreamClassifier(conf);
    classifier.verticalizeTuples(_fieldNames);
    EPStatement stmt = classifier.run(_fieldNames.length + 1);

    /////////// TASK 2. Periodically check quality of the classifier

    PeriodicChecker checker = new PeriodicChecker(conf, stmt);
    checker.run(
        "2 seconds", 100, 0.9); // every two seconds test last 100 tuples to satisfy threshold 0.7

    //////////

    _log.info("started");

    // emulate a continuous input
    AdapterInputSource adapterInputSource = new AdapterInputSource(new File("simulation.csv"));

    CSVInputAdapterSpec spec = new CSVInputAdapterSpec(adapterInputSource, "InputTuple");
    spec.setEventsPerSec(400);
    spec.setLooping(true);
    spec.setUsingEngineThread(true);

    (new CSVInputAdapter(epService, spec)).start();

    try {
      Thread.sleep(10000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    _log.info("stopped");
  }
 static {
   ResourceBundle resourceBundle = null;
   try {
     String log4j = System.getProperty("log4j.configuration");
     DOMConfigurator.configure(log4j);
     System.out.println("->Logging configured (log4j.properties)");
   } catch (MissingResourceException e) {
     System.out.println("Missing resource : log4j.properties");
     System.out.println("Iris not started - see log file");
     System.exit(0);
   }
 }
 /** {@inheritDoc} */
 public boolean parseUnrecognizedElement(Element element, Properties props) throws Exception {
   if ("connectionSource".equals(element.getNodeName())) {
     Object instance = DOMConfigurator.parseElement(element, props, ConnectionSource.class);
     if (instance instanceof ConnectionSource) {
       ConnectionSource source = (ConnectionSource) instance;
       source.activateOptions();
       setConnectionSource(source);
     }
     return true;
   }
   return false;
 }
示例#22
0
  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {
      String appPath = config.getServletContext().getRealPath("");
      // 是否为开发mode
      debug = "true".equals(config.getInitParameter("development"));
      // 读取log4j.xml配置文件
      DOMConfigurator.configure(appPath + "/WEB-INF/log4j.xml");

      logger.info("Starting JForum. Debug mode is " + debug);
      //
      ConfigLoader.startSystemglobals(appPath);
      // 启动缓存引擎
      ConfigLoader.startCacheEngine();

      // Configure the template engine
      Configuration templateCfg = new Configuration();
      templateCfg.setTemplateUpdateDelay(2);
      templateCfg.setSetting("number_format", "#");
      templateCfg.setSharedVariable("startupTime", new Long(new Date().getTime()));

      // Create the default template loader
      String defaultPath = SystemGlobals.getApplicationPath() + "/templates";
      FileTemplateLoader defaultLoader = new FileTemplateLoader(new File(defaultPath));

      String extraTemplatePath = SystemGlobals.getValue(ConfigKeys.FREEMARKER_EXTRA_TEMPLATE_PATH);

      if (StringUtils.isNotBlank(extraTemplatePath)) {
        // An extra template path is configured, we need a MultiTemplateLoader
        FileTemplateLoader extraLoader = new FileTemplateLoader(new File(extraTemplatePath));
        TemplateLoader[] loaders = new TemplateLoader[] {extraLoader, defaultLoader};
        MultiTemplateLoader multiLoader = new MultiTemplateLoader(loaders);
        templateCfg.setTemplateLoader(multiLoader);
      } else {
        // An extra template path is not configured, we only need the default loader
        templateCfg.setTemplateLoader(defaultLoader);
      }
      // 载入模块
      ModulesRepository.init(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR));

      this.loadConfigStuff();

      if (!this.debug) {
        templateCfg.setTemplateUpdateDelay(3600);
      }

      JForumExecutionContext.setTemplateConfig(templateCfg);
    } catch (Exception e) {
      throw new ForumStartupException("Error while starting JForum", e);
    }
  }
示例#23
0
  public static void main(String[] args) {
    try {
      if ((new File(GUI.LOG_CONFIG_FILE)).exists()) {
        DOMConfigurator.configure(GUI.LOG_CONFIG_FILE);
      } else {
        DOMConfigurator.configure(GUI.class.getResource("/" + GUI.LOG_CONFIG_FILE));
      }
    } catch (AccessControlException e) {
      BasicConfigurator.configure();
    }

    if (args.length > 0) {
      /* Generate executable JAR */
      if (args.length != 2) {
        throw new RuntimeException("Usage: [input .csc] [output .jar]");
      }
      generate(new File(args[0]), new File(args[1]));
    } else {
      /* Run simulation */
      execute();
    }
  }
示例#24
0
  protected void initLog() {
    if (!logIsInitialized) {
      String logFileName =
          System.getProperty(SoapUISystemProperties.SOAPUI_LOG4j_CONFIG_FILE, "soapui-log4j.xml");
      File log4jconfig =
          root == null ? new File(logFileName) : new File(new File(getRoot()), logFileName);
      if (log4jconfig.exists()) {
        System.out.println("Configuring log4j from [" + log4jconfig.getAbsolutePath() + "]");
        DOMConfigurator.configureAndWatch(log4jconfig.getAbsolutePath(), 5000);
      } else {
        URL url = SoapUI.class.getResource("/com/eviware/soapui/resources/conf/soapui-log4j.xml");
        if (url != null) {
          DOMConfigurator.configure(url);
        } else {
          System.err.println("Missing soapui-log4j.xml configuration");
        }
      }

      logIsInitialized = true;

      log = Logger.getLogger(DefaultSoapUICore.class);
    }
  }
  public GeorchestraConfiguration(String context) {

    this.contextName = context;
    globalDatadir = System.getProperty("georchestra.datadir");
    if (globalDatadir != null) {
      contextDataDir =
          new File(
                  String.format("%s%s%s%s", globalDatadir, File.separator, context, File.separator))
              .getAbsolutePath();

      // Simple check that the path exists
      if (new File(contextDataDir).exists() == false) {
        contextDataDir = null;
        return;
      }
      // loads the application context property file
      FileInputStream propsFis = null;
      try {
        try {
          // application-context
          propsFis = new FileInputStream(new File(contextDataDir, context + ".properties"));
          InputStreamReader isr = new InputStreamReader(propsFis, "UTF8");
          applicationSpecificProperties.load(isr);
        } finally {
          if (propsFis != null) {
            propsFis.close();
          }
        }
      } catch (Exception e) {
        activated = false;
        return;
      }

      // log4j configuration
      File log4jProperties =
          new File(contextDataDir, "log4j" + File.separator + "log4j.properties");
      File log4jXml = new File(contextDataDir, "log4j" + File.separator + "log4j.xml");
      String log4jConfigurationFile = null;
      if (log4jProperties.exists()) {
        log4jConfigurationFile = log4jProperties.getAbsolutePath();
        PropertyConfigurator.configure(log4jConfigurationFile);
      } else if (log4jXml.exists()) {
        log4jConfigurationFile = log4jXml.getAbsolutePath();
        DOMConfigurator.configure(log4jConfigurationFile);
      }
      // everything went well
      activated = true;
    }
  }
示例#26
0
  public void testCsvRenderer() throws Exception {
    DOMConfigurator.configure(getClass().getResource("log4jWCsv.xml"));

    Logger logger = Logger.getLogger("org.perf4j.CsvAppenderTest");

    for (int i = 0; i < 20; i++) {
      StopWatch stopWatch = new Log4JStopWatch(logger);
      Thread.sleep(i * 10);
      stopWatch.stop("csvTest");
    }

    // close the appender
    logger.getAppender("coalescingStatistics").close();

    // verify the statisticsLog.csv file
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (Object line : FileUtils.readLines(new File("./target/statisticsLog.csv"))) {
      String[] values = line.toString().split(",");
      // first column is the tag
      assertEquals("\"csvTest\"", values[0]);
      // next 2 columns are the dates - ensure they can be parsed
      assertTrue(dateFormat.parse(values[1]).before(dateFormat.parse(values[2])));
      // next 3 columns are mean, min and max
      double mean = Double.parseDouble(values[3]);
      int min = Integer.parseInt(values[4]);
      int max = Integer.parseInt(values[5]);
      assertTrue(mean >= min && mean <= max);
      // next column is stddev - ust make sure it's parseable
      Double.parseDouble(values[6]);
      // next column is count
      assertTrue(Integer.parseInt(values[7]) < 20);
      // final column is TPS - just make sure it's parseable
      Double.parseDouble(values[8]);
    }

    // verify the pivotedStatisticsLog.csv file
    for (Object line : FileUtils.readLines(new File("./target/pivotedStatisticsLog.csv"))) {
      String[] values = line.toString().split(",");
      // first 2 columns are the dates - ensure they can be parsed
      assertTrue(dateFormat.parse(values[0]).before(dateFormat.parse(values[1])));
      // next column is mean, ensure it can be parsed
      Double.parseDouble(values[2]);
      // last column should be empty, so make sure last char on string is comma
      assertEquals(',', line.toString().charAt(line.toString().length() - 1));
    }
  }
示例#27
0
  public void init(String[] args) throws ConfigurationException {

    // PropertiesUtil is used both in management server and agent packages,
    // it searches path under class path and common J2EE containers
    // For KVM agent, do it specially here

    File file = new File("/etc/cloudstack/agent/log4j-cloud.xml");
    if (!file.exists()) {
      file = PropertiesUtil.findConfigFile("log4j-cloud.xml");
    }
    DOMConfigurator.configureAndWatch(file.getAbsolutePath());

    s_logger.info("Agent started");

    final Class<?> c = this.getClass();
    _version = c.getPackage().getImplementationVersion();
    if (_version == null) {
      throw new CloudRuntimeException("Unable to find the implementation version of this agent");
    }
    s_logger.info("Implementation Version is " + _version);

    loadProperties();
    parseCommand(args);

    if (s_logger.isDebugEnabled()) {
      List<String> properties = Collections.list((Enumeration<String>) _properties.propertyNames());
      for (String property : properties) {
        s_logger.debug("Found property: " + property);
      }
    }

    s_logger.info("Defaulting to using properties file for storage");
    _storage = new PropertiesStorage();
    _storage.configure("Storage", new HashMap<String, Object>());

    // merge with properties from command line to let resource access
    // command line parameters
    for (Map.Entry<String, Object> cmdLineProp : getCmdLineProperties().entrySet()) {
      _properties.put(cmdLineProp.getKey(), cmdLineProp.getValue());
    }

    s_logger.info("Defaulting to the constant time backoff algorithm");
    _backoff = new ConstantTimeBackoff();
    _backoff.configure("ConstantTimeBackoff", new HashMap<String, Object>());
  }
  @BeforeClass
  public void setUp() throws Exception {

    // Configuring Log4j logs.
    new BaseClass();
    DOMConfigurator.configure(BaseClass.bLog);
    // Setting Excel File -- Test Data xls File
    ExcelUtils.setExcelFile(
        Constant.Path_TestData + Constant.File_TestData, Constant.File_TestappNameSheet);
    // Getting the Test Case name, as it will going to use in so many places
    // The main use is to get the TestCase row from the Test Data Excel sheet
    sTestCaseName = this.toString();
    Log.info(sTestCaseName);
    sTestCaseName = Utils.getTestCaseName(this.toString());
    Log.info(sTestCaseName);
    Log.startTestCase(sTestCaseName);
    testStep = new HelperFunction();
  }
示例#29
0
  // test only
  private static void configLog4j() {
    URL configUrl = System.class.getResource("/conf/log4j-cloud.xml");
    if (configUrl != null) {
      System.out.println("Configure log4j using log4j-cloud.xml");

      try {
        File file = new File(configUrl.toURI());

        System.out.println("Log4j configuration from : " + file.getAbsolutePath());
        DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000);
      } catch (URISyntaxException e) {
        System.out.println("Unable to convert log4j configuration Url to URI");
      }
      // DOMConfigurator.configure(configUrl);
    } else {
      System.out.println("Configure log4j with default properties");
    }
  }
示例#30
0
  static {
    if (System.getProperty("cst.home") != null) {
      baseDir = System.getProperty("cst.home");
    } else {
      baseDir = System.getProperty("CST_HOME");
    }

    if (baseDir == null) {
      throw new ToolsStartException("CST_HOME not set");
    }

    logFile = baseDir + File.separator + CONFIGURATION + File.separator + TOOLS_LOG4J;
    if (!(new File(logFile).exists())) {
      throw new ToolsStartException(logFile + " doesn't exists");
    }

    toolsConf = baseDir + File.separator + CONFIGURATION + File.separator + CORE_CONF;
    if (!(new File(toolsConf).exists())) {
      throw new ToolsStartException(toolsConf + " doesn't exists");
    }

    outDir = baseDir + File.separator + OUT;
    if (!(new File(outDir).exists())) {
      new File(outDir).mkdir();
    }

    inputDir = baseDir + File.separator + INPUT;
    if (!(new File(inputDir).exists())) {
      throw new ToolsStartException(inputDir + " doesn't exists");
    }

    logDir = baseDir + File.separator + LOG;
    if (!(new File(logDir).exists())) {
      new File(logDir).mkdir();
    }

    System.setProperty(baseDirProps, baseDir);
    System.setProperty(inputDirProps, inputDir);
    System.setProperty(outDirProps, outDir);
    System.setProperty(logDirProps, logDir);

    DOMConfigurator.configure(logFile);
  }