[英]using Log4j2 in servlet 3.0
我在我的Web應用程序中使用Log4j2進行日志記錄。 如果我創建任何簡單的java類並調用我的記錄器,它可以很好地工作並將日志打印在一個文件中。 但是,如果我在servlet類中執行相同操作,則無法正常工作。 正如文檔中所指定的,我沒有在web.xml中配置與log4j2相關的任何內容。
Web.xml代碼:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>SampleWebApp</display-name>
<welcome-file-list>
<welcome-file>Welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
在Servlet類中記錄代碼:
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger log=LogManager.getLogger(MyServlet.class);
我沒有明確地將log4j2.xml文件放在WEB-INF文件夾中,因為我在classpath中添加了這個文件,在構建項目后它自動添加到WEB-INF / classes中。
我錯過了一些配置嗎?
代碼行:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
log.error("i am inside servlet");
/*response.getWriter().append("Served at: ").append(request.getContextPath());*/
System.out.println("GET called");
}
log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="MyFile" filename="C:/Users/jasleen_kathuria/Documents/logs/info.log">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<logger name="MyServlet" level="TRACE">
<AppenderRef ref="MyFile"/>
</logger>
</Loggers>
您應該至少說明如何構建/部署Web應用程序,在哪個servlet容器上以及如何向classpath 添加內容 。
同樣,主要問題可能是你沒有在WEB-INF / lib中添加log4j2 jar,或者在WEB-INF / classes中添加它的配置。
當您調用簡單的java類時,您依賴於Web應用程序中的不同類路徑。
確保部署了log4j2.jar,例如你可以構建war解壓縮它並查看它包含的內容。
好吧,在我重新啟動Tomcat並清除瀏覽器緩存后,它得到了解決。 我現在可以看到正在打印的日志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.