通常情况下,log4j的日志格式由它的layout组件来管理,最典型的一个日志格式的定义是这样的:
在log4j.propties文件里这样写:
log4j.appender.com.xxx.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} | %l | %p | %m%n
最终我们产生的日志如下:
2011-06-21 09:55:09 | com.jl.mi.Test.main(Test.java:22) | INFO | test message!
但是,在实际项目中,仅仅记录上述信息是不够的,比如,我们有这样一个需求:
1、集群状态下,我们一个应用部署了多个web server,我们希望在日志里打印出当前日志时哪台服务器上产生的。
2、为了进行审计,我们需要在日志中记录业务操作员的工号信息。
对于上述两个需求,很多同学可能在想,这还不简单吗,只要将log4j的Logger类进行简单封装,在messge部分就可以了,如果不分装也可以啊,可如下去记录这些信息:
Logger logger = MyLogger.getLogger(Test.class);
logger.info(getUserCode() + " | " + getSvrName() " | test customization log info!");
事实上上述做法不是最巧妙的,也不是log4j所设计的标准做法。通过对log4j源码的分析,我们发现可以用如下方式扩转日志信息的格式:
LoggingEvent event = new LoggingEvent(JLogger.class.getName(), logger, level, msg, e);
event.setProperty(Constant.MGD_SVR_NAME, Util.getMgdSvrName());
event.setProperty(Constant.USER_CODE, Util.getUserCode());
然后,我们的layout格式写成如下方式,就可以达到扩展的目的:
log4j.appender.y_svr_logout.layout.ConversionPattern=%X{mgdSvrName} | %X{userCode} | %d{yyyy-MM-dd HH:mm:ss} | %l | %p | %m%n
使用%X{...}读取设置在LoggingEvent实例中的属性。这种扩展是巧妙的,优雅的,符合log4j设计者的初衷的。
基于上面的分析,我们可以进行一个封装,其代码如下:
package com.jl.yyf.common.logging;
import com.jl.yyf.common.ini.ERPIni;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.apache.log4j.spi.LoggingEvent;
/**
* Customization log tool.it has carried on the simple seal to log4j, simplifies the development.
*
* @author Jack Dou
* @version 2010.09.17
*/
public final class JLogger {
private static final boolean logDisable = false;
/**
* JianLong log level definition.
*
* @author Jack Dou
* @since Sep 29, 2010
*/
public enum Level{
/**
* debug level.
*/
DEBUG,
/**
* info level.
*/
INFO,
/**
* warn level.
*/
WARN,
/**
* error level.
*/
ERROR
}
/**
* Delegate the org.apache.log4j.Logger#getLogger(String clsName)
*
* @param clsName Class name
* @return org.apache.log4j.Logger
* @see org.apache.log4j.Logger
*/
public static Logger getLogger(String clsName) {
return Logger.getLogger(clsName);
}
/**
* Delegate the org.apache.log4j.Logger#getLogger(Class cls)
*
* @param cls The class
* @return org.apache.log4j.Logger
* @see org.apache.log4j.Logger
*/
public static Logger getLogger(Class cls) {
return Logger.getLogger(cls);
}
/**
* Log the message for level(debug)
*
* @param logger The logger
* @param msg The message
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logDebug(Logger logger, String msg) {
logDebug(logger, msg, null);
}
/**
* Log the message for level(info)
*
* @param logger The logger
* @param msg The message
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logInfo(Logger logger, String msg) {
logInfo(logger, msg, null);
}
/**
* Log the message for level(warn)
*
* @param logger The logger
* @param msg The message
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logWarn(Logger logger, String msg) {
logWarn(logger, msg, null);
}
/**
* Log the message for level(error)
*
* @param logger The logger
* @param msg The message
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logError(Logger logger, String msg) {
logError(logger, msg, null);
}
/**
* Log the message for level(debug)
*
* @param logger The logger
* @param msg The message
* @param e The exception stack
*/
public static void logDebug(Logger logger, String msg, Throwable e) {
if (logDisable){
return;
}
try {
validateParam(logger, msg);
log(logger, Level.DEBUG, msg, e);
} catch (Exception ex) {
onException(ex);
}
}
/**
* Log the message for level(info)
*
* @param logger The logger
* @param msg The message
* @param e The exception stack
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logInfo(Logger logger, String msg, Throwable e) {
if (logDisable){
return;
}
try {
validateParam(logger, msg);
log(logger, Level.INFO, msg, e);
} catch (Exception ex) {
onException(ex);
}
}
/**
* Log the message for level(warn)
*
* @param logger The logger
* @param msg The message
* @param e The exception stack
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logWarn(Logger logger, String msg, Throwable e) {
if (logDisable){
return;
}
try {
validateParam(logger, msg);
log(logger, Level.WARN, msg, e);
} catch (Exception ex) {
onException(ex);
}
}
/**
* Log the message for level(error)
*
* @param logger The logger
* @param msg The message
* @param e The exception stack
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logError(Logger logger, String msg, Throwable e) {
if (logDisable){
return;
}
try {
validateParam(logger, msg);
log(logger, Level.ERROR, msg, e);
} catch (Exception ex) {
onException(ex);
}
}
/**
* Log the message for level(debug)
*
* @param cls The class
* @param msg The message
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logDebug(Class cls, String msg) {
logDebug(cls, msg, null);
}
/**
* Log the message for level(info)
*
* @param cls The class
* @param msg The message
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logInfo(Class cls, String msg) {
logInfo(cls, msg, null);
}
/**
* Log the message for level(warn)
*
* @param cls The class
* @param msg The message
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logWarn(Class cls, String msg) {
logWarn(cls, msg, null);
}
/**
* Log the message for level(error)
*
* @param cls The class
* @param msg The message
* @throws IllegalArgumentException if logger or msg parameter is null.
*/
public static void logError(Class cls, String msg) {
logError(cls, msg, null);
}
/**
* Log the message for level(debug)
*
* @param cls The class
* @param msg The message
* @param e The exception stack
*/
public static void logDebug(Class cls, String msg, Throwable e) {
if (logDisable){
return;
}
try {
validateParam2(cls, msg);
Logger logger = Logger.getLogger(cls);
log(logger, Level.DEBUG, msg, e);
} catch (Exception ex) {
onException(ex);
}
}
/**
* Log the message for level(info)
*
* @param cls The class
* @param msg The message
* @param e The exception stack
* @throws IllegalArgumentException if class or msg parameter is null.
*/
public static void logInfo(Class cls, String msg, Throwable e) {
if (logDisable){
return;
}
try {
validateParam2(cls, msg);
Logger logger = Logger.getLogger(cls);
log(logger, Level.INFO, msg, e);
} catch (Exception ex) {
onException(ex);
}
}
/**
* Log the message for level(warn)
*
* @param cls The class
* @param msg The message
* @param e The exception stack
* @throws IllegalArgumentException if class or msg parameter is null.
*/
public static void logWarn(Class cls, String msg, Throwable e) {
if (logDisable){
return;
}
try {
validateParam2(cls, msg);
Logger logger = Logger.getLogger(cls);
log(logger, Level.WARN, msg, e);
} catch (Exception ex) {
onException(ex);
}
}
/**
* Log the message for level(error)
*
* @param cls The class
* @param msg The message
* @param e The exception stack
* @throws IllegalArgumentException if class or msg parameter is null.
*/
public static void logError(Class cls, String msg, Throwable e) {
if (logDisable){
return;
}
try {
validateParam2(cls, msg);
Logger logger = Logger.getLogger(cls);
log(logger, Level.ERROR, msg, e);
} catch (Exception ex) {
onException(ex);
}
}
/**
* Log the message for level(debug, info, warn, error)
*
* @param logger The logger
* @param msg The message
* @param e The exception stack
*/
private static void log(Logger logger, Level level, String msg, Throwable e) {
// Debug level
if (level == Level.DEBUG && logger.isDebugEnabled()) {
forcedLog(logger, org.apache.log4j.Level.DEBUG, org.apache.log4j.Level.DEBUG_INT, msg, e);
return;
}
// Info level
if (level == Level.INFO && logger.isInfoEnabled()) {
forcedLog(logger, org.apache.log4j.Level.INFO, org.apache.log4j.Level.INFO_INT, msg, e);
return;
}
// Warnning level
if (level == Level.WARN) {
forcedLog(logger, org.apache.log4j.Level.WARN, org.apache.log4j.Level.WARN_INT, msg, e);
return;
}
// Error level
if (level == Level.ERROR) {
forcedLog(logger, org.apache.log4j.Level.ERROR, org.apache.log4j.Level.ERROR_INT, msg, e);
return;
}
}
/**
* Overwrite Logger class metheds(info debug warn error forcedLog)
*
* @param logger log4j Logger instanse
* @param level log4j level
* @param levelInt log4j level number
* @param msg log message
* @param e the exception stack
*/
private static void forcedLog(Logger logger, Priority level, int levelInt, String msg, Throwable e) {
if (logger.getLoggerRepository().isDisabled(levelInt))
return;
LoggingEvent event = new LoggingEvent(JLogger.class.getName(), logger, level, msg, e);
event.setProperty(Constant.MGD_SVR_NAME, Util.getMgdSvrName());
event.setProperty(Constant.USER_CODE, Util.getUserCode());
logger.callAppenders(event);
}
/**
* Validate the parameter.
*
* @param logger The logger
* @param msg The message
*/
private static void validateParam(Logger logger, String msg) {
if (logger == null) {
throw new IllegalArgumentException("logger must be not null.");
}
if (msg == null || msg.trim().equals("")) {
throw new IllegalArgumentException("msg must be not null.");
}
}
/**
* Validate the parameter.
*
* @param cls The class
* @param msg The message
*/
private static void validateParam2(Class cls, String msg) {
if (cls == null) {
throw new IllegalArgumentException("clsss must be not null.");
}
if (msg == null || msg.trim().equals("")) {
throw new IllegalArgumentException("msg must be not null.");
}
}
/**
* Listen the exception happen.
* @param e The exception
*/
private static void onException(Exception e) {
System.out.println(e.getMessage());
//TODO:增加发送邮件或其他异常处理方式
}
private static String[] propKeys = {"log.parent.path","log.mail.subject"};
static{
ERPIni ini = new ERPIni();
for (String propKey : propKeys){
System.setProperty(propKey, ini.getValue(propKey));
}
}
}
使用这个封装,我们可以自由的对LoggingEvent类的实例属性进行控制。
下面是封装类的使用示例:
public class Class1 {
private static final Logger logger = JLogger.getLogger(Class1.class);
public static void main(String[] args) {
JLogger.logInfo(logger, "[Class1]this is log info ....");
}
}
最终的日志格式如下:
DefaultServer | 100580 | 2011-05-31 05:32:02 | com.jl.mc.test.Class1.cb1_action(Class1.java:35) | INFO | [Class1]this is log info ....