org.apache.log4j.helpers.OptionConverter Java Examples

The following examples show how to use org.apache.log4j.helpers.OptionConverter. 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: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Used internally to parse an {@link ErrorHandler} element.
 */
private void parseErrorHandler(Element element, Appender appender) {
    ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByClassName(
            subst(element.getAttribute(CLASS_ATTR)),
            ErrorHandler.class,
            null);

    if (eh != null) {
        eh.setAppender(appender);

        PropertySetter propSetter = new PropertySetter(eh);
        forEachElement(element.getChildNodes(), (currentElement) -> {
            String tagName = currentElement.getTagName();
            if (tagName.equals(PARAM_TAG)) {
                setParameter(currentElement, propSetter);
            }
        });
        propSetter.activate();
        appender.setErrorHandler(eh);
    }
}
 
Example #2
Source File: PropertyConfigurator.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
void configureRootCategory(Properties props, LoggerRepository hierarchy) {
   String effectiveFrefix = ROOT_LOGGER_PREFIX;
   String value = OptionConverter.findAndSubst(ROOT_LOGGER_PREFIX, props);

   if(value == null) {
     value = OptionConverter.findAndSubst(ROOT_CATEGORY_PREFIX, props);
     effectiveFrefix = ROOT_CATEGORY_PREFIX;
   }

   if(value == null)
     LogLog.debug("Could not find root logger information. Is this OK?");
   else {
     Logger root = hierarchy.getRootLogger();
     synchronized(root) {
parseCategory(props, root, effectiveFrefix, INTERNAL_ROOT_NAME, value);
     }
   }
 }
 
Example #3
Source File: RendererMap.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    Add a renderer to a hierarchy passed as parameter.
 */
 static
 public
 void addRenderer(RendererSupport repository, String renderedClassName,
	   String renderingClassName) {
   LogLog.debug("Rendering class: ["+renderingClassName+"], Rendered class: ["+
	 renderedClassName+"].");
   ObjectRenderer renderer = (ObjectRenderer)
            OptionConverter.instantiateByClassName(renderingClassName,
					    ObjectRenderer.class,
					    null);
   if(renderer == null) {
     LogLog.error("Could not instantiate renderer ["+renderingClassName+"].");
     return;
   } else {
     try {
Class renderedClass = Loader.loadClass(renderedClassName);
repository.setRenderer(renderedClass, renderer);
     } catch(ClassNotFoundException e) {
LogLog.error("Could not find class ["+renderedClassName+"].", e);
     }
   }
 }
 
Example #4
Source File: Log4jTest.java    From sofa-common-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndependentSpaceLog4j() {
    LoggerRepository repo1 = new Hierarchy(new RootLogger((Level) Level.DEBUG));
    URL url1 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/log4j/log-conf.xml");
    OptionConverter.selectAndConfigure(url1, null, repo1);
    Logger logger1 = repo1.getLogger("com.foo.Bar");
    Assert.assertNotNull(logger1);

    //log4j logger 2

    LoggerRepository repo2 = new Hierarchy(new RootLogger((Level) Level.DEBUG));
    URL url2 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/log4j/log4j_b.xml");
    OptionConverter.selectAndConfigure(url2, null, repo2);
    Logger logger2 = repo1.getLogger("com.foo.Bar2");
    Assert.assertNotNull(logger2);

    Assert.assertNotSame(logger1, logger2);
}
 
Example #5
Source File: AsyncAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private <T extends Log4j1Configuration> Appender createAppender(String name, String level,
        String[] appenderRefs, boolean blocking, int bufferSize, boolean includeLocation,
        T configuration) {
    org.apache.logging.log4j.Level logLevel = OptionConverter.convertLevel(level,
            org.apache.logging.log4j.Level.TRACE);
    AppenderRef[] refs = new AppenderRef[appenderRefs.length];
    int index = 0;
    for (String appenderRef : appenderRefs) {
        refs[index++] = AppenderRef.createAppenderRef(appenderRef, logLevel, null);
    }
    return new AppenderWrapper(AsyncAppender.newBuilder()
            .setName(name)
            .setAppenderRefs(refs)
            .setBlocking(blocking)
            .setBufferSize(bufferSize)
            .setIncludeLocation(includeLocation)
            .setConfiguration(configuration)
            .build());
}
 
