import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
public class WriteLogService {
private static final Logger log = LoggerFactory.getLogger(WriteLogService.class);
public static void main(String[] args) {
// //当前时间,文件名称, 文件路径, code , msg , 方法名称, 操作人
logger("/Users/xxxx/data/cpd", "abcd.txt","{\"id\":1,\"finish_flag\":1}\ttrue\tsuccess\txxxService\txxxx", "\t", "content json\tstatus\tmsg\tmethod\toperator");
}
/**
* 自定义业务log日志
* @param logPath 输出地址
* @param fileName 文件名字带后缀名
* @param params 要输出的列内容按splitStr分隔
* @param splitStr 根据什么分隔
* @param columnNamesStr 列明title按splitStr分隔
* @throws IOException
*/
public static void logger (String logPath, String fileName, String params, String splitStr, String columnNamesStr) {
FileOutputStream fw = null;
Writer out = null;
SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String trace = sdfs.format(new Date().getTime());//定义一个系统时间
logPath = logPath + File.separator + sdf.format(new Date());
String logFile = logPath + File.separator + fileName;
try {
// 如果文本文件不存在则创建它
Path logFilePath = Paths.get(logFile);
StringBuilder sf = new StringBuilder();
File file = new File(logPath);
if (!file.exists()) {//检测是否有logger.TXT文件
file.mkdir();
}
if (!logFilePath.toFile().exists()) {
logFilePath.toFile().createNewFile();
sf.append("CreateTime");
String[] strData = columnNamesStr.split(splitStr);
for (String str : strData) {
sf.append("\t");
sf.append(str);
}
}
fw = new FileOutputStream(logFilePath.toFile(), true);
out = new OutputStreamWriter(fw, "UTF-8");//设置字符集编码格式
out.write(sf.toString());
String newFile1 = System.getProperty("line.separator");
out.write(newFile1);
StringBuilder sf1 = new StringBuilder();
sf1.append(trace);
String[] strData = params.split(splitStr);
for (String str : strData) {
sf1.append("\t");
sf1.append(str);
}
String newFile = System.getProperty("line.separator");
out.write(newFile);
out.write(sf1.toString());
}catch (Exception e) {
log.error("WriteLogService logger error", e);
}finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
log.error("WriteLogService log out finally error ", e);
}
}
if(fw != null) {
try{
fw.flush();
fw.close();
}catch (IOException e) {
log.error("WriteLogService log fw finally error ", e);
}
}
}
}
}