Java Code Examples for org.apache.log4j.PropertyConfigurator#configure()

The following examples show how to use org.apache.log4j.PropertyConfigurator#configure() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ShortSocketServer.java    From cacheonix-core with GNU Lesser General Public License v2.1 7 votes vote down vote up
public 
 static 
 void main(String args[]) throws Exception {
   int totalTests = 0;
   String prefix = null;

   if(args.length == 2) {
     totalTests = Integer.parseInt(args[0]);
     prefix = args[1];
   } else {
     usage("Wrong number of arguments."); 
   }
   

     LogLog.debug("Listening on port " + SocketServerTestCase.PORT);
     ServerSocket serverSocket = new ServerSocket(SocketServerTestCase.PORT);

     MDC.put("hostID", "shortSocketServer");

     for(int i = 1; i <= totalTests; i++) {
PropertyConfigurator.configure(prefix+i+".properties");
LogLog.debug("Waiting to accept a new client.");
Socket socket = serverSocket.accept();
LogLog.debug("Connected to client at " + socket.getInetAddress());
LogLog.debug("Starting new socket node.");	
SocketNode sn = new SocketNode(socket, LogManager.getLoggerRepository());
Thread t = new Thread(sn);
t.start(); 
t.join();
     }
 }
 
Example 2
Source File: Log4jConfigurationHelper.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Update the log4j configuration.
 *
 * @param targetClass the target class used to get the original log4j configuration file as a resource
 * @param log4jPath the custom log4j configuration properties file path
 * @param log4jFileName the custom log4j configuration properties file name
 * @throws IOException if there's something wrong with updating the log4j configuration
 */
public static void updateLog4jConfiguration(Class<?> targetClass, String log4jPath, String log4jFileName)
    throws IOException {
  Closer closer = Closer.create();
  try {
    InputStream fileInputStream = closer.register(new FileInputStream(log4jPath));
    InputStream inputStream = closer.register(targetClass.getResourceAsStream("/" + log4jFileName));
    Properties customProperties = new Properties();
    customProperties.load(fileInputStream);
    Properties originalProperties = new Properties();
    originalProperties.load(inputStream);

    for (Entry<Object, Object> entry : customProperties.entrySet()) {
      originalProperties.setProperty(entry.getKey().toString(), entry.getValue().toString());
    }

    LogManager.resetConfiguration();
    PropertyConfigurator.configure(originalProperties);
  } catch (Throwable t) {
    throw closer.rethrow(t);
  } finally {
    closer.close();
  }
}
 
Example 3
Source File: Log.java    From clust4j with Apache License 2.0 6 votes vote down vote up
private static org.apache.log4j.Logger createLog4jLogger(String logDirParent) {
	synchronized (com.clust4j.log.Log.class) {
		// H2O API is synchronized here... this is not:
		if(null != _logger)
			return _logger;
		
		String l4jprops = System.getProperty("log4j.properties");
		if(null != l4jprops)
			PropertyConfigurator.configure(l4jprops);
		
		else {
			java.util.Properties p = new java.util.Properties();
			setLog4jProperties(logDirParent, p);
			PropertyConfigurator.configure(p);
		}
	}
	
	return _logger = LogManager.getLogger(Log.class.getName());
}
 
Example 4
Source File: LoggerBase.java    From functional-tests-core with Apache License 2.0 5 votes vote down vote up
/**
 * TODO(): Add docs.
 */
