XxlJobFileAppender.java 4.8 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;
4 5 6 7
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Layout;
import org.apache.log4j.spi.LoggingEvent;

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

12 13 14 15 16 17
/**
 * store trigger log in each log-file
 * @author xuxueli 2016-3-12 19:25:12
 */
public class XxlJobFileAppender extends AppenderSkeleton {
	
X
init  
xueli.xue 已提交
18
	// for JobThread
19 20 21 22 23 24 25 26
	public static ThreadLocal<String> contextHolder = new ThreadLocal<String>();
	public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	
	// trogger log file path
	public static volatile String filePath;
	public void setFilePath(String filePath) {
		XxlJobFileAppender.filePath = filePath;
	}
X
xueli.xue 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

	/**
	 * log filename: yyyy-MM-dd/9999.log
	 *
	 * @param triggerDate
	 * @param logId
	 * @return
	 */
	public static String makeLogFileName(Date triggerDate, int logId) {

        // filePath/
        File filePathDir = new File(filePath);
        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;
	}

55 56
	@Override
	protected void append(LoggingEvent event) {
X
xueli.xue 已提交
57 58 59

		String logFileName = contextHolder.get();
		if (logFileName==null || logFileName.trim().length()==0) {
60 61
			return;
		}
X
xueli.xue 已提交
62 63
		File logFile = new File(filePath, logFileName);

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
		if (!logFile.exists()) {
			try {
				logFile.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
		}
		
		// append file content
		try {
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(logFile, true);
				fos.write(layout.format(event).getBytes("utf-8"));
				if (layout.ignoresThrowable()) {
					String[] throwableInfo = event.getThrowableStrRep();
					if (throwableInfo != null) {
						for (int i = 0; i < throwableInfo.length; i++) {
							fos.write(throwableInfo[i].getBytes("utf-8"));
							fos.write(Layout.LINE_SEP.getBytes("utf-8"));
						}
					}
				}
				fos.flush();
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			} 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean requiresLayout() {
		// TODO Auto-generated method stub
		return false;
	}
	
	/**
	 * support read log-file
X
xueli.xue 已提交
118
	 * @param logFileName
X
xueli.xue 已提交
119
	 * @return log content
120
	 */
X
xueli.xue 已提交
121
	public static LogResult readLog(String logFileName, int fromLineNum){
X
xueli.xue 已提交
122

X
xueli.xue 已提交
123
		// valid log file
X
xueli.xue 已提交
124
		if (logFileName==null || logFileName.trim().length()==0) {
125
            return new LogResult(fromLineNum, 0, "readLog fail, logFile not found", true);
126
		}
X
xueli.xue 已提交
127 128
		File logFile = new File(filePath, logFileName);

129
		if (!logFile.exists()) {
130
            return new LogResult(fromLineNum, 0, "readLog fail, logFile not exists", true);
131
		}
X
xueli.xue 已提交
132 133 134 135 136

		// read file
		StringBuffer logContentBuffer = new StringBuffer();
		int toLineNum = 0;
		LineNumberReader reader = null;
137
		try {
X
xueli.xue 已提交
138 139 140 141
			reader = new LineNumberReader(new FileReader(logFile));
			String line = null;

			while ((line = reader.readLine())!=null) {
142 143
				toLineNum = reader.getLineNumber();		// [from, to], start as 1
				if (toLineNum >= fromLineNum) {
X
xueli.xue 已提交
144
					logContentBuffer.append(line).append("\n");
145
				}
X
xueli.xue 已提交
146 147 148 149 150 151 152 153 154
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
155
				}
X
xueli.xue 已提交
156
			}
X
xueli.xue 已提交
157 158 159
		}

		// result
X
xueli.xue 已提交
160
		LogResult logResult = new LogResult(fromLineNum, toLineNum, logContentBuffer.toString(), false);
X
xueli.xue 已提交
161 162 163 164 165 166 167 168
		return logResult;

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

X
xueli.xue 已提交
171
	/**
X
xueli.xue 已提交
172
	 * read log data
X
xueli.xue 已提交
173
	 * @param logFile
X
xueli.xue 已提交
174
	 * @return log line content
X
xueli.xue 已提交
175
	 */
X
xueli.xue 已提交
176 177
	public static String readLines(File logFile){
		BufferedReader reader = null;
X
xueli.xue 已提交
178
		try {
X
xueli.xue 已提交
179 180 181 182 183 184
			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");
185
				}
X
xueli.xue 已提交
186
				return sb.toString();
X
xueli.xue 已提交
187 188
			}
		} catch (IOException e) {
189
			e.printStackTrace();
X
xueli.xue 已提交
190 191 192 193 194 195 196 197
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
X
xueli.xue 已提交
198
		} 
199
		return null;
X
xueli.xue 已提交
200 201
	}

202
}