XxlJobFileAppender.java 4.7 KB
Newer Older
X
xueli.xue 已提交
1
package com.xxl.job.core.log;
2

X
xueli.xue 已提交
3
import com.xxl.job.core.biz.model.LogResult;
X
xueli.xue 已提交
4 5 6
import com.xxl.job.core.executor.XxlJobExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
7

X
init  
xueli.xue 已提交
8 9 10 11
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

12 13 14 15
/**
 * store trigger log in each log-file
 * @author xuxueli 2016-3-12 19:25:12
 */
X
xueli.xue 已提交
16 17
public class XxlJobFileAppender {
	private static Logger logger = LoggerFactory.getLogger(XxlJobFileAppender.class);
18
	
19 20 21
	// for JobThread (support log for child thread)
	//public static ThreadLocal<String> contextHolder = new ThreadLocal<String>();
	public static InheritableThreadLocal<String> contextHolder = new InheritableThreadLocal<String>();
22 23
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
X
xueli.xue 已提交
24 25 26 27 28 29 30 31 32 33
	/**
	 * log filename: yyyy-MM-dd/9999.log
	 *
	 * @param triggerDate
	 * @param logId
	 * @return
	 */
	public static String makeLogFileName(Date triggerDate, int logId) {

        // filePath/
X
xueli.xue 已提交
34
        File filePathDir = new File(XxlJobExecutor.logPath);
X
xueli.xue 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
        if (!filePathDir.exists()) {
            filePathDir.mkdirs();
        }

        // filePath/yyyy-MM-dd/
        String nowFormat = sdf.format(new Date());
        File filePathDateDir = new File(filePathDir, nowFormat);
        if (!filePathDateDir.exists()) {
            filePathDateDir.mkdirs();
        }

        // filePath/yyyy-MM-dd/9999.log
		String logFileName = XxlJobFileAppender.sdf.format(triggerDate).concat("/").concat(String.valueOf(logId)).concat(".log");
		return logFileName;
	}

X
xueli.xue 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63
	/**
	 * append log
	 *
	 * @param logFileName
	 * @param appendLog
	 */
	public static void appendLog(String logFileName, String appendLog) {

		// log
		if (appendLog == null) {
			appendLog = "";
		}
		appendLog += "\r\n";
X
xueli.xue 已提交
64

X
xueli.xue 已提交
65
		// log file
X
xueli.xue 已提交
66
		if (logFileName==null || logFileName.trim().length()==0) {
67 68
			return;
		}
X
xueli.xue 已提交
69
		File logFile = new File(XxlJobExecutor.logPath, logFileName);
X
xueli.xue 已提交
70

71 72 73 74
		if (!logFile.exists()) {
			try {
				logFile.createNewFile();
			} catch (IOException e) {
X
xueli.xue 已提交
75
				logger.error(e.getMessage(), e);
76 77 78 79 80 81 82 83 84
				return;
			}
		}
		
		// append file content
		try {
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(logFile, true);
X
xueli.xue 已提交
85
				fos.write(appendLog.getBytes("utf-8"));
86 87 88 89 90 91
				fos.flush();
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
X
xueli.xue 已提交
92
						logger.error(e.getMessage(), e);
93 94 95 96
					}
				}
			} 
		} catch (Exception e) {
X
xueli.xue 已提交
97
			logger.error(e.getMessage(), e);
98 99 100 101 102 103
		}
		
	}

	/**
	 * support read log-file
X
xueli.xue 已提交
104
	 *
X
xueli.xue 已提交
105
	 * @param logFileName
X
xueli.xue 已提交
106
	 * @return log content
107
	 */
X
xueli.xue 已提交
108
	public static LogResult readLog(String logFileName, int fromLineNum){
X
xueli.xue 已提交
109

X
xueli.xue 已提交
110
		// valid log file
X
xueli.xue 已提交
111
		if (logFileName==null || logFileName.trim().length()==0) {
112
            return new LogResult(fromLineNum, 0, "readLog fail, logFile not found", true);
113
		}
X
xueli.xue 已提交
114
		File logFile = new File(XxlJobExecutor.logPath, logFileName);
X
xueli.xue 已提交
115

116
		if (!logFile.exists()) {
117
            return new LogResult(fromLineNum, 0, "readLog fail, logFile not exists", true);
118
		}
X
xueli.xue 已提交
119 120 121 122 123

		// read file
		StringBuffer logContentBuffer = new StringBuffer();
		int toLineNum = 0;
		LineNumberReader reader = null;
124
		try {
125 126
			//reader = new LineNumberReader(new FileReader(logFile));
			reader = new LineNumberReader(new InputStreamReader(new FileInputStream(logFile), "utf-8"));
X
xueli.xue 已提交
127 128 129
			String line = null;

			while ((line = reader.readLine())!=null) {
130 131
				toLineNum = reader.getLineNumber();		// [from, to], start as 1
				if (toLineNum >= fromLineNum) {
X
xueli.xue 已提交
132
					logContentBuffer.append(line).append("\n");
133
				}
X
xueli.xue 已提交
134 135
			}
		} catch (IOException e) {
X
xueli.xue 已提交
136
			logger.error(e.getMessage(), e);
X
xueli.xue 已提交
137 138 139 140 141
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
X
xueli.xue 已提交
142
					logger.error(e.getMessage(), e);
143
				}
X
xueli.xue 已提交
144
			}
X
xueli.xue 已提交
145 146 147
		}

		// result
X
xueli.xue 已提交
148
		LogResult logResult = new LogResult(fromLineNum, toLineNum, logContentBuffer.toString(), false);
X
xueli.xue 已提交
149 150 151 152 153 154 155 156
		return logResult;

		/*
        // it will return the number of characters actually skipped
        reader.skip(Long.MAX_VALUE);
        int maxLineNum = reader.getLineNumber();
        maxLineNum++;	// 最大行号
        */
X
xueli.xue 已提交
157
	}
X
xueli.xue 已提交
158

X
xueli.xue 已提交
159
	/**
X
xueli.xue 已提交
160
	 * read log data
X
xueli.xue 已提交
161
	 * @param logFile
X
xueli.xue 已提交
162
	 * @return log line content
X
xueli.xue 已提交
163
	 */
X
xueli.xue 已提交
164 165
	public static String readLines(File logFile){
		BufferedReader reader = null;
X
xueli.xue 已提交
166
		try {
X
xueli.xue 已提交
167 168 169 170 171 172
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(logFile), "utf-8"));
			if (reader != null) {
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line).append("\n");
173
				}
X
xueli.xue 已提交
174
				return sb.toString();
X
xueli.xue 已提交
175 176
			}
		} catch (IOException e) {
177
			e.printStackTrace();
X
xueli.xue 已提交
178 179 180 181 182 183 184 185
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
X
xueli.xue 已提交
186
		}
187
		return null;
X
xueli.xue 已提交
188 189
	}

190
}