以下是完整的一个log4j 的配置。包括 分级别存储。存储到数据库。发送邮件。生成html等。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "../WebRoot/WEB-INF/config/log4j/log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<!--输出到控制台 -->
<appender name="LOG.Console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m%n" />
</layout>
<!--滤镜设置输出的级别 -->
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="debug" />
<param name="levelMax" value="fatal" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<!--将级别为INFO的信息输出到文件 -->
<appender name="LOG.INFO" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="logs/info.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="5120KB" />
<param name="MaxBackupIndex" value="1000" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy/MM/dd HH:mm:ss} - %-5p -%c %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="info" />
<param name="LevelMax" value="info" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<!--将级别为WARN的信息输出到文件 -->
<appender name="LOG.WARN" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="logs/warn.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="5120KB" />
<param name="MaxBackupIndex" value="1000" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy/MM/dd HH:mm:ss} - %-5p -%c %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="warn" />
<param name="LevelMax" value="warn" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<!--将级别为ERROR的信息输出到文件-->
<appender name="LOG.ERROR" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="logs/error.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="5120KB" />
<param name="MaxBackupIndex" value="1000" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy/MM/dd HH:mm:ss} - %-5p -%c %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="error" />
<param name="LevelMax" value="error" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<!--将级别为 info 级别以上的信息输出到文件 log4j.log-->
<appender name="LOG.LOG4J" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="logs/log4j.log" />
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy/MM/dd HH:mm:ss} - %-5p -%c %m%n" />
</layout>
<!-- 注掉过滤器 将所有信息存到log4j.log -->
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="info" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<!--将级别为DEBUG的信息输出到文件 -->
<appender name="LOG.DEBUG" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="logs/debug.log" />
<param name="Append" value="true" />
<param name="MaxFileSize" value="5120KB" />
<param name="MaxBackupIndex" value="1000" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy/MM/dd HH:mm:ss} - %-5p -%c %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="debug" />
<param name="LevelMax" value="debug" />
<param name="AcceptOnMatch" value="true" />
</filter>
</appender>
<!-- 将级别为 error 的信息 发送邮件 -->
<appender name="LOG.EMAIL" class="org.apache.log4j.net.SMTPAppender">
<param name="From" value="发送者邮箱" />
<param name="To" value="接受者邮箱" />
<param name="SMTPUsername" value="发送者邮箱 用户名" />
<param name="SMTPPassword" value="发送者邮箱 密码" />
<param name="threshold" value="error"/>
<param name="BufferSize" value="10" />
<param name="SMTPHost" value="smtp.163.com" />
<param name="Subject" value="Log4J Message" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss.SSS} [%p]-[%c] %m%n"/>
</layout>
</appender>
<!-- 将级别为 错误信息 生成html -->
<appender name="LOG.HTML" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="logs/exception.html" />
<param name="threshold" value="info"/>
<param name="BufferSize" value="10" />
<layout class="other.log4j.FormatHTMLLayout">
<param name="ConversionPattern" value="%-d{yyyy-MM-dd HH:mm:ss.SSS} [%p]-[%c] %m%n"/>
</layout>
</appender>
<!-- 将级别为 error 的信息输出到数据库 -->
<appender name="LOG.DB" class="org.apache.log4j.jdbc.JDBCAppender">
<param name="driver" value="com.mysql.jdbc.Driver" />
<param name="URL" value="jdbc:mysql://127.0.0.1/log4j?useUnicode=true&characterEncoding=UTF-8"/>
<param name="user" value="root" />
<param name="password" value="admin" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="INSERT INTO log4j(USERID,LOGTIME,LOGLEVEL,LOGACTION,MESSAGE)VALUES('%X{userId}','%d{yyyy-MM-dd HH:mm:ss}','%p','%l','%m')" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="levelMin" value="error" />
<param name="levelMax" value="error" />
<param name="acceptOnMatch" value="true" />
</filter>
</appender>
<!--
CREATE TABLE `log4j` (
`userid` VARCHAR(11) NULL DEFAULT NULL,
`logtime` VARCHAR(50) NULL DEFAULT NULL,
`logaction` VARCHAR(100) NULL DEFAULT NULL,
`loglevel` VARCHAR(100) NULL DEFAULT NULL,
`message` VARCHAR(255) NULL DEFAULT NULL
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
ROW_FORMAT=DEFAULT
-->
<root>
<priority value="debug" />
<appender-ref ref="LOG.Console" />
<appender-ref ref="LOG.DEBUG" />
<appender-ref ref="LOG.INFO" />
<appender-ref ref="LOG.WARN" />
<appender-ref ref="LOG.ERROR" />
<appender-ref ref="LOG.LOG4J" />
<appender-ref ref="LOG.DB" />
<appender-ref ref="LOG.EMAIL" />
<appender-ref ref="LOG.HTML" />
</root>
</log4j:configuration>
-----------------------------------
注意:
1. 在分级别输出日志时,log4.properties不能使用Filter拦截日志级别,而log4j.xml可以,从这点就感觉log4j.xml要强大些 .
2.log4j.xml插入数据库的时候sql写在layout属性的ConversionPattern参数中,而log4.properties则有单独的sql属性接受配置文件中的sql语句 .
3. 在将日志信息写到HTML时,布局需要开发人员根据样式重写。下面是一个简单的例子:
public class FormatHTMLLayout extends HTMLLayout {
protected final int BUF_SIZE = 256;
protected final int MAX_CAPACITY = 1024;
static String TRACE_PREFIX = "<br> ";
private StringBuffer sbuf = new StringBuffer(BUF_SIZE);
String title = "异常信息";
public static final String TITLE_OPTION = "Title";
boolean locationInfo = true;
public FormatHTMLLayout() {
}
public String format(LoggingEvent event) {
if (sbuf.capacity() > MAX_CAPACITY) {
sbuf = new StringBuffer(BUF_SIZE);
} else {
sbuf.setLength(0);
}
sbuf.append(Layout.LINE_SEP + "<tr>" + Layout.LINE_SEP);
sbuf.append("<td>");
sbuf.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));
sbuf.append("</td>" + Layout.LINE_SEP);
sbuf.append("<td>");
if (event.getLevel().equals(Level.FATAL)) {
sbuf.append("<font color=\"#339933\">");
sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
sbuf.append("</font>");
} else if (event.getLevel().isGreaterOrEqual(Level.WARN)) {
sbuf.append("<font color=\"#993300\"><strong>");
sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
sbuf.append("</strong></font>");
} else {
sbuf.append("<font color=\"green\">");
sbuf.append(Transform.escapeTags(String.valueOf(event.getLevel())));
sbuf.append("</font>");
}
sbuf.append("</td>" + Layout.LINE_SEP);
if (locationInfo) {
LocationInfo locInfo = event.getLocationInformation();
sbuf.append("<td>");
sbuf.append(Transform.escapeTags(locInfo.getFileName()));
sbuf.append(':');
sbuf.append(locInfo.getLineNumber());
sbuf.append("</td>" + Layout.LINE_SEP);
}
sbuf.append("<td>");
sbuf.append(Transform.escapeTags(event.getRenderedMessage()));
sbuf.append("</td>" + Layout.LINE_SEP);
sbuf.append("</tr>" + Layout.LINE_SEP);
if (event.getNDC() != null) {
sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : xx-small;\" colspan=\"6\" title=\"Nested Diagnostic Context\">");
sbuf.append("NDC: " + Transform.escapeTags(event.getNDC()));
sbuf.append("</td></tr>" + Layout.LINE_SEP);
}
String[] s = event.getThrowableStrRep();
if (s != null) {
sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : xx-small;\" colspan=\"4\">");
appendThrowableAsHTML(s, sbuf);
sbuf.append("</td></tr>" + Layout.LINE_SEP);
}
return sbuf.toString();
}
private void appendThrowableAsHTML(String[] s, StringBuffer sbuf) {
if (s != null) {
int len = s.length;
if (len == 0)
return;
sbuf.append(Transform.escapeTags(s[0]));
sbuf.append(Layout.LINE_SEP);
for (int i = 1; i < len; i++) {
sbuf.append(TRACE_PREFIX);
sbuf.append(Transform.escapeTags(s[i]));
sbuf.append(Layout.LINE_SEP);
}
}
}
public String getHeader() {
StringBuffer sbuf = new StringBuffer();
sbuf.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\" >" + Layout.LINE_SEP);
sbuf.append("<html>" + Layout.LINE_SEP);
sbuf.append("<head>" + Layout.LINE_SEP);
sbuf.append("<title>" + title + "</title>" + Layout.LINE_SEP);
sbuf.append("<style type=\"text/css\">" + Layout.LINE_SEP);
sbuf.append("<!--" + Layout.LINE_SEP);
sbuf.append("body, table {font-family: '??',arial,sans-serif; font-size: 12px;}" + Layout.LINE_SEP);
sbuf.append("th {background: #336699; color: #FFFFFF; text-align: left;}" + Layout.LINE_SEP);
sbuf.append("-->" + Layout.LINE_SEP);
sbuf.append("</style>" + Layout.LINE_SEP);
sbuf.append("<meta http-equiv=\"Content-Type\" content=\"text/html\"; charset=\"UTF-8\"> </meta>" + Layout.LINE_SEP);
sbuf.append("</head>" + Layout.LINE_SEP);
sbuf.append("<body bgcolor=\"#FFFFFF\" topmargin=\"6\" leftmargin=\"6\">" + Layout.LINE_SEP);
sbuf.append("<table cellspacing=\"0\" cellpadding=\"4\" border=\"1\" bordercolor=\"#224466\" width=\"100%\">" + Layout.LINE_SEP);
sbuf.append("<tr>" + Layout.LINE_SEP);
sbuf.append("<th>时间</th>" + Layout.LINE_SEP);
sbuf.append("<th>异常级别</h>" + Layout.LINE_SEP);
if (locationInfo) {
sbuf.append("<th>错误位置</th>" + Layout.LINE_SEP);
}
sbuf.append("<th>错误信息</th>" + Layout.LINE_SEP);
sbuf.append("</tr>" + Layout.LINE_SEP);
sbuf.append("<br></br>" + Layout.LINE_SEP);
return sbuf.toString();
}
}
效果图 参考附件。
4.在日志信息写入到数据库时:
public static void Log4jXML() {
Logger logger = Logger.getLogger(LogRun.class);
MDC.put("userId", "11");
logger.error("test_Error");
logger.warn("test_warn");
logger.info("test_Info");
logger.debug("test_debug");
MDC.remove("userId");
}
这里的 MDC :用于存储应用程序的上下文信息(context infomation),从而便于在log中使用这些上下文信息.
如图:http://my.iteye.com/admin/picture/118833.