Example #6
Source File: PropertiesConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private void configureRoot(Properties props) {
    String effectiveFrefix = ROOT_LOGGER_PREFIX;
    String value = OptionConverter.findAndSubst(ROOT_LOGGER_PREFIX, props);

    if (value == null) {
        value = OptionConverter.findAndSubst(ROOT_CATEGORY_PREFIX, props);
        effectiveFrefix = ROOT_CATEGORY_PREFIX;
    }

    if (value == null) {
        LOGGER.debug("Could not find root logger information. Is this OK?");
    } else {
        LoggerConfig root = getRootLogger();
        parseLogger(props, root, effectiveFrefix, INTERNAL_ROOT_NAME, value);
    }
}
 
Example #7
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Used internally to parse an {@link ErrorHandler} element.
 */
private void parseErrorHandler(Element element, Appender appender) {
    ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByClassName(
            subst(element.getAttribute(CLASS_ATTR)),
            ErrorHandler.class,
            null);

    if (eh != null) {
        eh.setAppender(appender);

        PropertySetter propSetter = new PropertySetter(eh);
        forEachElement(element.getChildNodes(), (currentElement) -> {
            String tagName = currentElement.getTagName();
            if (tagName.equals(PARAM_TAG)) {
                setParameter(currentElement, propSetter);
            }
        });
        propSetter.activate();
        appender.setErrorHandler(eh);
    }
}
 
Example #8
Source File: AppenderDynamicMBean.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
public
Object invoke(String operationName, Object params[], String signature[])
  throws MBeanException,
  ReflectionException {

  if(operationName.equals("activateOptions") &&
                   appender instanceof OptionHandler) {
    OptionHandler oh = (OptionHandler) appender;
    oh.activateOptions();
    return "Options activated.";
  } else if (operationName.equals("setLayout")) {
    Layout layout = (Layout) OptionConverter.instantiateByClassName((String)
						      params[0],
						      Layout.class,
						      null);
    appender.setLayout(layout);
    registerLayoutMBean(layout);
  }
  return null;
}
 
Example #9
Source File: PropertiesConfiguration.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
public Appender parseAppender(Properties props, String appenderName) {
    Appender appender = registry.get(appenderName);
    if ((appender != null)) {
        LOGGER.debug("Appender \"" + appenderName + "\" was already parsed.");
        return appender;
    }
    // Appender was not previously initialized.
    final String prefix = APPENDER_PREFIX + appenderName;
    final String layoutPrefix = prefix + ".layout";
    final String filterPrefix = APPENDER_PREFIX + appenderName + ".filter.";
    String className = OptionConverter.findAndSubst(prefix, props);
    appender = manager.parseAppender(appenderName, className, prefix, layoutPrefix, filterPrefix, props, this);
    if (appender == null) {
        appender = buildAppender(appenderName, className, prefix, layoutPrefix, filterPrefix, props);
    } else {
        registry.put(appenderName, appender);
        if (appender instanceof AppenderWrapper) {
            addAppender(((AppenderWrapper) appender).getAppender());
        } else {
            addAppender(new AppenderAdapter(appender).getAdapter());
        }
    }
    return appender;
}
 
Example #10
Source File: PropertySetter.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
   Convert <code>val</code> a String parameter to an object of a
   given type.
*/
protected
Object convertArg(String val, Class type) {
  if(val == null)
    return null;

  String v = val.trim();
  if (String.class.isAssignableFrom(type)) {
    return val;
  } else if (Integer.TYPE.isAssignableFrom(type)) {
    return new Integer(v);
  } else if (Long.TYPE.isAssignableFrom(type)) {
    return new Long(v);
  } else if (Boolean.TYPE.isAssignableFrom(type)) {
    if ("true".equalsIgnoreCase(v)) {
      return Boolean.TRUE;
    } else if ("false".equalsIgnoreCase(v)) {
      return Boolean.FALSE;
    }
  } else if (Priority.class.isAssignableFrom(type)) {
    return OptionConverter.toLevel(v, (Level) Level.DEBUG);
  }
  return null;
}
 
