本文主要是介绍Log4j放在其他目录下,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一般我们直接将log4j.properties放置在src目录下,这样系统自动会找到的,其实就是放在WEB-INF/classes文件下。这个路径在classpath下,所以直接就能找到。我们写Logger的时候如下: public class HelloLog4j { public static Logger logger = Logger.getLogger(HelloLog4j.class); public static void main(String[] args) { logger.debug(“This is debug message.”); logger.info(“This is info message.”); logger.error(“This is error message.”); xxx(); } public static void xxx(){ logger.debug(“main method has invoked xxx method.”); } } 如果现在我们想把log4j.properties文件放置在其它目录下,例如:WEB-INF下和web.xml放在一起。这时候就需要我们手动指定log4j配置文件的路径,否则系统是找不到的。 一、首先我们在web.xml中配置好log4j.properties路径: log4jConfigLocation /WEB-INF/log4j.properties 二、然后写个servlet,部分代码如下: public void init() { String prefix = getServletContext().getRealPath(“/”); String file = getInitParameter(“log4jConfigLocation”); if (file != null) { PropertyConfigurator.configure(prefix + file); } } 三、在web.xml中配置servlet,并将log4jConfigLocation加入到Servlet中,让其Server启动即运行:
your servlet your servelt class log4jConfigLocation /WEB-INF/log4j.properties 1 但是,如果放在SSH中时,servlet被封装了,还要这样写吗??当然不需要。但如果位置发生变化了,该如何处理呢? log4jConfigLocation \WEB-INF\classes\coo\log4j.properties org.springframework.web.util.Log4jConfigListener org.springframework.web.util.IntrospectorCleanupListener 注:在配置中“/”与”\”最终都被编译成“\”
放到src目录下 import java.io.IOException; import java.util.Properties; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; public class LogPathTest { public static void main(String[] args) throws IOException{ Properties pro = new Properties(); pro.load(Thread().currentThread()().getContextClassLoader().getResourceAsStream(“config\log\log4j.properties”)); PropertyConfigurator.configure(pro);
这篇关于Log4j放在其他目录下的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!