Java Code Examples for org.apache.log4j.PropertyConfigurator

The following are top voted examples for showing how to use org.apache.log4j.PropertyConfigurator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: log4j-aws-appenders   File: SNSAppenderIntegrationTest.java   Source Code and License 16 votes vote down vote up
/**
 *  Loads the test-specific Log4J configuration and resets the environment.
 */
public void setUp(String propertiesName)
throws Exception
{
    URL config = ClassLoader.getSystemResource(propertiesName);
    assertNotNull("missing configuration: " + propertiesName, config);

    LogManager.resetConfiguration();
    PropertyConfigurator.configure(config);

    localLogger = Logger.getLogger(getClass());

    runId = String.valueOf(System.currentTimeMillis());
    resourceName = "SNSAppenderIntegrationTest-" + runId;
    System.setProperty("SNSAppenderIntegrationTest.resourceName", resourceName);

    localSNSclient = AmazonSNSClientBuilder.defaultClient();
    localSQSclient = AmazonSQSClientBuilder.defaultClient();
}
 
Example 2
Project: ripme   File: Utils.java   Source Code and License 7 votes vote down vote up
/**
 * Configures root logger, either for FILE output or just console.
 */
public static void configureLogger() {
    LogManager.shutdown();
    String logFile;
    if (getConfigBoolean("log.save", false)) {
        logFile = "log4j.file.properties";
    }
    else {
        logFile = "log4j.properties";
    }
    InputStream stream = Utils.class.getClassLoader().getResourceAsStream(logFile);
    if (stream == null) {
        PropertyConfigurator.configure("src/main/resources/" + logFile);
    } else {
        PropertyConfigurator.configure(stream);
    }
    logger.info("Loaded " + logFile);
    try {
        stream.close();
    } catch (IOException e) { }
}
 