Example #11
Source File: RewriteAppenderBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private <T extends Log4j1Configuration> Appender createAppender(String name, String level,
        String[] appenderRefs, RewritePolicy policy, Filter filter, T configuration) {
    org.apache.logging.log4j.Level logLevel = OptionConverter.convertLevel(level,
            org.apache.logging.log4j.Level.TRACE);
    AppenderRef[] refs = new AppenderRef[appenderRefs.length];
    int index = 0;
    for (String appenderRef : appenderRefs) {
        refs[index++] = AppenderRef.createAppenderRef(appenderRef, logLevel, null);
    }
    org.apache.logging.log4j.core.Filter rewriteFilter = buildFilters(level, filter);
    org.apache.logging.log4j.core.appender.rewrite.RewritePolicy rewritePolicy;
    if (policy instanceof RewritePolicyWrapper) {
        rewritePolicy = ((RewritePolicyWrapper) policy).getPolicy();
    } else {
        rewritePolicy = new RewritePolicyAdapter(policy);
    }
    return new AppenderWrapper(RewriteAppender.createAppender(name, true, refs, configuration,
            rewritePolicy, rewriteFilter));
}
 
Example #12
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Used internally to parse a level  element.
 */
private void parseLevel(Element element, LoggerConfig logger, boolean isRoot) {
    String catName = logger.getName();
    if (isRoot) {
        catName = "root";
    }

    String priStr = subst(element.getAttribute(VALUE_ATTR));
    LOGGER.debug("Level value for {} is [{}}].", catName, priStr);

    if (INHERITED.equalsIgnoreCase(priStr) || NULL.equalsIgnoreCase(priStr)) {
        if (isRoot) {
            LOGGER.error("Root level cannot be inherited. Ignoring directive.");
        } else {
            logger.setLevel(null);
        }
    } else {
        String className = subst(element.getAttribute(CLASS_ATTR));
        if (EMPTY_STR.equals(className)) {
            logger.setLevel(convertLevel(OptionConverter.toLevel(priStr, Level.DEBUG)));
        } else {
            LOGGER.debug("Desired Level sub-class: [{}]", className);
            try {
                Class<?> clazz = LoaderUtil.loadClass(className);
                Method toLevelMethod = clazz.getMethod("toLevel", ONE_STRING_PARAM);
                Level pri = (Level) toLevelMethod.invoke(null, new Object[]{priStr});
                logger.setLevel(convertLevel(pri));
            } catch (Exception oops) {
                if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
                    Thread.currentThread().interrupt();
                }
                LOGGER.error("Could not create level [" + priStr +
                        "]. Reported error follows.", oops);
                return;
            }
        }
    }
    LOGGER.debug("{} level set to {}", catName,  logger.getLevel());
}
 
Example #13
Source File: OptionConverterTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
void varSubstTest2() {
  String r;

  r = OptionConverter.substVars("Test2 ${key1} mid ${key2} end.", null);
  assertEquals("Test2 value1 mid value2 end.", r);
}
 
Example #14
Source File: OptionConverterTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
void varSubstTest1() {
  String r;

  r = OptionConverter.substVars("hello world.", null);
  assertEquals("hello world.", r);
  
  r = OptionConverter.substVars("hello ${TOTO} world.", null);
  
  assertEquals("hello wonderful world.", r);
}
 
Example #15
Source File: SMTPAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
   The <b>EvaluatorClass</b> option takes a string value
   representing the name of the class implementing the {@link
   TriggeringEventEvaluator} interface. A corresponding object will
   be instantiated and assigned as the triggering event evaluator
   for the SMTPAppender.
 */
public
void setEvaluatorClass(String value) {
    evaluator = (TriggeringEventEvaluator)
              OptionConverter.instantiateByClassName(value,
			   TriggeringEventEvaluator.class,
				       evaluator);
}
 
