/**
  * Instantiate an object given a class name. Check that the <code>className</code> is a subclass
  * of <code>superClass</code>. If that test fails or the object could not be instantiated, then
  * <code>defaultValue</code> is returned.
  *
  * @param className The fully qualified class name of the object to instantiate.
  * @param superClass The class to which the new object should belong.
  * @param defaultValue The object to return in case of non-fulfillment
  */
 public static Object instantiateByClassName(
     String className, Class superClass, Object defaultValue) {
   if (className != null) {
     try {
       Class classObj = Loader.loadClass(className);
       if (!superClass.isAssignableFrom(classObj)) {
         LogLog.error(
             "A \""
                 + className
                 + "\" object is not assignable to a \""
                 + superClass.getName()
                 + "\" variable.");
         LogLog.error("The class \"" + superClass.getName() + "\" was loaded by ");
         LogLog.error("[" + superClass.getClassLoader() + "] whereas object of type ");
         LogLog.error(
             "\"" + classObj.getName() + "\" was loaded by [" + classObj.getClassLoader() + "].");
         return defaultValue;
       }
       return classObj.newInstance();
     } catch (Exception e) {
       LogLog.error("Could not instantiate class [" + className + "].", e);
     }
   }
   return defaultValue;
 }
 @AfterClass
 public static void afterClassResetLogging() {
   // Unfortunately, this code "knows" how log4j was set up in testing
   // Thsi is fragile.
   URL configURL = Loader.getResource("log4j.properties");
   new PropertyConfigurator().doConfigure(configURL, LogManager.getLoggerRepository());
 }
Example #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);
   }
 }
  /**
   * Converts a standard or custom priority level to a Level object.
   *
   * <p>If <code>value</code> is of form "level#classname", then the specified class' toLevel method
   * is called to process the specified level string; if no '#' character is present, then the
   * default {@link org.apache.log4j.Level} class is used to process the level value.
   *
   * <p>As a special case, if the <code>value</code> parameter is equal to the string "NULL", then
   * the value <code>null</code> will be returned.
   *
   * <p>If any error occurs while converting the value to a level, the <code>defaultValue</code>
   * parameter, which may be <code>null</code>, is returned.
   *
   * <p>Case of <code>value</code> is insignificant for the level level, but is significant for the
   * class name part, if present.
   *
   * @since 1.1
   */
  public static Level toLevel(String value, Level defaultValue) {
    if (value == null) return defaultValue;

    value = value.trim();

    int hashIndex = value.indexOf('#');
    if (hashIndex == -1) {
      if ("NULL".equalsIgnoreCase(value)) {
        return null;
      } else {
        // no class name specified : use standard Level class
        return (Level) Level.toLevel(value, defaultValue);
      }
    }

    Level result = defaultValue;

    String clazz = value.substring(hashIndex + 1);
    String levelName = value.substring(0, hashIndex);

    // This is degenerate case but you never know.
    if ("NULL".equalsIgnoreCase(levelName)) {
      return null;
    }

    LogLog.debug("toLevel" + ":class=[" + clazz + "]" + ":pri=[" + levelName + "]");

    try {
      Class customLevel = Loader.loadClass(clazz);

      // get a ref to the specified class' static method
      // toLevel(String, org.apache.log4j.Level)
      Class[] paramTypes = new Class[] {String.class, org.apache.log4j.Level.class};
      java.lang.reflect.Method toLevelMethod = customLevel.getMethod("toLevel", paramTypes);

      // now call the toLevel method, passing level string + default
      Object[] params = new Object[] {levelName, defaultValue};
      Object o = toLevelMethod.invoke(null, params);

      result = (Level) o;
    } catch (ClassNotFoundException e) {
      LogLog.warn("custom level class [" + clazz + "] not found.");
    } catch (NoSuchMethodException e) {
      LogLog.warn(
          "custom level class ["
              + clazz
              + "]"
              + " does not have a constructor which takes one string parameter",
          e);
    } catch (java.lang.reflect.InvocationTargetException e) {
      LogLog.warn("custom level class [" + clazz + "]" + " could not be instantiated", e);
    } catch (ClassCastException e) {
      LogLog.warn("class [" + clazz + "] is not a subclass of org.apache.log4j.Level", e);
    } catch (IllegalAccessException e) {
      LogLog.warn("class [" + clazz + "] cannot be instantiated due to access restrictions", e);
    } catch (Exception e) {
      LogLog.warn("class [" + clazz + "], level [" + levelName + "] conversion failed.", e);
    }
    return result;
  }
  public void init() {
    // TODO Auto-generated method stub

    System.out.println(
        "*** "
            + "["
            + IfrendCoreLoggerLoader.class.getName()
            + "] "
            + "loading the Log4j log loader...");
    String pack = IfrendCoreLoggerLoader.class.getPackage().getName();
    // URL url = Loader.getResource("com/isg/iloan/logger/log4j.properties");
    URL url = Loader.getResource(pack.replace('.', '/') + "/log4j.properties");
    System.out.println("URL:" + url.getPath());
    PropertyConfigurator.configure(url);

    System.out.println(
        "*** "
            + "["
            + IfrendCoreLoggerLoader.class.getName()
            + "] "
            + "loading the Log4j log loader...finished!");
  }
