我想你的java用戶端首先有個main函數,像這樣
public static Log logger=LogFactory.getLog(Program.class);
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
logger.info("load log4j ok!");
}
執行會出現如下異常,并且沒有列印日志
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
解決方法:
方法1(推薦):修改main函數,在載入Spring上下文之前,載入log4j
public static Log logger=LogFactory.getLog(Program.class);
public static void main(String[] args) {
DOMConfigurator.configure(Program.class.getResource("/log4j.xml"));//從class路徑加載
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
logger.info("load log4j ok!");
}
同時可以列印Spring的日志和自己的日志。
方法2:在Spring配置檔案中配置Bean
<bean id="log4jInitialization"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass"
value="org.springframework.util.Log4jConfigurer" />
<property name="targetMethod" value="initLogging" />
<property name="arguments">
<list>
<value>classpath:log4j.xml</value>
</list>
</property>
</bean>
可以列印log4j的日志,但因為首次加載時沒有找到log4j的路徑,是以之前也會出現警告:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
2013-04-26 11:05:52,593 INFO [main] ui.Program (Program.java:18) - load log4j ok!