import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import java.util.Date;
public class DeploymentTaskLogger {
/**
* 日志前面的时间格式
*/
private final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss SSS";
/**
* 单条日志的最大长度
*/
private final int SINGLE_LOG_MAX_LENGTH = 250;
private final StringBuilder builder = new StringBuilder();
private boolean hasChange;
public DeploymentTaskLogger() {
}
public DeploymentTaskLogger log(String info){
//删除字符串最后一个换行符
StringUtils.chomp(info);
hasChange = true;
if (info.length() > SINGLE_LOG_MAX_LENGTH){
builder.append(getDateTime()).append(" ").append(info, 0, SINGLE_LOG_MAX_LENGTH).append("...").append("\n");
return this;
}
builder.append(getDateTime()).append(" ").append(info).append("\n");
return this;
}
private String getDateTime(){
return DateFormatUtils.format(new Date(), DATE_FORMAT);
}
public String getLog(){
return builder.toString();
}
public boolean hasChange(){
boolean flag = hasChange;
hasChange = false;
return flag;
}
}
用法:
添加日志
taskLogger.log(String.format("执行后置命令");