webservice中使用log4j記錄日誌
阿新 • • 發佈:2019-02-11
這次專案只做了webservice,然後使用log4j記錄日誌,按照原來的方式放好了記錄日誌的類,放好了log4j.properties配置檔案,啟動專案,測試webservice,竟然沒有正常記錄日誌,提示:
log4j:WARN No appenders could be found for logger (SYSTEM_LOG).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
試過很多方法都不行,後來從網上查到,要強制載入log4j.properties配置檔案,試了一下果然可以了。
新增一個servlet:
public class Log4jConfig extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } public void init() throws ServletException { String prefix = getServletContext().getRealPath("/"); String file = getInitParameter("log4j"); if (file != null) { PropertyConfigurator.configure(prefix + file); } } }
web.xml增加配置:
<!-- 強制載入log4j配置檔案 --> <servlet> <servlet-name>log4jConfig</servlet-name> <servlet-class>config.Log4jConfig</servlet-class> <init-param> <param-name>log4j</param-name> <param-value>WEB-INF\classes\log4j.properties</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
參考:http://blog.sina.com.cn/s/blog_a1304cff0101c9bb.html,感謝作者的分享
以此記錄