下面列出了怎么用org.apache.log4j.spi.LoggerRepository的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@Test
public void testLocalProperties() throws NoSuchFieldException, IllegalAccessException {
LoggerRepository repo2 = new Hierarchy(new RootLogger((Level) Level.DEBUG));
URL url2 = LogbackTest.class.getResource("/com/alipay/sofa/rpc/log/log4j/log4j_b.xml");
DOMConfigurator domConfigurator = new DOMConfigurator();
Field field = DOMConfigurator.class.getDeclaredField("props");
field.setAccessible(true);
Properties props = new Properties();
field.set(domConfigurator, props);
props.put("hello", "defaultb");
domConfigurator.doConfigure(url2, repo2);
Logger logger2 = repo2.getLogger("com.foo.Bar3");
Assert.assertTrue(logger2.getAllAppenders().hasMoreElements());
}
/**
Read configuration options from url <code>configURL</code>.
*/
public
void doConfigure(java.net.URL configURL, LoggerRepository hierarchy) {
Properties props = new Properties();
LogLog.debug("Reading configuration from URL " + configURL);
InputStream istream = null;
try {
istream = configURL.openStream();
props.load(istream);
}
catch (Exception e) {
LogLog.error("Could not read configuration file from URL [" + configURL
+ "].", e);
LogLog.error("Ignoring configuration file [" + configURL +"].");
return;
}
finally {
if (istream != null) {
try {
istream.close();
} catch(Exception ignore) {
}
}
}
doConfigure(props, hierarchy);
}
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);
}
}
}
/**
Configure log4j by reading in a log4j.dtd compliant XML
configuration file.
*/
public
void doConfigure(final InputStream inputStream, LoggerRepository repository)
throws FactoryConfigurationError {
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
InputSource inputSource = new InputSource(inputStream);
inputSource.setSystemId("dummy://log4j.dtd");
return parser.parse(inputSource);
}
public String toString() {
return "input stream [" + inputStream.toString() + "]";
}
};
doConfigure(action, repository);
}
/**
Configure log4j by reading in a log4j.dtd compliant XML
configuration file.
*/
public
void doConfigure(final Reader reader, LoggerRepository repository)
throws FactoryConfigurationError {
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
InputSource inputSource = new InputSource(reader);
inputSource.setSystemId("dummy://log4j.dtd");
return parser.parse(inputSource);
}
public String toString() {
return "reader [" + reader.toString() + "]";
}
};
doConfigure(action, repository);
}
/**
Configure log4j by reading in a log4j.dtd compliant XML
configuration file.
*/
protected
void doConfigure(final InputSource inputSource, LoggerRepository repository)
throws FactoryConfigurationError {
if (inputSource.getSystemId() == null) {
inputSource.setSystemId("dummy://log4j.dtd");
}
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
return parser.parse(inputSource);
}
public String toString() {
return "input source [" + inputSource.toString() + "]";
}
};
doConfigure(action, repository);
}
private synchronized void captureState(LoggerRepository hierarchy) throws IllegalStateException {
if (null == hierarchy) {
throw new IllegalArgumentException("Null Hierarchy is not allowed.");
}
if (null != capturedHierarchy && capturedHierarchy != hierarchy) {
throw new IllegalStateException("Log configurations is already holding a captured hierarchy.");
}
capturedHierarchy = hierarchy;
threshold = hierarchy.getThreshold();
Enumeration e = hierarchy.getCurrentLoggers();
while (e.hasMoreElements()) {
Logger l = (Logger)e.nextElement();
Level v = l.getLevel();
// No point in capturing or restoring NULL loggers.
if (null != v) {
capturedConfiguration.addConfiguration(l.getName(), v);
}
}
}
public void doConfigure(Properties properties, LoggerRepository repository) {
String logParams = System.getenv(TezConstants.TEZ_CONTAINER_LOG_PARAMS);
if (logParams != null) {
String []parts = logParams.split(TezConstants.TEZ_CONTAINER_LOG_PARAMS_SEPARATOR);
for (String logParam : parts) {
String [] logParamParts = logParam.split("=");
if (logParamParts.length == 2) {
String loggerName = "log4j.logger." + logParamParts[0];
String logLevel = logParamParts[1].toUpperCase(Locale.ENGLISH);
properties.setProperty(loggerName, logLevel);
} else {
// Cannot use Log4J logging from here.
System.out.println("TezLog4jConfigurator Ignoring invalid log parameter [" + logParam + "]");
continue;
}
}
}
super.doConfigure(properties, repository);
}
/**
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();
}
/**
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);
}
}
}
}
public
void doConfigure(final String filename, LoggerRepository repository) {
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
return parser.parse(new File(filename));
}
public String toString() {
return "file [" + filename + "]";
}
};
doConfigure(action, repository);
}
public
void doConfigure(final URL url, LoggerRepository repository) {
ParseAction action = new ParseAction() {
public Document parse(final DocumentBuilder parser) throws SAXException, IOException {
return parser.parse(url.toString());
}
public String toString() {
return "url [" + url.toString() + "]";
}
};
doConfigure(action, repository);
}
public ThreadLocalAwareLoggerRepository(Logger originalRoot, LoggerRepository parentRepository, LoggerFactory loggerFactory) {
super(originalRoot);
if (loggerFactory == null) {
throw new IllegalArgumentException("loggerFactory must not be null");
}
loggerFactory_ = loggerFactory;
parentLoggerRepository_ = parentRepository;
}
/**
* Installs the ThreadLogManager in this system.
* <p>
* Note that this can fail if some other framework has done a call to LogManager.setRepositorySelector with a guard already.
*
* @param logMessageModifier
* optional implementation of LogMessageModifier which allows messages to be modified should they be affected by a threadlocal loglevel overwrite. This
* allows for example for messages to be prepended with a token so that they can be easier found in the log
*/
void install(final LogMessageModifier logMessageModifier) {
try {
final LoggerFactory loggerFactory = new LoggerFactory() {
@SuppressWarnings("synthetic-access")
@Override
public Logger makeNewLoggerInstance(String name) {
return new ThreadLocalAwareLogger(name, threadLocalLogLevel_, logMessageModifier);
}
};
final Logger originalRootLogger = LogManager.getRootLogger();
final LoggerRepository parentRepository = originalRootLogger.getLoggerRepository();
final LoggerRepository repository = new ThreadLocalAwareLoggerRepository(originalRootLogger, parentRepository, loggerFactory);
LogManager.setRepositorySelector(new RepositorySelector() {
@Override
public LoggerRepository getLoggerRepository() {
return repository;
}
}, guard);
} catch (IllegalArgumentException re) {
// thrown by LogManager.setRepositorySelector
log.error("Could not install ThreadLocalLogLevelManager", re);
}
}
public ThreadLocalAwareLoggerRepository(Logger originalRoot, LoggerRepository parentRepository, LoggerFactory loggerFactory) {
super(originalRoot);
if (loggerFactory == null) {
throw new IllegalArgumentException("loggerFactory must not be null");
}
loggerFactory_ = loggerFactory;
parentLoggerRepository_ = parentRepository;
}
/**
* Installs the ThreadLogManager in this system.
* <p>
* Note that this can fail if some other framework has done a call to LogManager.setRepositorySelector with a guard already.
*
* @param logMessageModifier
* optional implementation of LogMessageModifier which allows messages to be modified should they be affected by a threadlocal loglevel overwrite. This
* allows for example for messages to be prepended with a token so that they can be easier found in the log
*/
void install(final LogMessageModifier logMessageModifier) {
try {
final LoggerFactory loggerFactory = new LoggerFactory() {
@SuppressWarnings("synthetic-access")
@Override
public Logger makeNewLoggerInstance(String name) {
return new ThreadLocalAwareLogger(name, threadLocalLogLevel_, logMessageModifier);
}
};
final Logger originalRootLogger = LogManager.getRootLogger();
final LoggerRepository parentRepository = originalRootLogger.getLoggerRepository();
final LoggerRepository repository = new ThreadLocalAwareLoggerRepository(originalRootLogger, parentRepository, loggerFactory);
LogManager.setRepositorySelector(new RepositorySelector() {
@Override
public LoggerRepository getLoggerRepository() {
return repository;
}
}, guard);
} catch (IllegalArgumentException re) {
// thrown by LogManager.setRepositorySelector
log.error("Could not install ThreadLocalLogLevelManager", re);
}
}
public synchronized void mute(LoggerRepository hierarchy) throws IllegalStateException {
if (null == hierarchy) {
throw new IllegalArgumentException("Null Hierarchy is not allowed.");
}
if (null != capturedHierarchy && capturedHierarchy != hierarchy) {
throw new IllegalStateException("Trying to mute a hierarchy that is not the one previously captured.");
}
captureState(hierarchy);
hierarchy.setThreshold(Level.OFF);
}
private DelegatingLoggerRepository(LoggerRepository loggerRepository)
{
this.loggerRepository = loggerRepository;
}
@Override
@SuppressWarnings("deprecation")
public LoggerRepository getHierarchy() {
return log.getHierarchy();
}
@Override
public LoggerRepository getLoggerRepository() {
return log.getLoggerRepository();
}
private TestLogger(String name, LoggerRepository repo) {
super(name);
repository = repo;
setLevel(Level.INFO);
}
/**
* figure out the log4j's configuration: for example, appenders' file path, buff io, etc...
*
* @param context
* @param webapploader
*/
@SuppressWarnings({ "rawtypes", "static-access" })
private void figureOutLog4jConfig(HookContext context, ClassLoader webapploader) {
Logger logger4j = Logger.getLogger(Log4jHookProxy.class);
InterceptContext interceptContext = (InterceptContext) context.get(HookConstants.INTERCEPTCONTEXT);
if (interceptContext == null) {
logger.warn("No InterceptContext available, can't figure out Log4j configuration.", null);
return;
}
@SuppressWarnings("unchecked")
LinkedList<LogProfileInfo> list = (LinkedList<LogProfileInfo>) interceptContext
.get(HookConstants.LOG_PROFILE_LIST);
if (null == list) {
list = new LinkedList<LogProfileInfo>();
interceptContext.put(HookConstants.LOG_PROFILE_LIST, list);
}
String appid = (String) (interceptContext.get(InterceptConstants.CONTEXTPATH));
// figureout root logger
list.addAll(figureoutLogConfiguration(logger4j.getRootLogger(), appid));
// figureour norootlogger
LoggerRepository lr = null;
try {
lr = logger4j.getLoggerRepository();
}
catch (NoSuchMethodError err) {
// for log4j-over-slf4j, doesn't have this method
return;
}
Enumeration logEnum = lr.getCurrentLoggers();
while (logEnum != null && logEnum.hasMoreElements()) {
Logger sLogger = (Logger) logEnum.nextElement();
list.addAll(figureoutLogConfiguration(sLogger, appid));
}
}
private TestLogger(String name, LoggerRepository repo) {
super(name);
repository = repo;
setLevel(Level.INFO);
}
public
void doConfigure(URL url, LoggerRepository repository) {
}
/**
Configure by taking in an DOM element.
*/
public void doConfigure(Element element, LoggerRepository repository) {
this.repository = repository;
parse(element);
}
/**
* This is a dummy method that will throw an
* <code>IllegalStateException</code> if used.
*/
public void doConfigure(URL configURL, LoggerRepository repository) {
throw new IllegalStateException("This class should NOT be" +
" instantiated!");
}
/**
Only the Hiearchy class can set the hiearchy of a
category. Default package access is MANDATORY here. */
final
void setHierarchy(LoggerRepository repository) {
this.repository = repository;
}
public
void testDisable1() {
CountingAppender caRoot = new CountingAppender();
Logger root = Logger.getRootLogger();
root.addAppender(caRoot);
LoggerRepository h = LogManager.getLoggerRepository();
//h.disableDebug();
h.setThreshold((Level) Level.INFO);
assertEquals(caRoot.counter, 0);
root.debug(MSG); assertEquals(caRoot.counter, 0);
root.info(MSG); assertEquals(caRoot.counter, 1);
root.log(Level.WARN, MSG); assertEquals(caRoot.counter, 2);
root.warn(MSG); assertEquals(caRoot.counter, 3);
//h.disableInfo();
h.setThreshold((Level) Level.WARN);
root.debug(MSG); assertEquals(caRoot.counter, 3);
root.info(MSG); assertEquals(caRoot.counter, 3);
root.log(Level.WARN, MSG); assertEquals(caRoot.counter, 4);
root.error(MSG); assertEquals(caRoot.counter, 5);
root.log(Level.ERROR, MSG); assertEquals(caRoot.counter, 6);
//h.disableAll();
h.setThreshold(Level.OFF);
root.debug(MSG); assertEquals(caRoot.counter, 6);
root.info(MSG); assertEquals(caRoot.counter, 6);
root.log(Level.WARN, MSG); assertEquals(caRoot.counter, 6);
root.error(MSG); assertEquals(caRoot.counter, 6);
root.log(Level.FATAL, MSG); assertEquals(caRoot.counter, 6);
root.log(Level.FATAL, MSG); assertEquals(caRoot.counter, 6);
//h.disable(Level.FATAL);
h.setThreshold(Level.OFF);
root.debug(MSG); assertEquals(caRoot.counter, 6);
root.info(MSG); assertEquals(caRoot.counter, 6);
root.log(Level.WARN, MSG); assertEquals(caRoot.counter, 6);
root.error(MSG); assertEquals(caRoot.counter, 6);
root.log(Level.ERROR, MSG); assertEquals(caRoot.counter, 6);
root.log(Level.FATAL, MSG); assertEquals(caRoot.counter, 6);
}
private DelegatingLoggerRepository(LoggerRepository loggerRepository)
{
this.loggerRepository = loggerRepository;
}