Example #6
0
  public static URL configure() {
    final String log4jConfig = System.getProperty("log4j.configuration");

    if (log4jConfig != null) {
      // Log4j environment variable found, the LogManager will take care of
      // itself, don't bother reinitializing

      // This is what the LogManager does to find the resource.

      URL configUrl = null;
      try {
        configUrl = new URL(log4jConfig);
      } catch (MalformedURLException mue) {
        configUrl = Loader.getResource(log4jConfig);
      }

      Preconditions.checkState(configUrl != null, "Invalid config URL: %s", log4jConfig);

      return configUrl;
    }

    for (final String logFile : DEFAULT_LOG_FILES) {
      final URL configUrl = Log4jConfigurator.class.getResource(logFile);
      if (configUrl != null) {
        LogManager.resetConfiguration();
        DOMConfigurator.configure(configUrl);

        final Log log = Log.findLog();
        log.info("Configured logging from '%s'", configUrl);
        return configUrl;
      }
    }

    BasicConfigurator.configure();
    final Log log = Log.findLog();
    log.warn("No logging configuration, falling back to default!");

    return null;
  }
Example #7
0
 private MDC() {
   java1 = Loader.isJava1();
   if (!java1) {
     tlm = new ThreadLocalMap();
   }
 }
Example #8
0
  public static void main(String[] args) throws InterruptedException {
    System.setProperty("log4j.defaultInitOverride", String.valueOf(true));
    final URL log4jProps = Loader.getResource("example/log4jDirectoryProcessors.properties");
    PropertyConfigurator.configure(log4jProps);
    final Logger logger = LoggerFactory.getLogger(Main.class);
    logger.info("Log4j Config loaded from " + log4jProps.toString());

    final StateManager stateManager = new StateManager();

    final State1 state1 = new State1(new File("C:\\Users\\niket\\dirprocs\\state1"));
    final FailedState2 failedState2 =
        new FailedState2(new File("C:\\Users\\niket\\dirprocs\\failedState2"));
    final State2 state2 = new State2(new File("C:\\Users\\niket\\dirprocs\\state2"));
    final State3 state3 = new State3(new File("C:\\Users\\niket\\dirprocs\\state3"));
    final FailedState3 failedState3 =
        new FailedState3(new File("C:\\Users\\niket\\dirprocs\\failedState3"));

    final State1Processor processor1 = new State1Processor();
    final State2Processor processor2 = new State2Processor();

    stateManager.addDefinition(
        state1, processor1, new HashSet<>(Arrays.asList(new State[] {failedState2, state2})));
    stateManager.addDefinition(
        state2, processor2, new HashSet<>(Arrays.asList(new State[] {state3, failedState3})));

    final LoggerObserver logger1 = new LoggerObserver();
    stateManager.addObserver(state1, state2, logger1);
    stateManager.addObserver(state1, failedState2, logger1);
    stateManager.addObserver(state2, state3, logger1);
    stateManager.addObserver(state2, failedState3, logger1);

    final UIObserver uiObserver = new UIObserver();
    stateManager.addObserver(state1, state2, uiObserver);
    stateManager.addObserver(state1, failedState2, uiObserver);
    stateManager.addObserver(state2, state3, uiObserver);
    stateManager.addObserver(state2, failedState3, uiObserver);

    stateManager.addProcessorThreads(processor1, 1);
    stateManager.addProcessorThreads(processor2, 1);

    stateManager.startAll();

    TimeUnit.SECONDS.sleep(5);

    stateManager.stopProcessor(State1Processor.class);

    TimeUnit.SECONDS.sleep(5);

    stateManager.startProcessor(State1Processor.class);

    TimeUnit.SECONDS.sleep(5);

    stateManager.updateState(new State1(new File("C:\\Users\\niket\\dirprocs\\state4")));

    TimeUnit.SECONDS.sleep(5);

    stateManager.disableProcessor(State2Processor.class);

    TimeUnit.SECONDS.sleep(5);

    stateManager.enableProcessor(State2Processor.class, 3);

    TimeUnit.SECONDS.sleep(30);

    stateManager.shutdown();
  }