public static void initLog4j() {
    String userDir = System.getProperty("user.dir");
    String log4jConfig = userDir + File.separator + "resources" + File.separator + "log" + File.separator + "log4j.properties";

    File logFile = new File(log4jConfig);

    if (!logFile.exists()) {
        Properties props = new Properties();
        try {
            props.load(MobileSetupManager.class.getClass().getResourceAsStream("/log/log4j.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        PropertyConfigurator.configure(props);
    } else {
        PropertyConfigurator.configure(log4jConfig);
    }
    String logLevel;
    LoggerBase log = getLogger("LOG");
    try {
        logLevel = log.getLevel().toString();
    } catch (Exception ex) {
        log.info(ex.getMessage());
    }

    Reporter.setEscapeHtml(false);
    log.info("Log4j initialized.");
}
 
Example 5
Source File: SchemaReader.java    From Touchstone with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
		PropertyConfigurator.configure(".//test//lib//log4j.properties");
		SchemaReader schemaReader = new SchemaReader();
//		schemaReader.read(".//test//input//tpch_schema_sf_1.txt");
//		schemaReader.read(".//test//input//function_test_schema_0.txt");
		
		schemaReader.read(".//test//input//ssb_schema_sf_1_D.txt");
	}
 
Example 6
Source File: MyLoggerTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    When called wihtout arguments, this program will just print 
    <pre>
      DEBUG [main] some.cat - Hello world.
    </pre>
    and exit.
    
    <b>However, it can be called with a configuration file in XML or
    properties format.

  */
 static public void main(String[] args) {
   
   if(args.length == 0) {
     // Note that the appender is added to root but that the log
     // request is made to an instance of MyLogger. The output still
     // goes to System.out.
     Logger root = Logger.getRootLogger();
     Layout layout = new PatternLayout("%p [%t] %c (%F:%L) - %m%n");
     root.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT));
   }
   else if(args.length == 1) {
     if(args[0].endsWith("xml")) {
DOMConfigurator.configure(args[0]);
     } else {
PropertyConfigurator.configure(args[0]);
     }
   } else {
     usage("Incorrect number of parameters.");
   }
   try {
     MyLogger c = (MyLogger) MyLogger.getLogger("some.cat");    
     c.trace("Hello");
     c.debug("Hello");
   } catch(ClassCastException e) {
     LogLog.error("Did you forget to set the factory in the config file?", e);
   }
 }
 
Example 7
Source File: SqoopConfiguration.java    From sqoop-on-spark with Apache License 2.0 5 votes vote down vote up
private synchronized void configureLogging() {
  Properties props = new Properties();
  for (String key : config.keySet()) {
    if (key.startsWith(ConfigurationConstants.PREFIX_LOG_CONFIG)) {
      String logConfigKey = key.substring(
          ConfigurationConstants.PREFIX_GLOBAL_CONFIG.length());
      props.put(logConfigKey, config.get(key));
    }
  }

  PropertyConfigurator.configure(props);
}
 
Example 8
Source File: AdvancedDeviceUtils.java    From ethereumj with MIT License 5 votes vote down vote up
public static void adjustDetailedTracing(long blockNum) {
    // here we can turn on the detail tracing in the middle of the chain
    if (blockNum >= CONFIG.traceStartBlock() && CONFIG.traceStartBlock() != -1) {
        URL configFile = ClassLoader.getSystemResource("log4j-detailed.properties");
        PropertyConfigurator.configure(configFile);
    }
}
 
Example 9
Source File: CacheWatcher.java    From rubix with Apache License 2.0 5 votes vote down vote up
public CacheWatcher(Configuration conf, Path cacheDir, int maxWaitTime) throws IOException
{
  PropertyConfigurator.configure("rubix-client/src/test/resources/log4j.properties");
  log.info("=======  New Watcher  =======");

  this.watcher = FileSystems.getDefault().newWatchService();
  this.maxWaitTime = maxWaitTime;
  this.conf = conf;

  registerAll(cacheDir);
}
 
Example 10
Source File: DataGenerator.java    From Touchstone with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	PropertyConfigurator.configure(".//test//lib//log4j.properties");
	Configurations configurations = new Configurations(".//test//touchstone2.conf");
	// in a JVM, you can only have one data generator
	// because there are some static attributes in class 'DataGenerator'
	for (int i = 0; i < configurations.getDataGeneratorIps().size(); i++) {
		new Thread(new DataGenerator(configurations, i)).start();
	}
}
 
Example 11
Source File: SriSMLowLevelServer.java    From SigPloit with MIT License 5 votes vote down vote up
public void init() {
    try {


        InputStream inStreamLog4j = SriSMLowLevelServer.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);
    }

}
 
Example 12
Source File: Is24CsvWritingExample.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
/**
 * Start the example application.
 *
 * @param args command line arguments
 */
@SuppressWarnings("Duplicates")
public static void main(String[] args) {
    // init logging
    PropertyConfigurator.configure(
            Is24CsvWritingExample.class.getResource(PACKAGE + "/log4j.properties"));

    // create some CSV records
    List<Is24CsvRecord> records = new ArrayList<>();
    records.add(createHausKaufRecord());
    records.add(createHausKaufRecord());
    records.add(createWohnungMieteRecord());
    records.add(createWohnungMieteRecord());

    // write CSV records into a java.io.File
    try {
        write(records, File.createTempFile("output-", ".csv"));
    } catch (IOException ex) {
        LOGGER.error("Can't create temporary file!");
        LOGGER.error("> " + ex.getLocalizedMessage(), ex);
        System.exit(1);
    }

    // write CSV records into a java.io.OutputStream
    write(records, new NullOutputStream());

    // write CSV records into a java.io.Writer
    write(records, new NullWriter());

    // write CSV records into a string and send it to the console
    writeToConsole(records);
}
 
