[关闭]
@muyanfeixiang 2017-01-13T15:17:34.000000Z 字数 2144 阅读 1379

Java Web 学习笔记(6)

JavaWeb Spring SpringMVC log4j


本节讲述使用log4j2,其实和.net下的使用log4net用法差不多,只是要注意下配置文件位置。
配置寻找原则如下
image_1b6bagq42lnat4upud1i1a1o87p.png-347.7kB

首先在test\resources下添加log4j2-test.xml
image_1b6baiqv51js11r0e1gc716b018nb16.png-7.6kB
内容如下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration status="WARN">
  3. <appenders>
  4. <Console name="Console" target="SYSTEM_OUT">
  5. <PatternLayout
  6. pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
  7. </Console>
  8. </appenders>
  9. <loggers>
  10. <root level="debug">
  11. <appender-ref ref="Console"/>
  12. </root>
  13. </loggers>
  14. </configuration>

在GreetServlet中添加日志,代码如下

  1. public class GreetServlet extends HttpServlet {
  2. private static final Logger log = LogManager.getLogger();
  3. @Override
  4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  5. log.warn("Action GreetServlet not supported.");
  6. log.error("Action GreetServlet Error.");
  7. req.getRequestDispatcher("/WEB-INF/jsp/Greet.jsp")
  8. .forward(req, resp);
  9. }
  10. @Override
  11. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  12. resp.getWriter().println("Hello Post From GreetServlet");
  13. }
  14. }

运行程序,在浏览器输入localhost:8080\greet,会在Console输出看到如下日志,因为配置中leve是debug,所以只看到Error的日志输出,看不到info的日志输出
image_1b6bat6b1668v311vjudm91hj12d.png-32.6kB

PS:添加配置到test/resources注意,文件夹要设置成Test Resources而不是Resources,不然会覆盖掉production/resources下面的配置。如下
image_1b6basbtnf0t1v861csbram1c2p20.png-36.6kB

添加log4j2.xml配置

添加log4j2.xml到src\production\resources下,内容如下,可以输出到tomcat的log的目录下。配置和之前使用的log4net差别不大,不在赘述。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration status="WARN">
  3. <appenders>
  4. <Console name="Console" target="SYSTEM_OUT">
  5. <PatternLayout
  6. pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
  7. </Console>
  8. <RollingFile name="WroxFileAppender" fileName="../logs/application.log"
  9. filePattern="../logs/application-%d{MM-dd-yyyy}-%i.log">
  10. <PatternLayout>
  11. <pattern>%d{HH:mm:ss.SSS} [%t] %X{id} %X{username} %-5level %c{36} %l: %msg%n</pattern>
  12. </PatternLayout>
  13. <Policies>
  14. <SizeBasedTriggeringPolicy size="10 MB" />
  15. </Policies>
  16. <DefaultRolloverStrategy min="1" max="4" />
  17. </RollingFile>
  18. </appenders>
  19. <loggers>
  20. <root level="warn">
  21. <appender-ref ref="Console" />
  22. </root>
  23. <logger name="com.liuyb" level="info" additivity="false">
  24. <appender-ref ref="WroxFileAppender" />
  25. <appender-ref ref="Console">
  26. </appender-ref>
  27. </logger>
  28. <logger name="org.apache" level="info">
  29. <appender-ref ref="WroxFileAppender" />
  30. </logger>
  31. </loggers>
  32. </configuration>
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注