log4j 一直有个问题无法满足我,有可能我还不知道怎么去使用它。
就是他会把项目中所有的日志信息都记到一个文件里面,而业务系统往往需要根据某个业务流程查看日志分析。
public class BusinessLogUtil {
public enum Level {
ERROR(40, "ERROR"),
WARN(30, "WARN"),
INFO(20, "INFO"),
DEBUG(10, "DEBUG"),
TRACE(0, "TRACE");
private int levelInt;
private String levelStr;
private Level(int i, String s) {
this.levelInt = i;
this.levelStr = s;
}
public int toInt() {
return this.levelInt;
}
@Override
public String toString() {
return this.levelStr;
}
}
/**
* 得到记录日志所有的文件:行号
*
* @return
*/
private static String getLineInfo() {
StackTraceElement ste = new Throwable().getStackTrace()[3];
return MessageFormat.format("[{0}:{1}]", ste.getClassName(), ste.getLineNumber());
}
/**
* 记录日志信息
*
* @param businessName
* @param content
*/
private void write(String businessName, Level logLevel, String content) {
String logKey = businessName;
if (logKey.contains("_")) {
logKey = logKey.split("_")[0];
}
boolean isContinue = true; //TODO 此处根据 businessName 去数据库里面看这个业务日志有没有要求开启
if (!isContinue) {
//如果Elb_Settings 没开启开关,则不记录日志
return;
}
FileOutputStream out = null;
BufferedOutputStream Buff = null;
try {
Date currentDate = new Date();
String logRoot = System.getProperty("catalina.home");
if (StringUtil.isNullOrEmpty(logRoot)) {
logRoot = "";
}
String fileName = logRoot + "/logs/" + businessName + "_" + logLevel.levelStr.toLowerCase() + "." + com.iron.fast.util.DateUtil.toFormatString("yyyy-MM-dd", currentDate) + ".log";
out = new FileOutputStream(fileName, true);
Buff = new BufferedOutputStream(out);
String msg = MessageFormat.format("{0} {1} {2} - {3}\r\n", DateUtil.toFormatString("yyyy-MM-dd HH:mm:ss", currentDate), logLevel.levelStr, getLineInfo(), content);
Buff.write(msg.getBytes("utf-8"));
Buff.flush();
Buff.close();
} catch (Exception var15) {
var15.printStackTrace();
} finally {
try {
Buff.close();
out.close();
} catch (Exception var14) {
var14.printStackTrace();
}
}
}
/**
* 业务日志
*
* @param businessName
* @param content
*/
public void info(String businessName, String content) {
write(businessName, Level.INFO, content);
}
/**
* 警告日志,同时也会记录到 info 中
*
* @param businessName
* @param content
*/
public void warn(String businessName, String content) {
write(businessName, Level.WARN, content);
write(businessName, Level.WARN, content);
}
/**
* 错误日志,同时也会记录到 info 中,warn 中不记
*
* @param businessName
* @param content
*/
public void error(String businessName, String content) {
write(businessName, Level.ERROR, content);
write(businessName, Level.ERROR, content);
}
}

来源:https://www.cnblogs.com/vipsoft/p/10984476.html