我想你的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!