引入log4j-x.x.xx.jar、slf4j-api-x.x.xx.jar两个jar包。
1.定义抽象类AbstractLayout :
public abstract class AbstractLayout extends Layout {
protected final static DateFormat dateFormat = new SimpleDateFormat("yyMMdd HH:mm:ss,SSS");
private String header = "";
public void setHeader(String header) {
if (header == null)
return;
this.header = header;
}
public String getHeader() {
return this.header;
}
}
2.自定义日志打印格式:
/**
*
* 自定义日志打印格式
*
*/
public class ContextFileAppendLayout extends AbstractLayout {
public void activateOptions() {
}
public String format(LoggingEvent event) {
Date date = new Date(event.timeStamp);
String msg = event.getRenderedMessage();
if (msg == null) {
msg = "";
}
StringBuffer buf = new StringBuffer(msg.length() + 100);
buf.append(dateFormat.format(date)).append("\t");
buf.append(event.getLevel()).append("\t");
buf.append(msg).append("\r\n");
if (event.getThrowableStrRep() != null) {
String[] rows = event.getThrowableStrRep();
for (int i = 0; i < rows.length; ++i) {
buf.append(rows[i]).append("\r\n");
}
}
return buf.toString();
}
public boolean ignoresThrowable() {
return false;
}
}
3.LogFactory:
public class LogFactory {
private final static Level serviceLogLevel = Logger.getLogger("com.suntek.eap.service").getLevel();
private final static Level timerLogLevel = Logger.getLogger("com.suntek.eap.server.timer").getLevel();
private final static Map<String, Logger> serviceLoggers = new ConcurrentHashMap();
public static Logger getServiceLog(String moduleName) {
if (serviceLoggers.containsKey(moduleName)) {
return serviceLoggers.get(moduleName);
}
Logger log = initLogger(moduleName);
serviceLoggers.put(moduleName, log);
return log;
}
public static TimerLog getTimerLog(String timerName) {
if (timerLoggers.containsKey(timerName)) {
return timerLoggers.get(timerName);
}
Logger log = initLogger(timerName);
TimerLog timerLog = new TimerLog(timerName, log);
timerLoggers.put(timerName, timerLog);
return timerLog;
}
private synchronized static Logger initLogger(String moduleName) {
Layout layout = new ContextFileAppendLayout();
String logFilePath = SystemConfig.getProperty("user.dir") + "/logs/" + moduleName + ".log";
Appender appender;
try {
appender = new RollingFileAppender(layout, logFilePath, true);
} catch (IOException e) {
throw new RuntimeException("获取日志失败,创建日志文件失败!");
}
return newALogger(moduleName, appender);
}
private static Logger newALogger(String logName, Appender appender) {
Logger logger = Logger.getLogger(logName);
logger.removeAllAppenders();
logger.addAppender(appender);
if (logName.toUpperCase().contains("TIMER")) {
logger.setLevel(timerLogLevel);
} else {
logger.setLevel(serviceLogLevel);
}
return logger;
}
}
4.工具类:
public class Log {
public static Logger log = LogFactory.getServiceLog("myLog");
}
5.使用方法:
public static void main(String[] args) {
Log.log.debug("hello world");
}