Example #16
Source File: PropertyConfigurator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    Parse non-root elements, such non-root categories and renderers.
 */
 protected
 void parseCatsAndRenderers(Properties props, LoggerRepository hierarchy) {
   Enumeration enumeration = props.propertyNames();
   while(enumeration.hasMoreElements()) {
     String key = (String) enumeration.nextElement();
     if(key.startsWith(CATEGORY_PREFIX) || key.startsWith(LOGGER_PREFIX)) {
String loggerName = null;
if(key.startsWith(CATEGORY_PREFIX)) {
  loggerName = key.substring(CATEGORY_PREFIX.length());
} else if(key.startsWith(LOGGER_PREFIX)) {
  loggerName = key.substring(LOGGER_PREFIX.length());
}
String value =  OptionConverter.findAndSubst(key, props);
Logger logger = hierarchy.getLogger(loggerName, loggerFactory);
synchronized(logger) {
  parseCategory(props, logger, key, loggerName, value);
  parseAdditivityForLogger(props, logger, loggerName);
}
     } else if(key.startsWith(RENDERER_PREFIX)) {
String renderedClass = key.substring(RENDERER_PREFIX.length());
String renderingClass = OptionConverter.findAndSubst(key, props);
if(hierarchy instanceof RendererSupport) {
  RendererMap.addRenderer((RendererSupport) hierarchy, renderedClass,
			  renderingClass);
}
     }
   }
 }
 
Example #17
Source File: XmlConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an object and processes any nested param elements
 * but does not call activateOptions.  If the class also supports
 * UnrecognizedElementParser, the parseUnrecognizedElement method
 * will be call for any child elements other than param.
 *
 * @param element       element, may not be null.
 * @param props         properties
 * @param expectedClass interface or class expected to be implemented
 *                      by created class
 * @return created class or null.
 * @throws Exception thrown if the contain object should be abandoned.
 * @since 1.2.15
 */
public static Object parseElement(final Element element, final Properties props,
        @SuppressWarnings("rawtypes") final Class expectedClass) throws Exception {
    String clazz = subst(element.getAttribute("class"), props);
    Object instance = OptionConverter.instantiateByClassName(clazz,
            expectedClass, null);

    if (instance != null) {
        PropertySetter propSetter = new PropertySetter(instance);
        NodeList children = element.getChildNodes();
        final int length = children.getLength();

        for (int loop = 0; loop < length; loop++) {
            Node currentNode = children.item(loop);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                Element currentElement = (Element) currentNode;
                String tagName = currentElement.getTagName();
                if (tagName.equals("param")) {
                    setParameter(currentElement, propSetter, props);
                } else {
                    parseUnrecognizedElement(instance, currentElement, props);
                }
            }
        }
        return instance;
    }
    return null;
}
 
Example #18
Source File: HierarchyDynamicMBean.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
void setAttribute(Attribute attribute) throws AttributeNotFoundException,
                                              InvalidAttributeValueException,
                                              MBeanException,
                                              ReflectionException {

  // Check attribute is not null to avoid NullPointerException later on
  if (attribute == null) {
    throw new RuntimeOperationsException(
                new IllegalArgumentException("Attribute cannot be null"),
 "Cannot invoke a setter of "+dClassName+" with null attribute");
  }
  String name = attribute.getName();
  Object value = attribute.getValue();

  if (name == null) {
    throw new RuntimeOperationsException(
             new IllegalArgumentException("Attribute name cannot be null"),
      "Cannot invoke the setter of "+dClassName+
      " with null attribute name");
  }

  if(name.equals(THRESHOLD)) {
    Level l = OptionConverter.toLevel((String) value,
			   hierarchy.getThreshold());
    hierarchy.setThreshold(l);
  }


}
 
Example #19
Source File: StringMatchFilter.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
   @deprecated Use the setter method for the option directly instead
   of the generic <code>setOption</code> method. 
*/
public
void setOption(String key, String value) { 
  
  if(key.equalsIgnoreCase(STRING_TO_MATCH_OPTION)) {
    stringToMatch = value;
  } else if (key.equalsIgnoreCase(ACCEPT_ON_MATCH_OPTION)) {
    acceptOnMatch = OptionConverter.toBoolean(value, acceptOnMatch);
  }
}
 
