@muyanfeixiang
2017-01-13T15:17:34.000000Z
字数 2144
阅读 1389
JavaWeb
Spring
SpringMVC
log4j
本节讲述使用log4j2,其实和.net下的使用log4net用法差不多,只是要注意下配置文件位置。
配置寻找原则如下
首先在test\resources下添加log4j2-test.xml
内容如下
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</appenders>
<loggers>
<root level="debug">
<appender-ref ref="Console"/>
</root>
</loggers>
</configuration>
在GreetServlet中添加日志,代码如下
public class GreetServlet extends HttpServlet {
private static final Logger log = LogManager.getLogger();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
log.warn("Action GreetServlet not supported.");
log.error("Action GreetServlet Error.");
req.getRequestDispatcher("/WEB-INF/jsp/Greet.jsp")
.forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().println("Hello Post From GreetServlet");
}
}
运行程序,在浏览器输入localhost:8080\greet,会在Console输出看到如下日志,因为配置中leve是debug,所以只看到Error的日志输出,看不到info的日志输出
PS:添加配置到test/resources注意,文件夹要设置成Test Resources而不是Resources,不然会覆盖掉production/resources下面的配置。如下
添加log4j2.xml到src\production\resources下,内容如下,可以输出到tomcat的log的目录下。配置和之前使用的log4net差别不大,不在赘述。
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<RollingFile name="WroxFileAppender" fileName="../logs/application.log"
filePattern="../logs/application-%d{MM-dd-yyyy}-%i.log">
<PatternLayout>
<pattern>%d{HH:mm:ss.SSS} [%t] %X{id} %X{username} %-5level %c{36} %l: %msg%n</pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
<DefaultRolloverStrategy min="1" max="4" />
</RollingFile>
</appenders>
<loggers>
<root level="warn">
<appender-ref ref="Console" />
</root>
<logger name="com.liuyb" level="info" additivity="false">
<appender-ref ref="WroxFileAppender" />
<appender-ref ref="Console">
</appender-ref>
</logger>
<logger name="org.apache" level="info">
<appender-ref ref="WroxFileAppender" />
</logger>
</loggers>
</configuration>