标签:小公司与大公司 开发与运维 技术交流 职场故事 log4j配置
从最初学习使用log4j的时候,网上和书本上主要都是使用“log4j.properties”这种属性格式,配置日志。多年以来,一直使用这种格式,总的来说,简单、够用。<appender name="DEFAULT-APPENDER" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="${log4jOutputPath}/front/default.log" /><!-- 设置日志输出文件名 -->
</appender>log4j配置
可在web.xml中配置log4j.xml的位置,参数名称为:log4jXmlPath。
也可以,配置log4j的日志输出位置的目录,参数名称为:log4jOutputPath。
<servlet>
<servlet-name>Log4jInit</servlet-name>
<servlet-class>cn.fansunion.common.web.Log4jInit</servlet-class>
<init-param> <param-name>log4jXmlPath</param-name> <param-value>C:/log4j.xml</param-value> </init-param>
<init-param> <param-name>log4jOutputPath</param-name> <param-value>C:/log4j/xiaolei2</param-value> </init-param>
<load-on-startup>0</load-on-startup>
</servlet> 如果log4jOutputPath没有值,或者对应的文件不存在,将把classpath下的log4j文件夹作为默认的输出目录。
public class Log4jInit extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
// 从web.xml中找到log4j的输出目录
String log4jOutputPath = config.getInitParameter("log4jOutputPath");
// 默认的日志输出位置
if (StringUtils.isBlank(log4jOutputPath)) {
log4jOutputPath = Log4jInit.class.getClassLoader().getResource("")
.getFile()
+ "/log4j";
}
File log4jOutputPathFile = new File(log4jOutputPath);
// 如果输出文件不存在,手动创建
boolean log4xmlFileExists = log4jOutputPathFile.exists();
if (!log4xmlFileExists) {
System.out.println(log4jOutputPathFile.mkdirs());
}
// log4j.xml文件中的变量是在这里设置的
System.setProperty("log4jOutputPath", log4jOutputPath);
// 从web.xml中找到log4j.xml的输出目录
String log4jXmlPath = config.getInitParameter("log4jXmlPath");
boolean exist = false;
// 如果在web.xml手动配置,log4jXmlPath应该使用绝对地址,否则,就使用默认的位置和文件名就行
if (StringUtils.isNotBlank(log4jXmlPath)) {
File file = new File(log4jXmlPath);
exist = file.exists();
}
// log4jXmlPath默认位于classpath下log4j.xml
if (!exist) {
URL resource = Log4jInit.class.getClassLoader().getResource(
"log4j.xml");
if (resource != null) {
log4jXmlPath = resource.getFile();
}
}
DOMConfigurator.configure(log4jXmlPath);
}
}怀揣梦想的我,也不可能委身于阿里。
小雷FansUnion-博学的互联网技术工作者,全栈式多屏开发工程师
2015年1月25日
湖北-武汉-循礼门
怎样在log4j.xml配置文件中引入变量:小公司经验较多的我和阿里UC等大公司经验较多的Boss,一些技术交流和探讨
标签:小公司与大公司 开发与运维 技术交流 职场故事 log4j配置
原文地址:http://blog.csdn.net/fansunion/article/details/43114547