Example 13
Source File: AuditServiceTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() {
  CollectAppender.queue.clear();
  LogManager.shutdown();
  String absolutePath = "target/audit";
  File db = new File( absolutePath + ".db" );
  if( db.exists() ) {
    assertThat( "Failed to delete audit store db file.", db.delete(), is( true ) );
  }
  File lg = new File( absolutePath + ".lg" );
  if( lg.exists() ) {
    assertThat( "Failed to delete audit store lg file.", lg.delete(), is( true ) );
  }
  PropertyConfigurator.configure( ClassLoader.getSystemResourceAsStream( "audit-log4j.properties" ) );
}
 
Example 14
Source File: LevelLogger.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private LevelLogger() {
	File f = new File("res/conf/log4j.properties");
	if (f.exists()) {
		PropertyConfigurator.configure("res/conf/log4j.properties");
	} else {
		BasicConfigurator.configure();
	}
}
 
Example 15
Source File: RMFunctionalTest.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void configureLogging() {
    if (System.getProperty(CentralPAPropertyRepository.LOG4J.getName()) == null) {
        URL defaultLog4jConfig = RMFunctionalTest.class.getResource("/log4j-junit");
        System.setProperty(CentralPAPropertyRepository.LOG4J.getName(), defaultLog4jConfig.toString());
        PropertyConfigurator.configure(defaultLog4jConfig);
    }
}
 
Example 16
Source File: ReplicationWaitCli.java    From hbase-indexer with Apache License 2.0 4 votes vote down vote up
public void run(String[] args) throws Exception {
    LogManager.resetConfiguration();
    PropertyConfigurator.configure(getClass().getResource("log4j.properties"));

    OptionParser parser =  new OptionParser();
    OptionSpec<String> zkOption = parser
            .acceptsAll(Lists.newArrayList("z"), "ZooKeeper connection string, defaults to localhost")
            .withRequiredArg().ofType(String.class)
            .defaultsTo("localhost");
    OptionSpec verboseOption = parser
            .acceptsAll(Lists.newArrayList("verbose"), "Enable debug logging");
    
    OptionSpec<Integer> hbaseMasterPortOption = parser
            .acceptsAll(ImmutableList.of("hbase-master-port"), "HBase Master web ui port number")
            .withRequiredArg().ofType(Integer.class)
            .defaultsTo(60010);

    OptionSet options = null;
    try {
        options = parser.parse(args);
    } catch (OptionException e) {
        System.out.println("This tool does a best effort to wait until replication is done,");
        System.out.println("assuming no external write activity on HBase happens.");
        System.out.println();
        System.out.println("Error parsing command line options:");
        System.out.println(e.getMessage());
        parser.printHelpOn(System.out);
        System.exit(1);
    }

    boolean verbose = options.has(verboseOption);
    if (verbose) {
        Logger.getLogger(getClass().getPackage().getName()).setLevel(Level.DEBUG);
    }

    String zkConnectString = options.valueOf(zkOption);

    System.out.println("Connecting to Zookeeper " + zkConnectString + "...");
    ZooKeeperItf zk = ZkUtil.connect(zkConnectString, 30000);
    waitUntilReplicationDone(zk, options.valueOf(hbaseMasterPortOption));

    Closer.close(zk);
}
 
Example 17
Source File: KnoxCLI.java    From knox with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  PropertyConfigurator.configure( System.getProperty( "log4j.configuration" ) );
  int res = ToolRunner.run(new GatewayConfigImpl(), new KnoxCLI(), args);
  System.exit(res);
}
 
Example 18
Source File: LogConfigurator.java    From maestro-java with Apache License 2.0 4 votes vote down vote up
/**
 * Default log configuration for the daemon
 */
public static void defaultForDaemons() {
    PropertyConfigurator.configure(Constants.MAESTRO_CONFIG_DIR
            + File.separator + "log4j.properties");
}
 
Example 19
Source File: ProxyHostTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@AfterMethod(groups = { "simple" })
public void afterMethod(Method method) {
    LogManager.resetConfiguration();
    PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties"));
}
 
Example 20
Source File: Log4jSocketServer.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param log4JConfigFilename
 */
public static void setLog4JConfigFilename(String log4JConfigFilename) {
    System.out.println("Log4jSocketServer - setLog4JConfigFilename: " + log4JConfigFilename);
    PropertyConfigurator.configure(log4JConfigFilename);
}