Example 3
Project: TakinRPC   File: HelloImpl.java   Source Code and License 7 votes vote down vote up
public static void main(String[] args) {
    PropertyConfigurator.configure("conf/log4j.properties");
    Method[] methods = HelloImpl.class.getDeclaredMethods();
    for (Method method : methods) {
        System.out.println(method.getName());
        Class<?>[] param = method.getParameterTypes();
        System.out.println(JSON.toJSONString(param));
        try {
            Method m2 = RMethodUtils.searchMethod(HelloImpl.class, method.getName(), param);
            if (m2 == null) {
                System.out.println("null");
            } else {
                System.out.println(method.getName());
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
 
Example 4
Project: oscm   File: Initializer.java   Source Code and License 7 votes vote down vote up
/**
 * On change event
 */
void handleOnChange(File logFile) {
    try {
        long lastModif = logFile.lastModified();
        if (lastModif > logFileLastModified) {
            logFileLastModified = lastModif;
            logger.debug("Reload log4j configuration from "
                    + logFile.getAbsolutePath());
            new PropertyConfigurator().doConfigure(
                    logFile.getAbsolutePath(),
                    LogManager.getLoggerRepository());
            logFileWarning = false;
        }
    } catch (Exception e) {
        if (!logFileWarning) {
            logFileWarning = true;
            logger.error(logFile.getAbsolutePath(), e);
        }
    }
}
 
Example 5
Project: flume-release-1.7.0   File: TestLog4jAppender.java   Source Code and License 7 votes vote down vote up
@Test(expected = EventDeliveryException.class)
public void testSlowness() throws Throwable {
  ch = new SlowMemoryChannel(2000);
  Configurables.configure(ch, new Context());
  configureSource();
  props.put("log4j.appender.out2.Timeout", "1000");
  props.put("log4j.appender.out2.layout", "org.apache.log4j.PatternLayout");
  props.put("log4j.appender.out2.layout.ConversionPattern",
      "%-5p [%t]: %m%n");
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  Thread.currentThread().setName("Log4jAppenderTest");
  int level = 10000;
  String msg = "This is log message number" + String.valueOf(1);
  try {
    logger.log(Level.toLevel(level), msg);
  } catch (FlumeException ex) {
    throw ex.getCause();
  }
}
 
Example 6
Project: fwm   File: App.java   Source Code and License 6 votes vote down vote up
public static void noUiStart() throws Exception{
	AppConfig.firstInit();
	prod = AppConfig.getProd();
	appFileUtil = new AppFileUtil();
	if(!appFileUtil.success()){
		System.err.println(appFileUtil.getErrorMessage());
		System.exit(-1);
	}
	// ignore everything else because this means that we're in a jar file, so the app won't work
	// if it doesn't think that we're prod. 
	PropertyConfigurator.configure(appFileUtil.getLog4JFile().getAbsolutePath());
	AppConfig.init();
	
	String defaultLocationString = AppConfig.config.getString(AppConfig.WORLD_LOCATION);
	File defaultLocation = new File(defaultLocationString);
	
	
	defaultLocation.mkdirs();
	String relativePath = new File(".").toURI().relativize(defaultLocation.toURI()).getPath();
	AppConfig.saveDefaultWorldLocation("./" + relativePath);
	
	App.worldFileUtil = new WorldFileUtil(new File(AppConfig.config.getString(AppConfig.WORLD_LOCATION)));
	
	Backend.start();
}
 
Example 7
Project: phone-simulator   File: TesterHost.java   Source Code and License 6 votes vote down vote up
private void setupLog4j(String appName) {

        // InputStream inStreamLog4j = getClass().getResourceAsStream("/log4j.properties");

        String propFileName = appName + ".log4j.properties";
        File f = new File("./" + propFileName);
        if (f.exists()) {

            try {
                InputStream inStreamLog4j = new FileInputStream(f);
                Properties propertiesLog4j = new Properties();

                propertiesLog4j.load(inStreamLog4j);
                PropertyConfigurator.configure(propertiesLog4j);
            } catch (Exception e) {
                e.printStackTrace();
                BasicConfigurator.configure();
            }
        } else {
            BasicConfigurator.configure();
        }

        // logger.setLevel(Level.TRACE);
        logger.debug("log4j configured");

    }
 
Example 8
Project: incubator-servicecomb-java-chassis   File: Log4jUtils.java   Source Code and License 6 votes vote down vote up
public static void init(List<String> locationPatterns) throws Exception {
  if (inited) {
    return;
  }

  synchronized (LOCK) {
    if (inited) {
      return;
    }

    PropertiesLoader loader = new PropertiesLoader(locationPatterns);
    Properties properties = loader.load();
    if (properties.isEmpty()) {
      throw new Exception("can not find resource " + locationPatterns);
    }

    PropertyConfigurator.configure(properties);
    inited = true;

    // 如果最高优先级的文件是在磁盘上,且有写权限,则将merge的结果输出到该目录,方便维护时观察生效的参数
    outputFile(loader.getFoundResList(), properties);
  }
}
 
Example 9
Project: CrawlerSYS   File: CrawlerServlet.java   Source Code and License 6 votes vote down vote up
/**
 * Initialization of the servlet. <br>
 *
 * @throws ServletException if an error occurs
 */
public void init() throws ServletException {
	String file = this.getServletContext().getRealPath(this.getInitParameter("log4j"));
	//从web.xml配置读取,名字一定要和web.xml配置一致
	  if(file != null){
	     PropertyConfigurator.configure(file);
	  }
	// Put your code here
	new CrawlerServer(DefaultConfig.serverPort).start();
	try {
		new WebSocket(DefaultConfig.socketPort).start();
	} catch (UnknownHostException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 10
Project: TakinRPC   File: RPCServer.java   Source Code and License 6 votes vote down vote up
private void initConf() {
    try {
        String logpath = context.getConfigPath() + File.separator + "log4j.properties";
        PropertyConfigurator.configure(logpath);
        logger.info(String.format("log4j path:%s", logpath));

        String serverpath = context.getConfigPath() + File.separator + "server.properties";
        NettyServerConfig config = GuiceDI.getInstance(NettyServerConfig.class);
        PropertiesHelper pro = new PropertiesHelper(serverpath);
        config.setSelectorThreads(pro.getInt("selectorThreads"));
        config.setWorkerThreads(pro.getInt("workerThreads"));
        config.setListenPort(pro.getInt("server.Port"));
        config.setUsezk(pro.getBoolean("use.zk"));
        config.setZkhosts(pro.getString("zk.hosts"));

        logger.info(JSON.toJSONString(config));

    } catch (Exception e) {
        logger.error("", e);
    }
}
 
Example 11
Project: TakinRPC   File: Test2.java   Source Code and License 6 votes vote down vote up
public static void main(String... args) throws Exception {
    PropertyConfigurator.configure("D:/log4j.properties");

    try {
        List<Replica> members = Lists.newArrayList();
        members.add(Replica.fromString("localhost:10000"));
        members.add(Replica.fromString("localhost:10002"));
        File logDir = new File("D:/raft1");
        logDir.mkdir();

        // configure the service
        RaftService raft = RaftService.newBuilder().local(Replica.fromString("localhost:10001")).members(members).logDir(logDir).timeout(300).build(new Test2());

        // start this replica
        raft.startAsync().awaitRunning();

    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 12
Project: TakinRPC   File: Test3.java   Source Code and License 6 votes vote down vote up
public static void main(String... args) throws Exception {
    PropertyConfigurator.configure("D:/log4j.properties");

    try {
        List<Replica> members = Lists.newArrayList();
        members.add(Replica.fromString("localhost:10000"));
        members.add(Replica.fromString("localhost:10001"));
        File logDir = new File("D:/raft2");
        logDir.mkdir();

        // configure the service
        RaftService raft = RaftService.newBuilder().local(Replica.fromString("localhost:10002")).members(members).logDir(logDir).timeout(300).build(new Test3());

        // start this replica
        raft.startAsync().awaitRunning();

        // let's commit some things
        //            for (int i = 0; i < 10; i++) {
        //                raft.commit(new byte[] { 'O', '_', 'o' });
        //            }
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 13
Project: TakinRPC   File: Test.java   Source Code and License 6 votes vote down vote up
public static void main(String... args) throws Exception {
    PropertyConfigurator.configure("D:/log4j.properties");

    try {
        List<Replica> members = Lists.newArrayList();
        members.add(Replica.fromString("localhost:10001"));
        members.add(Replica.fromString("localhost:10002"));
        File logDir = new File("D:/raft");
        logDir.mkdir();

        // configure the service
        RaftService raft = RaftService.newBuilder().local(Replica.fromString("localhost:10000")).members(members).logDir(logDir).timeout(300).build(new Test());

        // start this replica
        Service guavaservice = raft.startAsync();
        guavaservice.awaitRunning();

        // let's commit some things
        //            for (int i = 0; i < 10; i++) {
        //                raft.commit(new byte[] { 'O', '_', 'o' });
        //            }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: TakinRPC   File: ClientTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    try {
        RateLimiter limit = RateLimiter.create(100d);
        PropertyConfigurator.configure("conf/log4j.properties");
        while (true) {
            if (limit.tryAcquire()) {
                final HelloCommand command = new HelloCommand();
                //            System.out.println("result: " + command.execute());
                //            System.out.println("");

                Future<String> future = command.queue();
                System.out.println("result: " + future.get());
                System.out.println("");
            }
        }

        //            Observable<String> observe = command.observe();
        //            observe.asObservable().subscribe((result) -> {
        //                System.out.println(result);
        //            });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 15
Project: TakinRPC   File: ClientTest.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    try {
        PropertyConfigurator.configure("conf/log4j.properties");
        final Hello hello = ProxyFactory.create(Hello.class, "test", null, null);
        System.out.println("result: " + hello.say("xiaoming"));
        System.out.println("");
        System.out.println("result: " + hello.hi(2));
        System.out.println("");
        //            System.out.println("result: " + hello.hi(2));
        //            System.out.println("");
        //            System.out.println("result: " + hello.hi(2));
        //            System.out.println("");
        //            System.out.println("result: " + hello.hi(2));
        System.out.println("");
        // 
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Project: TakinRPC   File: ClientBeanTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testbean() {
    try {
        PropertyConfigurator.configure("conf/log4j.properties");
        final Hello hello = ProxyFactory.create(Hello.class, "test", null, null);

        User u = new User();
        u.setAge(12);
        u.setName("nana");
        u.setStart(new Date());
        System.out.println("");
        u.setName("lua");
        System.out.println("");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 17
Project: TakinRPC   File: ClientBeanTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testList() {
    try {
        PropertyConfigurator.configure("conf/log4j.properties");
        final Hello hello = ProxyFactory.create(Hello.class, "test", null, null);

        User u = new User();
        u.setAge(12);
        u.setName("nana");
        u.setStart(new Date());
        System.out.println("result: " + hello.getall(u));
        System.out.println("");
        u.setName("lua");
        System.out.println("result: " + hello.getall(u));
        System.out.println("");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 18
Project: hadoop-oss   File: KMSWebApp.java   Source Code and License 6 votes vote down vote up
private void initLogging(String confDir) {
  if (System.getProperty("log4j.configuration") == null) {
    System.setProperty("log4j.defaultInitOverride", "true");
    boolean fromClasspath = true;
    File log4jConf = new File(confDir, LOG4J_PROPERTIES).getAbsoluteFile();
    if (log4jConf.exists()) {
      PropertyConfigurator.configureAndWatch(log4jConf.getPath(), 1000);
      fromClasspath = false;
    } else {
      ClassLoader cl = Thread.currentThread().getContextClassLoader();
      URL log4jUrl = cl.getResource(LOG4J_PROPERTIES);
      if (log4jUrl != null) {
        PropertyConfigurator.configure(log4jUrl);
      }
    }
    LOG = LoggerFactory.getLogger(KMSWebApp.class);
    LOG.debug("KMS log starting");
    if (fromClasspath) {
      LOG.warn("Log4j configuration file '{}' not found", LOG4J_PROPERTIES);
      LOG.warn("Logging with INFO level to standard output");
    }
  } else {
    LOG = LoggerFactory.getLogger(KMSWebApp.class);
  }
}
 
Example 19
Project: OftenPorter   File: PortMethodTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSort()
{
    PropertyConfigurator.configure(getClass().getResource("/log4j.properties"));
    PortMethod[] methods = {
            PortMethod.POST, PortMethod.GET, PortMethod.PUT, PortMethod.DELETE
    };
    Arrays.sort(methods);

    Assert.assertTrue(Arrays.binarySearch(methods, PortMethod.POST) >= 0);
    Assert.assertTrue(Arrays.binarySearch(methods, PortMethod.GET) >= 0);
    Assert.assertTrue(Arrays.binarySearch(methods, PortMethod.PUT) >= 0);
    Assert.assertTrue(Arrays.binarySearch(methods, PortMethod.DELETE) >= 0);

    Assert.assertTrue(Arrays.binarySearch(methods, PortMethod.OPTIONS) < 0);
    Assert.assertTrue(Arrays.binarySearch(methods, PortMethod.TARCE) < 0);
    Assert.assertTrue(Arrays.binarySearch(methods, PortMethod.HEAD) < 0);


}
 
Example 20
Project: opencron   File: LoggerFactory.java   Source Code and License 6 votes vote down vote up
public static Logger getLogger(@SuppressWarnings("rawtypes") Class clazz) {

        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        URL url = loader.getResource("log4j.properties");
        String path;
        if (url==null) {
            String currPath = LoggerFactory.class.getProtectionDomain().getCodeSource().getLocation().getFile();
            File file = new File(currPath);
            path = file.getParentFile().getParentFile() + "/conf/log4j.properties";
            if (!new File(path).exists()) {
                throw new ExceptionInInitializerError("[opencron] error: can not found log4j.properties...");
            }
        }else {
            path = url.getPath();
        }
        PropertyConfigurator.configure(path);
        return org.slf4j.LoggerFactory.getLogger(clazz);
    }
 
Example 21
Project: oscm-app   File: Initializer.java   Source Code and License 6 votes vote down vote up
/**
 * On change event
 */
void handleOnChange(File logFile) {
    try {
        long lastModif = logFile.lastModified();
        if (lastModif > logFileLastModified) {
            logFileLastModified = lastModif;
            logger.debug("Reload log4j configuration from "
                    + logFile.getAbsolutePath());
            new PropertyConfigurator().doConfigure(
                    logFile.getAbsolutePath(),
                    LogManager.getLoggerRepository());
            logFileWarning = false;
        }
    } catch (Exception e) {
        if (!logFileWarning) {
            logFileWarning = true;
            logger.error(logFile.getAbsolutePath(), e);
        }
    }
}
 
Example 22
Project: log4j-aws-appenders   File: KinesisAppenderIntegrationTest.java   Source Code and License 6 votes vote down vote up
/**
 *  Loads the test-specific Log4J configuration and resets the environment.
 */
public void setUp(String propertiesName, String streamName) throws Exception
{
    URL config = ClassLoader.getSystemResource(propertiesName);
    assertNotNull("missing configuration: " + propertiesName, config);

    LogManager.resetConfiguration();
    PropertyConfigurator.configure(config);

    localLogger = Logger.getLogger(getClass());

    localClient = AmazonKinesisClientBuilder.defaultClient();

    deleteStreamIfExists(streamName);
}
 
Example 23
Project: oscm   File: Initializer.java   Source Code and License 6 votes vote down vote up
/**
 * On change event
 */
void handleOnChange(File logFile) {
	try {
		long lastModif = logFile.lastModified();
		if (lastModif > logFileLastModified) {
			logFileLastModified = lastModif;
			LOGGER.debug("Reload log4j configuration from " + logFile.getAbsolutePath());
			new PropertyConfigurator().doConfigure(logFile.getAbsolutePath(), LogManager.getLoggerRepository());
			logFileWarning = false;
		}
	} catch (Exception e) {
		if (!logFileWarning) {
			logFileWarning = true;
			LOGGER.error(logFile.getAbsolutePath(), e);
		}
	}
}
 
Example 24
Project: oscm   File: Initializer.java   Source Code and License 6 votes vote down vote up
/**
 * On change event
 */
void handleOnChange(File logFile) {
    try {
        long lastModif = logFile.lastModified();
        if (lastModif > logFileLastModified) {
            logFileLastModified = lastModif;
            LOGGER.debug("Reload log4j configuration from "
                    + logFile.getAbsolutePath());
            new PropertyConfigurator().doConfigure(
                    logFile.getAbsolutePath(),
                    LogManager.getLoggerRepository());
            logFileWarning = false;
        }
    } catch (Exception e) {
        if (!logFileWarning) {
            logFileWarning = true;
            LOGGER.error(logFile.getAbsolutePath(), e);
        }
    }
}
 
Example 25
Project: JInsight   File: Log4JInstrumentationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testLoggerReconfiguration() throws Exception {
  logger.setLevel(Level.ERROR);

  Map<String, Long> expectedCounts = getCurrentCounts();
  expectedCounts.compute("total", (s, aLong) -> aLong + 1);
  expectedCounts.compute("error", (s, aLong) -> aLong + 1);

  Properties properties = new Properties();
  properties.setProperty("log4j.rootCategory", "INFO,TestLog");
  properties.setProperty("log4j.appender.TestLog", "org.apache.log4j.ConsoleAppender");
  properties.setProperty("log4j.appender.TestLog.layout", "org.apache.log4j.PatternLayout");
  PropertyConfigurator.configure(properties);

  logger.error("error!");
  assertEquals(expectedCounts, getCurrentCounts());

}
 
Example 26
Project: ibench   File: iBenchDriver.java   Source Code and License 6 votes vote down vote up
private static void setUpExperimentalLogger(File pathF) throws IOException {
	
	Logger.getRootLogger().removeAllAppenders();
	log.removeAllAppenders();
	
	PropertyConfigurator.configure("resource/log4jproperties.txt");
	
	FileAppender resultAppender = new FileAppender(
			new PatternLayout("%m"),
			new File(pathF, "result.txt").toString(), false);
	
	LevelRangeFilter infoFilter = new LevelRangeFilter();
	infoFilter.setLevelMin(Level.INFO);
	infoFilter.setLevelMax(Level.FATAL);
	infoFilter.setAcceptOnMatch(true);
	resultAppender.addFilter(infoFilter);
	log.addAppender(resultAppender);
	Logger.getLogger(iBench.class).addAppender(resultAppender);
	
}
 
Example 27
Project: ibench   File: iBenchDriver.java   Source Code and License 6 votes vote down vote up
private static void setUpConfigLogger(File pathF, String configName) throws IOException {
	Logger.getRootLogger().removeAllAppenders();
	
	String nameSuffix = configName.replace(".txt", "");
	
	PropertyConfigurator.configure("resource/log4jproperties.txt");	
	
	FileAppender logFileAppender = new FileAppender(
			new PatternLayout("%-4r [%t] %-5p %c %x - %m%n"),
			new File(pathF, "log_" + nameSuffix + ".txt").toString(), false);
	Logger.getRootLogger().addAppender(logFileAppender);
	
	if (opt.logToConsole)
		Logger.getRootLogger().addAppender(new ConsoleAppender(
				new PatternLayout("%-4r [%t] %-5p %c %x - %m%n")));
}
 
Example 28
Project: flume-release-1.7.0   File: TestLog4jAppender.java   Source Code and License 6 votes vote down vote up
@Test
public void testLog4jAppender() throws IOException {
  configureSource();
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  for (int count = 0; count <= 1000; count++) {
    /*
     * Log4j internally defines levels as multiples of 10000. So if we
     * create levels directly using count, the level will be set as the
     * default.
     */
    int level = ((count % 5) + 1) * 10000;
    String msg = "This is log message number" + String.valueOf(count);

    logger.log(Level.toLevel(level), msg);
    Transaction transaction = ch.getTransaction();
    transaction.begin();
    Event event = ch.take();
    Assert.assertNotNull(event);
    Assert.assertEquals(new String(event.getBody(), "UTF8"), msg);

    Map<String, String> hdrs = event.getHeaders();

    Assert.assertNotNull(hdrs.get(Log4jAvroHeaders.TIMESTAMP.toString()));

    Assert.assertEquals(Level.toLevel(level),
        Level.toLevel(Integer.valueOf(hdrs.get(Log4jAvroHeaders.LOG_LEVEL
            .toString()))
        ));

    Assert.assertEquals(logger.getName(),
        hdrs.get(Log4jAvroHeaders.LOGGER_NAME.toString()));

    Assert.assertEquals("UTF8",
        hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));
    transaction.commit();
    transaction.close();
  }

}
 
Example 29
Project: flume-release-1.7.0   File: TestLog4jAppender.java   Source Code and License 6 votes vote down vote up
@Test
public void testLayout() throws IOException {
  configureSource();
  props.put("log4j.appender.out2.layout", "org.apache.log4j.PatternLayout");
  props.put("log4j.appender.out2.layout.ConversionPattern",
      "%-5p [%t]: %m%n");
  PropertyConfigurator.configure(props);
  Logger logger = LogManager.getLogger(TestLog4jAppender.class);
  Thread.currentThread().setName("Log4jAppenderTest");
  for (int count = 0; count <= 100; count++) {
    /*
     * Log4j internally defines levels as multiples of 10000. So if we
     * create levels directly using count, the level will be set as the
     * default.
     */
    int level = ((count % 5) + 1) * 10000;
    String msg = "This is log message number" + String.valueOf(count);

    logger.log(Level.toLevel(level), msg);
    Transaction transaction = ch.getTransaction();
    transaction.begin();
    Event event = ch.take();
    Assert.assertNotNull(event);
    StringBuilder builder = new StringBuilder();
    builder.append("[").append("Log4jAppenderTest").append("]: ")
        .append(msg);
    //INFO seems to insert an extra space, so lets split the string.
    String eventBody = new String(event.getBody(), "UTF-8");
    String eventLevel = eventBody.split("\\s+")[0];
    Assert.assertEquals(Level.toLevel(level).toString(), eventLevel);
    Assert.assertEquals(
        new String(event.getBody(), "UTF8").trim()
            .substring(eventLevel.length()).trim(), builder.toString());

    Map<String, String> hdrs = event.getHeaders();

    Assert.assertNotNull(hdrs.get(Log4jAvroHeaders.TIMESTAMP.toString()));

    Assert.assertEquals(Level.toLevel(level),
        Level.toLevel(Integer.parseInt(hdrs.get(Log4jAvroHeaders.LOG_LEVEL
            .toString()))));

    Assert.assertEquals(logger.getName(),
        hdrs.get(Log4jAvroHeaders.LOGGER_NAME.toString()));

    Assert.assertEquals("UTF8",
        hdrs.get(Log4jAvroHeaders.MESSAGE_ENCODING.toString()));
    transaction.commit();
    transaction.close();
  }


}
 
Example 30
Project: CrypDist   File: Property.java   Source Code and License 6 votes vote down vote up
public Property() {

        PropertyConfigurator.configure(this.getClass().getResourceAsStream("log4j_custom.properties"));
        Logger l1 = Logger.getLogger("P2P");
        Appender a = new CustomAppender();
        l1.addAppender(a);

        l1 = Logger.getLogger("BlockchainManager");
        l1.addAppender(a);

        l1 = Logger.getLogger("DbManager");
        l1.addAppender(a);

        l1 = Logger.getLogger("CrypDist");
        l1.addAppender(a);

        try {
            Config.PRIVATE_KEY = new String((IOUtils.toByteArray(getClass().getResourceAsStream("private.pem"))) );

        } catch (Exception e) {

        }
    }
 
Example 31
Project: unitimes   File: OnlineSectioningTestFwk.java   Source Code and License 6 votes vote down vote up
protected void configureLogging() {
       Properties props = new Properties();
       props.setProperty("log4j.rootLogger", "DEBUG, A1");
       props.setProperty("log4j.appender.A1", "org.apache.log4j.ConsoleAppender");
       props.setProperty("log4j.appender.A1.layout", "org.apache.log4j.PatternLayout");
       props.setProperty("log4j.appender.A1.layout.ConversionPattern","%-5p %c{2}: %m%n");
       props.setProperty("log4j.logger.org.hibernate","INFO");
       props.setProperty("log4j.logger.org.hibernate.cfg","WARN");
       props.setProperty("log4j.logger.org.hibernate.cache.EhCacheProvider","ERROR");
       props.setProperty("log4j.logger.org.unitime.commons.hibernate","INFO");
       props.setProperty("log4j.logger.net","INFO");
       props.setProperty("log4j.logger.org.unitime.timetable.onlinesectioning","WARN");
       props.setProperty("log4j.logger.org.unitime.timetable.onlinesectioning.test","INFO");
       props.setProperty("log4j.logger." + OnlineSectioningTestFwk.class.getName(), "INFO");
       props.setProperty("log4j.logger.org.cpsolver.ifs.util.JProf", "INFO");
       props.setProperty("log4j.logger.org.jgroups", "INFO");
       props.setProperty("log4j.logger.net.sf.ehcache.distribution.jgroups", "WARN");
       props.setProperty("log4j.logger.org.hibernate.cache.ehcache.AbstractEhcacheRegionFactory", "ERROR");
       props.setProperty("log4j.logger.net.sf.ehcache.distribution.jgroups.JGroupsCacheReceiver", "ERROR");
       props.setProperty("log4j.logger.org.unitime.timetable.solver.jgroups.DummySolverServer", "INFO");
       PropertyConfigurator.configure(props);
}
 
Example 32
Project: unitimes   File: SolverServerImplementation.java   Source Code and License 6 votes vote down vote up
private static void configureLogging(Properties properties) {
       PropertyConfigurator.configure(properties);
       
       Logger log = Logger.getRootLogger();
       log.info("-----------------------------------------------------------------------");
       log.info("UniTime Log File");
       log.info("");
       log.info("Created: " + new Date());
       log.info("");
       log.info("System info:");
       log.info("System:      " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch"));
       log.info("CPU:         " + System.getProperty("sun.cpu.isalist") + " endian:" + System.getProperty("sun.cpu.endian") + " encoding:" + System.getProperty("sun.io.unicode.encoding"));
       log.info("Java:        " + System.getProperty("java.vendor") + ", " + System.getProperty("java.runtime.name") + " " + System.getProperty("java.runtime.version", System.getProperty("java.version")));
       log.info("User:        " + System.getProperty("user.name"));
       log.info("Timezone:    " + System.getProperty("user.timezone"));
       log.info("Working dir: " + System.getProperty("user.dir"));
       log.info("Classpath:   " + System.getProperty("java.class.path"));
       log.info("Memory:      " + (Runtime.getRuntime().maxMemory() / 1024 / 1024) + " MB");
       log.info("Cores:       " + Runtime.getRuntime().availableProcessors());
       log.info("");
}
 
Example 33
Project: hadoop   File: KMSWebApp.java   Source Code and License 6 votes vote down vote up
private void initLogging(String confDir) {
  if (System.getProperty("log4j.configuration") == null) {
    System.setProperty("log4j.defaultInitOverride", "true");
    boolean fromClasspath = true;
    File log4jConf = new File(confDir, LOG4J_PROPERTIES).getAbsoluteFile();
    if (log4jConf.exists()) {
      PropertyConfigurator.configureAndWatch(log4jConf.getPath(), 1000);
      fromClasspath = false;
    } else {
      ClassLoader cl = Thread.currentThread().getContextClassLoader();
      URL log4jUrl = cl.getResource(LOG4J_PROPERTIES);
      if (log4jUrl != null) {
        PropertyConfigurator.configure(log4jUrl);
      }
    }
    LOG = LoggerFactory.getLogger(KMSWebApp.class);
    LOG.debug("KMS log starting");
    if (fromClasspath) {
      LOG.warn("Log4j configuration file '{}' not found", LOG4J_PROPERTIES);
      LOG.warn("Logging with INFO level to standard output");
    }
  } else {
    LOG = LoggerFactory.getLogger(KMSWebApp.class);
  }
}
 
Example 34
Project: linked_data_authorities   File: Loader.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws IOException {
PropertyConfigurator.configure("log4j.info");
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
FileOutputStream out = new FileOutputStream(new File("/usr/local/RAID/geonames.nt"));
String buffer = null;
int count = 0;

while ((buffer = reader.readLine()) != null) {
    if (++count % 2 == 0) {
	logger.debug("processing xml: " + buffer);
	Model model = ModelFactory.createDefaultModel() ;
	model.read(new StringReader(buffer), null, "RDF/XML");
	model.write(out, "N-TRIPLE");
    } else {
	logger.info("skipping: " + buffer);
    }
}
reader.close();
   }
 
Example 35
Project: strictfp-back-end   File: MainServer.java   Source Code and License 6 votes vote down vote up
public static void main(@NotNull @NonNls String[] args) throws Exception {
	PropertyConfigurator.configure(System.getProperty("user.dir") + "/log4j.properties");
	logger.warn("StrictFP | Back-end");
	logger.info("StrictFP Back-end is now running...");
	Server server = new Server(Constant.SERVER.SERVER_PORT);
	ServletContextHandler context =
			new ServletContextHandler(ServletContextHandler.SESSIONS);
	context.setContextPath("/api/v0");
	server.setHandler(context);
	server.setStopAtShutdown(true);
	// 像下面这行一样
	context.addServlet(new ServletHolder(new GetQuiz()), "/misc/getquiz");
	context.addServlet(new ServletHolder(new TimeLine()), "/timeline");
	context.addServlet(new ServletHolder(new Counter()), "/misc/counter");
	context.addServlet(new ServletHolder(new User()), "/user");
	context.addServlet(new ServletHolder(new Heartbeat()), "/misc/heartbeat");
	context.addServlet(new ServletHolder(new SafeCheck()), "/misc/safecheck");
	context.addServlet(new ServletHolder(new CheckCert()), "/auth/check_cert");
	//
	server.start();
	server.join();
}
 
Example 36
Project: fwm   File: App.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {		
	// PRODUCTION mode needs to be determined before we get here... 
	AppConfig.firstInit();
	prod = AppConfig.getProd();
	appFileUtil = new AppFileUtil();
	if(!appFileUtil.success()){
		System.err.println(appFileUtil.getErrorMessage());
		Platform.runLater(new Runnable(){
			public void run(){
				Alert al = new Alert(AlertType.ERROR);
				al.setResizable(true);
				for(Node n : al.getDialogPane().getChildren()){
					if(n instanceof Label){
						((Label)n).setMinHeight(Region.USE_PREF_SIZE);
					}
				}
				al.setContentText(appFileUtil.getErrorMessage());
				al.setHeaderText("FWM Startup Error");
				al.showAndWait();
				System.exit(-1);
			}
		});
		return;
	}
	// ignore everything else because this means that we're in a jar file, so the app won't work
	// if it doesn't think that we're prod. 
	PropertyConfigurator.configure(appFileUtil.getLog4JFile().getAbsolutePath());
	AppConfig.init();
	HotkeyController.init();
	log.debug("Currently prod? "  + prod);
	log.debug(retGlobalResource("/src/main/webapp/WEB-INF/images/FWM-icon.png").getFile());
	launch(args);
}
 
Example 37
Project: improved-journey   File: FileTailerSource.java   Source Code and License 5 votes vote down vote up
public void configure(Context context) {
		batchUpperLimit = context.getInteger("batchUpperLimit",1);
		PropertyConfigurator.configure(PropertyUtil.getCurrentConfPath() + "log4j.properties");
		log.info(PropertyUtil.getCurrentConfPath() + "log4j.properties");
		prop.put("fileRootDir", context.getString("fileRootDir",""));
		//批量提交Event个数
		prop.put("batchUpperLimit", context.getString("batchUpperLimit","1"));
		//获取快照文件存放根目录
		prop.put("backupFileDirPath", context.getString("backupFileDirPath", ""));
//		// 目录文件组合方式 0:文件log4j滚动、1:文件非log4j滚动
//		// 2:日期目录+文件log4j滚动 3:日期目录+文件非log4j滚动
//		prop.put("rollType", context.getString("rollType",""));
		// 日期目录
//		prop.put("dateDir", context.getString("dateDir",""));
		// 文件前缀(实时文件名前缀)
		prop.put("filePrefix", context.getString("filePrefix",""));
		// 文件后缀
		prop.put("fileSuffix", context.getString("fileSuffix",""));
		// 文件字符集
		prop.put("charset", context.getString("charset", "UTF-8"));
		// 文件字符集
		prop.put("bufferSize", context.getString("bufferSize", "4096"));
		//设置正则表达式匹配的文件名
		prop.put("regexFileName", context.getString("regexFileName", ".*"));
		
		prop.put("clearTimeInterval", context.getString("clearTimeInterval", "3600000"));
		
	}
 
Example 38
Project: SigFW   File: DiameterServer.java   Source Code and License 5 votes vote down vote up
private static void configLog4j() {
	InputStream inStreamLog4j = DiameterServer.class.getClassLoader().getResourceAsStream("log4j.properties");
	Properties propertiesLog4j = new Properties();
	try {
		propertiesLog4j.load(inStreamLog4j);
		PropertyConfigurator.configure(propertiesLog4j);
	} catch (Exception e) {
		e.printStackTrace();
	}

	log.debug("log4j configured");

}
 
Example 39
Project: SigFW   File: DiameterFirewall.java   Source Code and License 5 votes vote down vote up
private static void configLog4j() {
    InputStream inStreamLog4j = DiameterFirewall.class.getClassLoader().getResourceAsStream("log4j.properties");
    Properties propertiesLog4j = new Properties();
    try {
        propertiesLog4j.load(inStreamLog4j);
        PropertyConfigurator.configure(propertiesLog4j);
    } catch (Exception e) {
        e.printStackTrace();
    }

    logger.debug("log4j configured");

}
 
Example 40
Project: SigFW   File: AbstractSctpBase.java   Source Code and License 5 votes vote down vote up
public void init() {
    try {
        Properties tckProperties = new Properties();

        InputStream inStreamLog4j = AbstractSctpBase.class.getResourceAsStream("/log4j.properties");

        System.out.println("Input Stream = " + inStreamLog4j);

        Properties propertiesLog4j = new Properties();
        try {
            propertiesLog4j.load(inStreamLog4j);
            PropertyConfigurator.configure(propertiesLog4j);
        } catch (IOException e) {
            e.printStackTrace();
            BasicConfigurator.configure();
        }

        logger.debug("log4j configured");

        String lf = System.getProperties().getProperty(LOG_FILE_NAME);
        if (lf != null) {
            logFileName = lf;
        }

        // If already created a print writer then just use it.
        try {
            logger.addAppender(new FileAppender(new SimpleLayout(), logFileName));
        } catch (FileNotFoundException fnfe) {

        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }

}