Java Code Examples for org.apache.log4j.LogManager#resetConfiguration()

The following examples show how to use org.apache.log4j.LogManager#resetConfiguration() . 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: DatabaseTaskBase.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the logging.
 */
private void initLogging()
{
    if (_simpleLogging)
    {
        // For Ant, we're forcing DdlUtils to do logging via log4j to the console
        Properties props = new Properties();
        String     level = (_verbosity == null ? Level.INFO.toString() : _verbosity.getValue()).toUpperCase();

        props.setProperty("log4j.rootCategory", level + ",A");
        props.setProperty("log4j.appender.A", "org.apache.log4j.ConsoleAppender");
        props.setProperty("log4j.appender.A.layout", "org.apache.log4j.PatternLayout");
        props.setProperty("log4j.appender.A.layout.ConversionPattern", "%m%n");
        // we don't want debug logging from Digester
        props.setProperty("log4j.logger.org.apache.commons", "WARN");

        LogManager.resetConfiguration();
        PropertyConfigurator.configure(props);
    }
    _log = LogFactory.getLog(getClass());
}
 
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: Server.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes Log4j logging.
 *
 * @throws ServerException thrown if Log4j could not be initialized.
 */
protected void initLog() throws ServerException {
  verifyDir(logDir);
  LogManager.resetConfiguration();
  File log4jFile = new File(configDir, name + "-log4j.properties");
  if (log4jFile.exists()) {
    PropertyConfigurator.configureAndWatch(log4jFile.toString(), 10 * 1000); //every 10 secs
    log = LoggerFactory.getLogger(Server.class);
  } else {
    Properties props = new Properties();
    try {
      InputStream is = getResource(DEFAULT_LOG4J_PROPERTIES);
      try {
        props.load(is);
      } finally {
        is.close();
      }
    } catch (IOException ex) {
      throw new ServerException(ServerException.ERROR.S03, DEFAULT_LOG4J_PROPERTIES, ex.getMessage(), ex);
    }
    PropertyConfigurator.configure(props);
    log = LoggerFactory.getLogger(Server.class);
    log.warn("Log4j [{}] configuration file not found, using default configuration from classpath", log4jFile);
  }
}
 
Example 4
Source File: LoggingUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void initLog4J(PropertyHandler propertyHandler) {
	LOG.info("****************  Init LOG4J");

	if (propertyHandler != null) {
		Path path = Paths.get(propertyHandler.getProperty("LOG4J", "log4j.xml"));
		if (Files.exists(path)) {
				LogManager.resetConfiguration();
				DOMConfigurator.configure(path.toAbsolutePath().toString());
				LOG.info("Loading log4j config from " + path.toAbsolutePath().toString());
		}
	}
}
 
