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
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
6

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

11 12 13 14
/**
 * store trigger log in each log-file
 * @author xuxueli 2016-3-12 19:25:12
 */
X
xueli.xue 已提交
15 16
public class XxlJobFileAppender {
	private static Logger logger = LoggerFactory.getLogger(XxlJobFileAppender.class);
17
	
18
	// for JobThread (support log for child thread of job handler)
19
	//public static ThreadLocal<String> contextHolder = new ThreadLocal<String>();
许雪里's avatar
许雪里 已提交
20
	public static final InheritableThreadLocal<String> contextHolder = new InheritableThreadLocal<String>();
许雪里's avatar
许雪里 已提交
21 22
	public static String logPath = "/data/applogs/xxl-job/jobhandler/";

X
xueli.xue 已提交
23 24 25 26 27 28 29 30 31 32
	/**
	 * log filename: yyyy-MM-dd/9999.log
	 *
	 * @param triggerDate
	 * @param logId
	 * @return
	 */
	public static String makeLogFileName(Date triggerDate, int logId) {

        // filePath/
许雪里's avatar
许雪里 已提交
33
        File filePathDir = new File(logPath);
X
xueli.xue 已提交
34 35 36 37 38
        if (!filePathDir.exists()) {
            filePathDir.mkdirs();
        }

        // filePath/yyyy-MM-dd/
许雪里's avatar
许雪里 已提交
39 40
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");	// avoid concurrent problem, can not be static

X
xueli.xue 已提交
41 42 43 44 45 46 47
        String nowFormat = sdf.format(new Date());
        File filePathDateDir = new File(filePathDir, nowFormat);
        if (!filePathDateDir.exists()) {
            filePathDateDir.mkdirs();
        }

        // filePath/yyyy-MM-dd/9999.log
许雪里's avatar
许雪里 已提交
48
		String logFileName = sdf.format(triggerDate).concat("/").concat(String.valueOf(logId)).concat(".log");
X
xueli.xue 已提交
49 50 51
		return logFileName;
	}

X
xueli.xue 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64
	/**
	 * 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 已提交
65

X
xueli.xue 已提交
66
		// log file
X
xueli.xue 已提交
67
		if (logFileName==null || logFileName.trim().length()==0) {
68 69
			return;
		}
许雪里's avatar
许雪里 已提交
70
		File logFile = new File(logPath, logFileName);
X
xueli.xue 已提交
71

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

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

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

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

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

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

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

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

X
xueli.xue 已提交
160
	/**
X
xueli.xue 已提交
161
	 * read log data
X
xueli.xue 已提交
162
	 * @param logFile
X
xueli.xue 已提交
163
	 * @return log line content
X
xueli.xue 已提交
164
	 */
X
xueli.xue 已提交
165 166
	public static String readLines(File logFile){
		BufferedReader reader = null;
X
xueli.xue 已提交
167
		try {
X
xueli.xue 已提交
168 169 170 171 172 173
			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");
174
				}
X
xueli.xue 已提交
175
				return sb.toString();
X
xueli.xue 已提交
176 177
			}
		} catch (IOException e) {
许雪里's avatar
许雪里 已提交
178
			logger.error(e.getMessage(), e);
X
xueli.xue 已提交
179 180 181 182 183
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
许雪里's avatar
许雪里 已提交
184
					logger.error(e.getMessage(), e);
X
xueli.xue 已提交
185 186
				}
			}
X
xueli.xue 已提交
187
		}
188
		return null;
X
xueli.xue 已提交
189 190
	}

191
}