Example #20
Source File: PropertyConfigurator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    Read configuration options from <code>properties</code>.

    See {@link #doConfigure(String, LoggerRepository)} for the expected format.
 */
 public
 void doConfigure(Properties properties, LoggerRepository hierarchy) {
   String value = properties.getProperty(LogLog.DEBUG_KEY);
   if(value == null) {
     value = properties.getProperty("log4j.configDebug");
     if(value != null)
LogLog.warn("[log4j.configDebug] is deprecated. Use [log4j.debug] instead.");
   }

   if(value != null) {
     LogLog.setInternalDebugging(OptionConverter.toBoolean(value, true));
   }

     //
     //   if log4j.reset=true then
     //        reset hierarchy
   String reset = properties.getProperty(RESET_KEY);
   if (reset != null && OptionConverter.toBoolean(reset, false)) {
         hierarchy.resetConfiguration();
   }

   String thresholdStr = OptionConverter.findAndSubst(THRESHOLD_PREFIX,
					       properties);
   if(thresholdStr != null) {
     hierarchy.setThreshold(OptionConverter.toLevel(thresholdStr,
					     (Level) Level.ALL));
     LogLog.debug("Hierarchy threshold set to ["+hierarchy.getThreshold()+"].");
   }

   configureRootCategory(properties, hierarchy);
   configureLoggerFactory(properties);
   parseCatsAndRenderers(properties, hierarchy);

   LogLog.debug("Finished configuring.");
   // We don't want to hold references to appenders preventing their
   // garbage collection.
   registry.clear();
 }
 
Example #21
Source File: OptionConverterTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
void varSubstTest3() {
  String r;

  r = OptionConverter.substVars(
		     "Test3 ${unset} mid ${key1} end.", null);
  assertEquals("Test3  mid value1 end.", r);
}
 
Example #22
Source File: OptionConverterTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
void varSubstTest4() {
  String res;
  String val = "Test4 ${incomplete ";
  try {
    res = OptionConverter.substVars(val, null);
  }
  catch(IllegalArgumentException e) {
    String errorMsg = e.getMessage();
    //System.out.println('['+errorMsg+']');
    assertEquals('"'+val
   + "\" has no closing brace. Opening brace at position 6.", 
   errorMsg);
  }
}
 
Example #23
Source File: OptionConverterTestCase.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public
void varSubstTest5() {
  Properties props = new Properties();
  props.put("p1", "x1");
  props.put("p2", "${p1}");
  String res = OptionConverter.substVars("${p2}", props);
  System.out.println("Result is ["+res+"].");
  assertEquals(res, "x1");
}
 
Example #24
Source File: PropertiesConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public Layout parseLayout(String layoutPrefix, String appenderName, Properties props) {
    String layoutClass = OptionConverter.findAndSubst(layoutPrefix, props);
    if (layoutClass == null) {
        return null;
    }
    Layout layout = manager.parseLayout(layoutClass, layoutPrefix, props, this);
    if (layout == null) {
        layout = buildLayout(layoutPrefix, layoutClass, appenderName, props);
    }
    return layout;
}
 
Example #25
Source File: PropertiesConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Appender buildAppender(final String appenderName, final String className, final String prefix,
        final String layoutPrefix, final String filterPrefix, final Properties props) {
    Appender appender = newInstanceOf(className, "Appender");
    if (appender == null) {
        return null;
    }
    appender.setName(appenderName);
    appender.setLayout(parseLayout(layoutPrefix, appenderName, props));
    final String errorHandlerPrefix = prefix + ".errorhandler";
    String errorHandlerClass = OptionConverter.findAndSubst(errorHandlerPrefix, props);
    if (errorHandlerClass != null) {
        ErrorHandler eh = parseErrorHandler(props, errorHandlerPrefix, errorHandlerClass, appender);
        if (eh != null) {
            appender.setErrorHandler(eh);
        }
    }
    parseAppenderFilters(props, filterPrefix, appenderName);
    String[] keys = new String[] {
            layoutPrefix,
    };
    addProperties(appender, keys, props, prefix);
    if (appender instanceof AppenderWrapper) {
        addAppender(((AppenderWrapper) appender).getAppender());
    } else {
        addAppender(new AppenderAdapter(appender).getAdapter());
    }
    registry.put(appenderName, appender);
    return appender;
}
 
Example #26
Source File: PropertiesConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the additivity option for a non-root category.
 */
private boolean getAdditivityForLogger(Properties props, String loggerName) {
    boolean additivity = true;
    String key = ADDITIVITY_PREFIX + loggerName;
    String value = OptionConverter.findAndSubst(key, props);
    LOGGER.debug("Handling {}=[{}]", key, value);
    // touch additivity only if necessary
    if ((value != null) && (!value.equals(""))) {
        additivity = OptionConverter.toBoolean(value, true);
    }
    return additivity;
}
 
Example #27
Source File: DailyFileAppender1.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
   Retuns the option names for this component, namely {@link
   #FILE_NAME_PATTERN_OPTION} in
   addition to the options of {@link FileAppender#getOptionStrings
   FileAppender}.
*/
public
String[] getOptionStrings() {

  return OptionConverter.concatanateArrays(super.getOptionStrings(),
 new String[] {FILE_NAME_PATTERN_OPTION});
}
 
Example #28
Source File: DatagramStringAppender.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
   Returns the option names for this component, namely the string
   array consisting of {{@link #DATAGRAM_HOST_OPTION}, {@link
   #DATAGRAM_PORT_OPTION}, {@link #DATAGRAM_ENCODING_OPTION}  */
public
String[] getOptionStrings() {
  return OptionConverter.concatanateArrays(super.getOptionStrings(),
      new String[] {
          DATAGRAM_HOST_OPTION,
          DATAGRAM_PORT_OPTION,
          DATAGRAM_ENCODING_OPTION});
}
 
Example #29
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Used internally to parse a level  element.
 */
private void parseLevel(Element element, LoggerConfig logger, boolean isRoot) {
    String catName = logger.getName();
    if (isRoot) {
        catName = "root";
    }

    String priStr = subst(element.getAttribute(VALUE_ATTR));
    LOGGER.debug("Level value for {} is [{}}].", catName, priStr);

    if (INHERITED.equalsIgnoreCase(priStr) || NULL.equalsIgnoreCase(priStr)) {
        if (isRoot) {
            LOGGER.error("Root level cannot be inherited. Ignoring directive.");
        } else {
            logger.setLevel(null);
        }
    } else {
        String className = subst(element.getAttribute(CLASS_ATTR));
        if (EMPTY_STR.equals(className)) {
            logger.setLevel(OptionConverter.convertLevel(priStr, org.apache.logging.log4j.Level.DEBUG));
        } else {
            LOGGER.debug("Desired Level sub-class: [{}]", className);
            try {
                Class<?> clazz = LoaderUtil.loadClass(className);
                Method toLevelMethod = clazz.getMethod("toLevel", ONE_STRING_PARAM);
                Level pri = (Level) toLevelMethod.invoke(null, new Object[]{priStr});
                logger.setLevel(OptionConverter.convertLevel(pri));
            } catch (Exception oops) {
                if (oops instanceof InterruptedException || oops instanceof InterruptedIOException) {
                    Thread.currentThread().interrupt();
                }
                LOGGER.error("Could not create level [" + priStr +
                        "]. Reported error follows.", oops);
                return;
            }
        }
    }
    LOGGER.debug("{} level set to {}", catName,  logger.getLevel());
}
 
Example #30
Source File: XmlConfiguration.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an object and processes any nested param elements
 * but does not call activateOptions.  If the class also supports
 * UnrecognizedElementParser, the parseUnrecognizedElement method
 * will be call for any child elements other than param.
 *
 * @param element       element, may not be null.
 * @param props         properties
 * @param expectedClass interface or class expected to be implemented
 *                      by created class
 * @return created class or null.
 * @throws Exception thrown if the contain object should be abandoned.
 * @since 1.2.15
 */
public Object parseElement(final Element element, final Properties props,
        @SuppressWarnings("rawtypes") final Class expectedClass) throws Exception {
    String clazz = subst(element.getAttribute("class"), props);
    Object instance = OptionConverter.instantiateByClassName(clazz,
            expectedClass, null);

    if (instance != null) {
        PropertySetter propSetter = new PropertySetter(instance);
        NodeList children = element.getChildNodes();
        final int length = children.getLength();

        for (int loop = 0; loop < length; loop++) {
            Node currentNode = children.item(loop);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                Element currentElement = (Element) currentNode;
                String tagName = currentElement.getTagName();
                if (tagName.equals("param")) {
                    setParameter(currentElement, propSetter, props);
                } else {
                    parseUnrecognizedElement(instance, currentElement, props);
                }
            }
        }
        return instance;
    }
    return null;
}