Example 5
Source File: ManagementMBeanImpl.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public void refreshConfiguration() {
    try {
        // reloading permissions
        Policy.getPolicy().refresh();

        // reloading log4j configuration
        String configFilename = System.getProperty("log4j.configuration");
        if (configFilename != null) {
            LogManager.resetConfiguration();
            PropertyConfigurator.configure(new URL(configFilename));
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: LoggingConfigure.java    From Pistachio with Apache License 2.0 5 votes vote down vote up
@Override
public void resetConfiguration() {
    ClassLoader cl = getClass().getClassLoader();
    LogManager.resetConfiguration();
    URL log4jprops = cl.getResource("log4j.properties");
    if (log4jprops != null) {
        PropertyConfigurator.configure(log4jprops);
    }
}
 
Example 7
Source File: HasNextVsHasNextLineDemo.java    From tutorials with MIT License 5 votes vote down vote up
private static void setLogger() throws IOException {
    InputStream is = HasNextVsHasNextLineDemo.class.getResourceAsStream("/scanner/log4j.properties");
    Properties props = new Properties();
    props.load(is);
    LogManager.resetConfiguration();
    PropertyConfigurator.configure(props);
}
 
Example 8
Source File: AdminServiceRestImpl.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Override
public Response reload() {
    ApplicationProperties.reload();
    Properties copyToReturn = ApplicationProperties.getProperties();
    configurer.setProperties(copyToReturn);

    filesConfiguration.reload();

    LogManager.resetConfiguration();
    DOMConfigurator.configure("../data/conf/log4j.xml");

    copyToReturn.put("logging-reload-state", "Property reload complete");

    return ResponseBuilder.ok(new TreeMap<>(copyToReturn));
}
 
Example 9
Source File: ManagementMBeanImpl.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public void refreshConfiguration() {
    // reloading permissions
    Policy.getPolicy().refresh();

    // reloading log4j configuration
    String configFilename = System.getProperty("log4j.configuration");
    if (configFilename != null) {
        LogManager.resetConfiguration();
        try {
            PropertyConfigurator.configure(new URL(configFilename));
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example 10
Source File: ERFATestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
   * Reset configuration after test.
   */
public void tearDown() {
    LogManager.resetConfiguration();
}
 
Example 11
Source File: TestKMSAudit.java    From big-c with Apache License 2.0 4 votes vote down vote up
@After
public void cleanUp() {
  System.setErr(originalOut);
  LogManager.resetConfiguration();
  kmsAudit.shutdown();
}
 
Example 12
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 13
Source File: ClientSharedUtils.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static void initLog4J(String logFile,
    Level level) throws IOException {
  // set the log file location
  Properties props = new Properties();
  InputStream in = ClientSharedUtils.class.getResourceAsStream(
      "/store-log4j.properties");
  try {
    props.load(in);
  } finally {
    in.close();
  }

  // override file location and level
  if (level != null) {
    String levelStr = "INFO";
    // convert to log4j level
    if (level == Level.SEVERE) {
      levelStr = "ERROR";
    } else if (level == Level.WARNING) {
      levelStr = "WARN";
    } else if (level == Level.INFO || level == Level.CONFIG) {
      levelStr = "INFO";
    } else if (level == Level.FINE || level == Level.FINER ||
        level == Level.FINEST) {
      levelStr = "TRACE";
    } else if (level == Level.ALL) {
      levelStr = "DEBUG";
    } else if (level == Level.OFF) {
      levelStr = "OFF";
    }
    if (logFile != null) {
      props.setProperty("log4j.rootCategory", levelStr + ", file");
    } else {
      props.setProperty("log4j.rootCategory", levelStr + ", console");
    }
  }
  if (logFile != null) {
    props.setProperty("log4j.appender.file.file", logFile);
  }
  // lastly override with any user provided properties file
  in = ClientSharedUtils.class.getResourceAsStream("/log4j.properties");
  if (in != null) {
    Properties setProps = new Properties();
    try {
      setProps.load(in);
    } finally {
      in.close();
    }
    props.putAll(setProps);
  }
  LogManager.resetConfiguration();
  PropertyConfigurator.configure(props);
}
 
Example 14
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 15
Source File: ProxyHostTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@BeforeMethod(groups = { "simple"})
public void beforeMethod() {
    LogManager.resetConfiguration();
    PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties"));
}
 
Example 16
Source File: LogLevelTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT)
public void afterClass() {
    LogManager.resetConfiguration();
    PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties"));
}
 
Example 17
Source File: ClientSharedUtils.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static void initLog4J(String logFile,
    Level level) throws IOException {
  // set the log file location
  Properties props = new Properties();
  InputStream in = ClientSharedUtils.class.getResourceAsStream(
      "/store-log4j.properties");
  try {
    props.load(in);
  } finally {
    in.close();
  }

  // override file location and level
  if (level != null) {
    String levelStr = "INFO";
    // convert to log4j level
    if (level == Level.SEVERE) {
      levelStr = "ERROR";
    } else if (level == Level.WARNING) {
      levelStr = "WARN";
    } else if (level == Level.INFO || level == Level.CONFIG) {
      levelStr = "INFO";
    } else if (level == Level.FINE || level == Level.FINER ||
        level == Level.FINEST) {
      levelStr = "TRACE";
    } else if (level == Level.ALL) {
      levelStr = "DEBUG";
    } else if (level == Level.OFF) {
      levelStr = "OFF";
    }
    if (logFile != null) {
      props.setProperty("log4j.rootCategory", levelStr + ", file");
    } else {
      props.setProperty("log4j.rootCategory", levelStr + ", console");
    }
  }
  if (logFile != null) {
    props.setProperty("log4j.appender.file.file", logFile);
  }
  // lastly override with any user provided properties file
  in = ClientSharedUtils.class.getResourceAsStream("/log4j.properties");
  if (in != null) {
    Properties setProps = new Properties();
    try {
      setProps.load(in);
    } finally {
      in.close();
    }
    props.putAll(setProps);
  }
  LogManager.resetConfiguration();
  PropertyConfigurator.configure(props);
}
 
Example 18
Source File: LogLevelTest.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@BeforeMethod(groups = { "simple"})
public void beforeMethod(Method method) {
    LogManager.resetConfiguration();
    PropertyConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.properties"));
}
 
Example 19
Source File: TestKMSAudit.java    From ranger with Apache License 2.0 4 votes vote down vote up
@After
public void cleanUp() {
  System.setErr(originalOut);
  LogManager.resetConfiguration();
  kmsAudit.shutdown();
}
 
Example 20
Source File: TestSkewedJoin.java    From spork with Apache License 2.0 4 votes vote down vote up
@Test
public void testNonExistingInputPathInSkewJoin() throws Exception {
    String script =
      "exists = LOAD '" + INPUT_FILE2 + "' AS (a:long, x:chararray);" +
      "missing = LOAD '/non/existing/directory' AS (a:long);" +
      "missing = FOREACH ( GROUP missing BY a ) GENERATE $0 AS a, COUNT_STAR($1);" +
      "joined = JOIN exists BY a, missing BY a USING 'skewed';";

    String logFile = Util.createTempFileDelOnExit("tmp", ".log").getAbsolutePath();
    Logger logger = Logger.getLogger("org.apache.pig");
    logger.setLevel(Level.INFO);
    SimpleLayout layout = new SimpleLayout();
    FileAppender appender = new FileAppender(layout, logFile.toString(), false, false, 0);
    logger.addAppender(appender);
    
    try {
        pigServer.registerScript(new ByteArrayInputStream(script.getBytes("UTF-8")));
        pigServer.openIterator("joined");
    } catch (Exception e) {
        boolean foundInvalidInputException = false;

        // Search through chained exceptions for InvalidInputException. If
        // input splits are calculated on the front-end, we will see this
        // exception in the stack trace.
        Throwable cause = e.getCause();
        while (cause != null) {
            if (cause instanceof InvalidInputException) {
                foundInvalidInputException = true;
                break;
            }
            cause = cause.getCause();
        }

        // InvalidInputException was not found in the stack trace. But it's
        // possible that the exception was thrown in the back-end, and Pig
        // couldn't retrieve it in the front-end. To be safe, search the log
        // file before declaring a failure.
        if (!foundInvalidInputException) {
            FileInputStream fis = new FileInputStream(new File(logFile));
            int bytes = fis.available();
            byte[] buffer = new byte[bytes];
            fis.read(buffer);
            String str = new String(buffer, "UTF-8");
            if (str.contains(InvalidInputException.class.getName())) {
                foundInvalidInputException = true;
            }
            fis.close();
        }

        assertTrue("This exception was not caused by InvalidInputException: " + e,
                foundInvalidInputException);
    } finally {
        LogManager.resetConfiguration();
    }
}