在log4j2中,我个人比较喜欢把web项目的日志文件保存到对应项目的路径下,
网上这样的写法:(错误处理方法,正确请看下面)
在日志路径中调用System property的参数,大概是这样的:
log4j2配置文件:

<param name="File" value="${webApp.root}/logs/webapp.log" />

而这个webApp.root在项目中使用Sysetm.setProperty("webApp.root", "xxxx");来设置
我用静态块来设置webApp.root,但他是在log4j2加载后再加载的,结果扑街。。。
输出结果变成这样:日志文件保存到一个名为${webApp.root}的文件夹里面了。

==========================正确处理方================================
看官方介绍,还有更多方法:http://logging.apache.org/log...
1、这个是上面方法的正确写法:

System Properties Lookup As it is quite common to define values inside
and outside the application by using System Properties, it is only
natural that they should be accessible via a Lookup. As system
properties are often defined outside the application it would be quite
common to see something like:
<Appenders>
  <File name="ApplicationLog" fileName="${sys:logPath}/app.log"/>
</Appenders>

2、直接随web项目路径:

Web Lookup The WebLookup allows applications to retrieve variables
that are associated with the ServletContext. In addition to being able
to retrieve various fields in the ServletContext, WebLookup supports
looking up values stored as attributes or configured as initialization
parameters. The following table lists various keys that can be
retrieved:

Key Description attr.name Returns the ServletContext attribute with
the specified name contextPath The context path of the web application
effectiveMajorVersion Gets the major version of the Servlet
specification that the application represented by this ServletContext
is based on. effectiveMinorVersion Gets the minor version of the
Servlet specification that the application represented by this
ServletContext is based on. initParam.name Returns the ServletContext
initialization parameter with the specified name majorVersion Returns
the major version of the Servlet API that this servlet container
supports. minorVersion Returns the minor version of the Servlet API
that this servlet container supports. rootDir Returns the result of
calling getRealPath with a value of "/". serverInfo Returns the name
and version of the servlet container on which the servlet is running.
servletContextName Returns the name of the web application as defined
in the display-name element of the deployment descriptor Any other key
names specified will first be checked to see if a ServletContext
attribute exists with that name and then will be checked to see if an
initialization parameter of that name exists. If the key is located
then the corresponding value will be returned.

<Appenders>
  <File name="ApplicationLog" fileName="${web:rootDir}/app.log"/>
</Appenders>

lin_bo
33 声望0 粉丝

引用和评论

0 条评论