主頁 >  其他 > 改造xxl-job的客戶端日志檔案生成體系

改造xxl-job的客戶端日志檔案生成體系

2021-02-05 07:15:50 其他

為什么要改造XXL-JOB原有的日志檔案生成體系

?  xxl-job原本自己的客戶端日志檔案生成策略是:一個日志記錄就生成一個檔案,也就是當資料庫存在一條日志logId,對應的客戶端就會生成一個檔案,由于定時任務跑批很多,并且有些任務間隔時間很短,比如幾秒觸發一次,這樣的結果就是客戶端會生成大量的檔案,但是每個檔案的內容其實不多,但大量的單獨檔案相比會占用更多的磁盤,造成磁盤資源緊張,同時對檔案系統性能存在影響,長久以來,就會觸發資源報警,所以,如果不想經常去清理日志檔案的話,那么將零碎的檔案通過某種方式進行整合就顯得迫切需要了,

本文篇幅較長,代碼涉及較多啦~

改造后的日志檔案生成策略

基本描述

?  減少日志檔案個數,其實就是要將分散的日志檔案進行合并,同時建立外部索引檔案維護各自當次日志Id所對應的起始日志內容,在讀取的時候先通過讀取索引檔案,進而再讀取真實的日志內容,

?  下面是日志檔案描述分析圖:

  • 對于一個執行器,在執行器下的所有的定時任務每天只生成一個logId_jobId_index.log的索引檔案,用來維護日志Id與任務Id的對應關系;

  • 對于一個定時任務,每天只生成一個jobId.log的日志內容檔案,里面保存當天所有的日志內容;

  • 對于日志索引檔案jobId_index.log,用來維護日志內容中的索引,便于知道jobId.log中對應行數是屬于哪個logId的,便于查找,

?  大致思路就是如此,可以預期,日志檔案大大的減少,磁盤占用應該會得到改善.

?  筆者改造的這個功能已經在線上跑了快接近一年了,目前暫未出現問題,如有需要可結合自身業務進行相應的調整與改造,以及認真測驗,以防未知錯誤,

代碼實操

本文改造是基于XXL-JOB 1.8.2 版本改造,其他版本暫未實驗

?  打開代碼目錄xxl-job-core模塊,主要涉及以下幾個檔案的改動:

  • XxlJobFileAppender.java
  • XxlJobLogger.java
  • JobThread.java
  • ExecutorBizImpl.java
  • LRUCacheUtil.java

XxlJobFileAppender.java

?  代碼中部分原有未涉及改動的方法此處不再粘貼,

package com.xxl.job.core.log;

import com.xxl.job.core.biz.model.LogResult;
import com.xxl.job.core.util.LRUCacheUtil;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * store trigger log in each log-file
 * @author xuxueli 2016-3-12 19:25:12
 */
public class XxlJobFileAppender {
	private static Logger logger = LoggerFactory.getLogger(XxlJobFileAppender.class);

	// for JobThread (support log for child thread of job handler)
	//public static ThreadLocal<String> contextHolder = new ThreadLocal<String>();
	public static final InheritableThreadLocal<String> contextHolder = new InheritableThreadLocal<String>();
	// for logId,記錄日志Id
	public static final InheritableThreadLocal<Integer> contextHolderLogId = new InheritableThreadLocal<>();
	// for JobId,定時任務的Id
	public static final InheritableThreadLocal<Integer> contextHolderJobId = new InheritableThreadLocal<>();

	// 使用一個快取map集合來存取索引偏移量資訊
	public static final LRUCacheUtil<Integer, Map<String ,Long>> indexOffsetCacheMap = new LRUCacheUtil<>(80);

	private static final String DATE_FOMATE = "yyyy-MM-dd";

	private static final String UTF_8 = "utf-8";

	// 檔案名后綴
	private static final String FILE_SUFFIX = ".log";

	private static final String INDEX_SUFFIX = "_index";

	private static final String LOGID_JOBID_INDEX_SUFFIX = "logId_jobId_index";

	private static final String jobLogIndexKey = "jobLogIndexOffset";

	private static final String indexOffsetKey = "indexOffset";

	/**
	 * log base path
	 *
	 * strut like:
	 * 	---/
	 * 	---/gluesource/
	 * 	---/gluesource/10_1514171108000.js
	 * 	---/gluesource/10_1514171108000.js
	 * 	---/2017-12-25/
	 * 	---/2017-12-25/639.log
	 * 	---/2017-12-25/821.log
	 *
	 */
	private static String logBasePath = "/data/applogs/xxl-job/jobhandler";
	private static String glueSrcPath = logBasePath.concat("/gluesource");
	public static void initLogPath(String logPath){
		// init
		if (logPath!=null && logPath.trim().length()>0) {
			logBasePath = logPath;
		}
		// mk base dir
		File logPathDir = new File(logBasePath);
		if (!logPathDir.exists()) {
			logPathDir.mkdirs();
		}
		logBasePath = logPathDir.getPath();

		// mk glue dir
		File glueBaseDir = new File(logPathDir, "gluesource");
		if (!glueBaseDir.exists()) {
			glueBaseDir.mkdirs();
		}
		glueSrcPath = glueBaseDir.getPath();
	}
	public static String getLogPath() {
		return logBasePath;
	}
	public static String getGlueSrcPath() {
		return glueSrcPath;
	}

	/**
	 * 重寫生成日志目錄和日志檔案名的方法:
	 * log filename,like "logPath/yyyy-MM-dd/jobId.log"
	 * @param triggerDate
	 * @param jobId
	 * @return
	 */
	public static String makeLogFileNameByJobId(Date triggerDate, int jobId) {

		// filePath/yyyy-MM-dd
		// avoid concurrent problem, can not be static
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FOMATE);
		File logFilePath = new File(getLogPath(), sdf.format(triggerDate));
		if (!logFilePath.exists()) {
			logFilePath.mkdir();
		}
		// 生成日志索引檔案
		String logIndexFileName = logFilePath.getPath()
				.concat("/")
				.concat(String.valueOf(jobId))
				.concat(INDEX_SUFFIX)
				.concat(FILE_SUFFIX);
		File logIndexFilePath = new File(logIndexFileName);
		if (!logIndexFilePath.exists()) {
			try {
				logIndexFilePath.createNewFile();
				logger.debug("生成日志索引檔案,檔案路徑:{}", logIndexFilePath);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		// 在yyyy-MM-dd檔案夾下生成當天的logId對應的jobId的全域索引,減少對后管的修改
		String logIdJobIdIndexFileName = logFilePath.getPath()
				.concat("/")
				.concat(LOGID_JOBID_INDEX_SUFFIX)
				.concat(FILE_SUFFIX);
		File logIdJobIdIndexFileNamePath = new File(logIdJobIdIndexFileName);
		if (!logIdJobIdIndexFileNamePath.exists()) {
			try {
				logIdJobIdIndexFileNamePath.createNewFile();
				logger.debug("生成logId與jobId的索引檔案,檔案路徑:{}", logIdJobIdIndexFileNamePath);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		// filePath/yyyy-MM-dd/jobId.log log日志檔案
		String logFileName = logFilePath.getPath()
				.concat("/")
				.concat(String.valueOf(jobId))
				.concat(FILE_SUFFIX);
		return logFileName;
	}


	/**
	 * 后管平臺讀取詳細日志查看,生成檔案名
	 * admin read log, generate logFileName bu logId
	 * @param triggerDate
	 * @param logId
	 * @return
	 */
	public static String makeFileNameForReadLog(Date triggerDate, int logId) {
		// filePath/yyyy-MM-dd
		SimpleDateFormat sdf = new SimpleDateFormat(DATE_FOMATE);
		File logFilePath = new File(getLogPath(), sdf.format(triggerDate));
		if (!logFilePath.exists()) {
			logFilePath.mkdir();
		}
		String logIdJobIdFileName = logFilePath.getPath().concat("/")
				.concat(LOGID_JOBID_INDEX_SUFFIX)
				.concat(FILE_SUFFIX);
		// find logId->jobId mapping
		// 獲取索引映射
		String infoLine = readIndex(logIdJobIdFileName, logId);
		String[] arr = infoLine.split("->");
		int jobId = 0;
		try {
			jobId = Integer.parseInt(arr[1]);
		} catch (Exception e) {
			logger.error("makeFileNameForReadLog StringArrayException,{},{}", e.getMessage(), e);
			throw new RuntimeException("StringArrayException");
		}
		String logFileName = logFilePath.getPath().concat("/")
				.concat(String.valueOf(jobId)).concat(FILE_SUFFIX);
		return logFileName;
	}

	/**
	 * 向日志檔案中追加內容,向索引檔案中追加索引
	 * append log
	 * @param logFileName
	 * @param appendLog
	 */
	public static void appendLogAndIndex(String logFileName, String appendLog) {

		// log file
		if (logFileName == null || logFileName.trim().length() == 0) {
			return;
		}
		File logFile = new File(logFileName);

		if (!logFile.exists()) {
			try {
				logFile.createNewFile();
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				return;
			}
		}
		// start append, count line num
		long startLineNum = countFileLineNum(logFileName);
		logger.debug("開始追加日志檔案,開始行數:{}", startLineNum);
		// log
		if (appendLog == null) {
			appendLog = "";
		}
		appendLog += "\r\n";

		// append file content
		try {
			FileOutputStream fos = null;
			try {
				fos = new FileOutputStream(logFile, true);
				fos.write(appendLog.getBytes("utf-8"));
				fos.flush();
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						logger.error(e.getMessage(), e);
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		// end append, count line num,再次計數
		long endLineNum = countFileLineNum(logFileName);
		Long lengthTmp = endLineNum - startLineNum;
		int length = 0;
		try {
			length = lengthTmp.intValue();
		} catch (Exception e) {
			logger.error("Long to int Exception", e);
		}
		logger.debug("結束追加日志檔案,結束行數:{}, 長度:{}", endLineNum, length);
		Map<String, Long> indexOffsetMap = new HashMap<>();
		appendIndexLog(logFileName, startLineNum, length, indexOffsetMap);
		appendLogIdJobIdFile(logFileName, indexOffsetMap);
	}


	/**
	 * 創建日志Id與JobId的映射關系
	 * @param logFileName
	 * @param indexOffsetMap
	 */
	public static void appendLogIdJobIdFile(String logFileName, Map indexOffsetMap) {
		// 獲取ThreadLocal中變數保存的值
		int logId = XxlJobFileAppender.contextHolderLogId.get();
		int jobId = XxlJobFileAppender.contextHolderJobId.get();
		File file = new File(logFileName);
		// 獲取父級目錄,尋找同檔案夾下的索引檔案
		String parentDirName = file.getParent();
		// logId_jobId_index fileName
		String logIdJobIdIndexFileName = parentDirName.concat("/")
				.concat(LOGID_JOBID_INDEX_SUFFIX)
				.concat(FILE_SUFFIX);
		// 從快取中獲取logId
		boolean jobLogIndexOffsetExist = indexOffsetCacheMap.exists(logId);
		Long jobLogIndexOffset = null;
		if (jobLogIndexOffsetExist) {
			jobLogIndexOffset = indexOffsetCacheMap.get(logId).get(jobLogIndexKey);
		}
		if (jobLogIndexOffset == null) {
			// 為空則添加
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append(logId).append("->").append(jobId).append("\r\n");
			Long currentPoint = getAfterAppendIndexLog(logIdJobIdIndexFileName, stringBuffer.toString());
			indexOffsetMap.put(jobLogIndexKey, currentPoint);
			indexOffsetCacheMap.save(logId, indexOffsetMap);
		}
		// 不為空說明快取已經存在,不做其他處理
	}

	/**
	 * 追加索引檔案內容,回傳偏移量
	 * @param fileName
	 * @param content
	 * @return
	 */
	private static Long getAfterAppendIndexLog(String fileName, String content) {
		RandomAccessFile raf = null;
		Long point = null;
		try {
			raf = new RandomAccessFile(fileName, "rw");
			long end = raf.length();
			// 因為是追加內容,所以將指標放入到檔案的末尾
			raf.seek(end);
			raf.writeBytes(content);
			// 獲取當前的指標偏移量
			/**
			 * 偏移量放入到快取變數中:注意,此處獲取偏移量,是獲取開始的地方的偏移量,不能再追加內容后再獲取,否則會獲取到結束
			 * 時的偏移量
			 */
			point = end;
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				raf.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return point;
	}

	/**
	 * 追加索引日志,like "345->(577,10)"
	 * @param logFileName
	 * @param from
	 * @param length
	 * @param indexOffsetMap
	 */
	public static void appendIndexLog(String logFileName, Long from, int length, Map indexOffsetMap) {
		int strLength = logFileName.length();
		// 通過截取獲取索引檔案名
		String prefixFilePath = logFileName.substring(0, strLength - 4);
		String logIndexFilePath = prefixFilePath.concat(INDEX_SUFFIX).concat(FILE_SUFFIX);
		File logIndexFile = new File(logIndexFilePath);
		if (!logIndexFile.exists()) {
			try {
				logIndexFile.createNewFile();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				return;
			}
		}
		int logId = XxlJobFileAppender.contextHolderLogId.get();

		StringBuffer stringBuffer = new StringBuffer();
		// 判斷是添加還是修改
		boolean indexOffsetExist = indexOffsetCacheMap.exists(logId);
		Long indexOffset = null;
		if (indexOffsetExist) {
			indexOffset = indexOffsetCacheMap.get(logId).get(indexOffsetKey);
		}
		if (indexOffset == null) {
			// append
			String lengthStr = getFormatNum(length);
			stringBuffer.append(logId).append("->(")
					.append(from).append(",").append(lengthStr).append(")\r\n");
			// 添加新的索引,記錄偏移量
			Long currentIndexPoint = getAfterAppendIndexLog(logIndexFilePath, stringBuffer.toString());
			indexOffsetMap.put(indexOffsetKey, currentIndexPoint);
		} else {
			String infoLine = getIndexLineIsExist(logIndexFilePath, logId);
			// 修改索引檔案內容
			int startTmp = infoLine.indexOf("(");
			int endTmp = infoLine.indexOf(")");
			String[] lengthTmp = infoLine.substring(startTmp + 1, endTmp).split(",");
			int lengthTmpInt = 0;
			try {
				lengthTmpInt = Integer.parseInt(lengthTmp[1]);
				from = Long.valueOf(lengthTmp[0]);
			} catch (Exception e) {
				logger.error("appendIndexLog StringArrayException,{},{}", e.getMessage(), e);
				throw new RuntimeException("StringArrayException");
			}
			int modifyLength = length + lengthTmpInt;
			String lengthStr2 = getFormatNum(modifyLength);
			stringBuffer.append(logId).append("->(")
					.append(from).append(",").append(lengthStr2).append(")\r\n");
			modifyIndexFileContent(logIndexFilePath, infoLine, stringBuffer.toString());
		}
	}

	/**
	 * handle getFormatNum
	 * like 5 to 005
	 * @return
	 */
	private static String getFormatNum(int num) {
		DecimalFormat df = new DecimalFormat("000");
		String str1 = df.format(num);
		return str1;
	}

	/**
	 * 查詢索引是否存在
	 * @param filePath
	 * @param logId
	 * @return
	 */
	private static String getIndexLineIsExist(String filePath, int logId) {
		// 讀取索引問價判斷是否存在,日志每生成一行就會呼叫一次,所以索引檔案需要將同一個logId對應的進行合并
		String prefix = logId + "->";
		Pattern pattern = Pattern.compile(prefix + ".*?");
		String indexInfoLine = "";
		RandomAccessFile raf = null;
		try {
			raf = new RandomAccessFile(filePath, "rw");
			String tmpLine = null;
			// 偏移量
			boolean indexOffsetExist = indexOffsetCacheMap.exists(logId);
			Long cachePoint = null;
			if (indexOffsetExist) {
				cachePoint = indexOffsetCacheMap.get(logId).get(indexOffsetKey);
			}
			if (null == cachePoint) {
				cachePoint = Long.valueOf(0);
			}
			raf.seek(cachePoint);
			while ((tmpLine = raf.readLine()) != null) {
				final long point = raf.getFilePointer();
				boolean matchFlag = pattern.matcher(tmpLine).find();
				if (matchFlag) {
					indexInfoLine = tmpLine;
					break;
				}
				cachePoint = point;
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				raf.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return indexInfoLine;
	}

	/**
	 * 在后管頁面上需要查詢執行日志的時候,獲取索引資訊,
	 * 此處不能與上個通用,因為讀取時沒有map存取偏移量資訊,相對隔離
	 * @param filePath
	 * @param logId
	 * @return
	 */
	private static String readIndex(String filePath, int logId) {
		filePath = FilenameUtils.normalize(filePath);
		String prefix = logId + "->";
		Pattern pattern = Pattern.compile(prefix + ".*?");
		String indexInfoLine = "";
		BufferedReader bufferedReader = null;
		try {
			bufferedReader = new BufferedReader(new FileReader(filePath));
			String tmpLine = null;
			while ((tmpLine = bufferedReader.readLine()) != null) {
				boolean matchFlag = pattern.matcher(tmpLine).find();
				if (matchFlag) {
					indexInfoLine = tmpLine;
					break;
				}
			}
			bufferedReader.close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		return indexInfoLine;
	}

	/**
	 * 修改 logIndexFile 內容
	 * @param indexFileName
	 * @param oldContent
	 * @param newContent
	 * @return
	 */
	private static boolean modifyIndexFileContent(String indexFileName, String oldContent, String newContent) {
		RandomAccessFile raf = null;
		int logId = contextHolderLogId.get();
		try {
			raf = new RandomAccessFile(indexFileName, "rw");
			String tmpLine = null;
			// 偏移量
			boolean indexOffsetExist = indexOffsetCacheMap.exists(logId);
			Long cachePoint = null;
			if (indexOffsetExist) {
				cachePoint = indexOffsetCacheMap.get(logId).get(indexOffsetKey);
			}
			if (null == cachePoint) {
				cachePoint = Long.valueOf(0);
			}
			raf.seek(cachePoint);
			while ((tmpLine = raf.readLine()) != null) {
				final long point = raf.getFilePointer();
				if (tmpLine.contains(oldContent)) {
					String str = tmpLine.replace(oldContent, newContent);
					raf.seek(cachePoint);
					raf.writeBytes(str);
				}
				cachePoint = point;
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				raf.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return true;
	}

	/**
	 * 統計檔案內容行數
	 * @param logFileName
	 * @return
	 */
	private static long countFileLineNum(String logFileName) {
		File file = new File(logFileName);
		if (file.exists()) {
			try {
				FileReader fileReader = new FileReader(file);
				LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
				lineNumberReader.skip(Long.MAX_VALUE);
				// getLineNumber() 從0開始計數,所以加1
				long totalLines = lineNumberReader.getLineNumber() + 1;
				fileReader.close();
				lineNumberReader.close();
				return totalLines;
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
			}
		}
		return 0;
	}


	/**
	 * 重寫讀取日志:1. 讀取logIndexFile;2.logFile
	 * @param logFileName
	 * @param logId
	 * @param fromLineNum
	 * @return
	 */
	public static LogResult readLogByIndex(String logFileName, int logId, int fromLineNum) {
		int strLength = logFileName.length();
		// 獲取檔案名前綴出去.log
		String prefixFilePath = logFileName.substring(0, strLength-4);
		String logIndexFilePath = prefixFilePath.concat(INDEX_SUFFIX).concat(FILE_SUFFIX);
		// valid logIndex file
		if (StringUtils.isEmpty(logIndexFilePath)) {
			return new LogResult(fromLineNum, 0, "readLogByIndex fail, logIndexFile not found", true);
		}
		logIndexFilePath = FilenameUtils.normalize(logIndexFilePath);
		File logIndexFile = new File(logIndexFilePath);
		if (!logIndexFile.exists()) {
			return new LogResult(fromLineNum, 0, "readLogByIndex fail, logIndexFile not exists", true);
		}
		// valid log file
		if (StringUtils.isEmpty(logFileName)) {
			return new LogResult(fromLineNum, 0, "readLogByIndex fail, logFile not found", true);
		}
		logFileName = FilenameUtils.normalize(logFileName);
		File logFile = new File(logFileName);
		if (!logFile.exists()) {
			return new LogResult(fromLineNum, 0, "readLogByIndex fail, logFile not exists", true);
		}

		// read logIndexFile
		String indexInfo = readIndex(logIndexFilePath, logId);
		int startNum = 0;
		int endNum = 0;
		if (!StringUtils.isEmpty(indexInfo)) {
			int startTmp = indexInfo.indexOf("(");
			int endTmp = indexInfo.indexOf(")");
			String[] fromAndTo = indexInfo.substring(startTmp + 1, endTmp).split(",");
			try {
				startNum = Integer.parseInt(fromAndTo[0]);
				endNum = Integer.parseInt(fromAndTo[1]) + startNum;
			} catch (Exception e) {
				logger.error("readLogByIndex StringArrayException,{},{}", e.getMessage(), e);
				throw new RuntimeException("StringArrayException");
			}
		}

		// read File
		StringBuffer logContentBuffer = new StringBuffer();
		int toLineNum = 0;
		LineNumberReader reader = null;
		try {
			reader = new LineNumberReader(new InputStreamReader(new FileInputStream(logFile), UTF_8));
			String line = null;

			while ((line = reader.readLine()) != null) {
				// [from, to], start as fromNum(logIndexFile)
				toLineNum = reader.getLineNumber();
				if (toLineNum >= startNum && toLineNum < endNum) {
					logContentBuffer.append(line).append("\n");
				}
				// break when read over
				if (toLineNum >= endNum) {
					break;
				}
			}
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		LogResult logResult = new LogResult(fromLineNum, toLineNum, logContentBuffer.toString(), false);
		return logResult;

	}
}

XxlJobLogger.java

package com.xxl.job.core.log;

import com.xxl.job.core.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * Created by xuxueli on 17/4/28.
 */
public class XxlJobLogger {
    private static Logger logger = LoggerFactory.getLogger("xxl-job logger");

    /**
     * append log
     *
     * @param callInfo
     * @param appendLog
     */
    private static void logDetail(StackTraceElement callInfo, String appendLog) {


        /*// "yyyy-MM-dd HH:mm:ss [ClassName]-[MethodName]-[LineNumber]-[ThreadName] log";
        StackTraceElement[] stackTraceElements = new Throwable().getStackTrace();
        StackTraceElement callInfo = stackTraceElements[1];*/

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(DateUtil.formatDateTime(new Date())).append(" ")
            .append("["+ callInfo.getClassName() + "#" + callInfo.getMethodName() +"]").append("-")
            .append("["+ callInfo.getLineNumber() +"]").append("-")
            .append("["+ Thread.currentThread().getName() +"]").append(" ")
            .append(appendLog!=null?appendLog:"");
        String formatAppendLog = stringBuffer.toString();

        // appendlog
        String logFileName = XxlJobFileAppender.contextHolder.get();
        if (logFileName!=null && logFileName.trim().length()>0) {
            // XxlJobFileAppender.appendLog(logFileName, formatAppendLog);
			  // 此處修改方法呼叫
            // modify appendLogAndIndex for addIndexLogInfo
            XxlJobFileAppender.appendLogAndIndex(logFileName, formatAppendLog);
        } else {
            logger.info(">>>>>>>>>>> {}", formatAppendLog);
        }
    }
}

JobThread.java

@Override
	public void run() {
	......
		// execute
		while(!toStop){
			running = false;
			idleTimes++;

            TriggerParam triggerParam = null;
            ReturnT<String> executeResult = null;
            try {
				// to check toStop signal, we need cycle, so wo cannot use queue.take(), instand of poll(timeout)
				triggerParam = triggerQueue.poll(3L, TimeUnit.SECONDS);
				if (triggerParam!=null) {
					running = true;
					idleTimes = 0;
					triggerLogIdSet.remove(triggerParam.getLogId());

					// log filename, like "logPath/yyyy-MM-dd/9999.log"
					// String logFileName = XxlJobFileAppender.makeLogFileName(new Date(triggerParam.getLogDateTim()), triggerParam.getLogId());

					// modify 將生成的日志檔案重新命名,以jobId命名
					String logFileName = XxlJobFileAppender.makeLogFileNameByJobId(new Date(triggerParam.getLogDateTim()), triggerParam.getJobId());
					XxlJobFileAppender.contextHolderJobId.set(triggerParam.getJobId());
					// 此處根據xxl-job版本號做修改
					XxlJobFileAppender.contextHolderLogId.set(Integer.parseInt(String.valueOf(triggerParam.getLogId())));

					XxlJobFileAppender.contextHolder.set(logFileName);
					ShardingUtil.setShardingVo(new ShardingUtil.ShardingVO(triggerParam.getBroadcastIndex(), triggerParam.getBroadcastTotal()));

					......
	}

ExecutorBizImpl.java

package com.xxl.job.core.biz.impl;

import com.xxl.job.core.biz.ExecutorBiz;
import com.xxl.job.core.biz.model.LogResult;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.biz.model.TriggerParam;
import com.xxl.job.core.enums.ExecutorBlockStrategyEnum;
import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.glue.GlueFactory;
import com.xxl.job.core.glue.GlueTypeEnum;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.impl.GlueJobHandler;
import com.xxl.job.core.handler.impl.ScriptJobHandler;
import com.xxl.job.core.log.XxlJobFileAppender;
import com.xxl.job.core.thread.JobThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Created by xuxueli on 17/3/1.
 */
public class ExecutorBizImpl implements ExecutorBiz {
    private static Logger logger = LoggerFactory.getLogger(ExecutorBizImpl.class);


    /**
     * 重寫讀取日志方法
     * @param logDateTim
     * @param logId
     * @param fromLineNum
     * @return
     */
    @Override
    public ReturnT<LogResult> log(long logDateTim, long logId, int fromLineNum) {
        // log filename: logPath/yyyy-MM-dd/9999.log
        String logFileName = XxlJobFileAppender.makeFileNameForReadLog(new Date(logDateTim), (int)logId);

        LogResult logResult = XxlJobFileAppender.readLogByIndex(logFileName, Integer.parseInt(String.valueOf(logId)), fromLineNum);
        return new ReturnT<LogResult>(logResult);
    }
}

LRUCacheUtil.java

?  通過LinkedHashMap實作一個快取容器

package com.xxl.job.core.util;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: liangxuanhao
 * @Description: 使用LinkedHashMap實作一個固定大小的快取器
 * @Date:
 */
public class LRUCacheUtil<K, V> extends LinkedHashMap<K, V> {

    // 最大快取容量
    private static final int CACHE_MAX_SIZE = 100;

    private int limit;

    public LRUCacheUtil() {
        this(CACHE_MAX_SIZE);
    }

    public LRUCacheUtil(int cacheSize) {
        // true表示更新到末尾
        super(cacheSize, 0.75f, true);
        this.limit = cacheSize;
    }

	/**
	 * 加鎖同步,防止多執行緒時出現多執行緒安全問題
	 */
    public synchronized V save(K key, V val) {
        return put(key, val);
    }

    public V getOne(K key) {
        return get(key);
    }

    public boolean exists(K key) {
        return containsKey(key);
    }

    /**
     * 判斷是否超限
     * @param elsest
     * @return 超限回傳true,否則回傳false
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry elsest) {
        // 在put或者putAll方法后呼叫,超出容量限制,按照LRU最近最少未使用進行洗掉
        return size() > limit;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<K, V> entry : entrySet()) {
            sb.append(String.format("%s:%s ", entry.getKey(), entry.getValue()));
        }
        return sb.toString();
    }
}

結果

?  執行效果如圖所示:達到預期期望,且效果良好,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/256625.html

標籤:其他

上一篇:CODING X C-Life:云端 DevOps 加速企業數智化

下一篇:兩個月拿到N個offer,看看我是如何做到的

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 網閘典型架構簡述

    網閘架構一般分為兩種:三主機的三系統架構網閘和雙主機的2+1架構網閘。 三主機架構分別為內端機、外端機和仲裁機。三機無論從軟體和硬體上均各自獨立。首先從硬體上來看,三機都用各自獨立的主板、記憶體及存盤設備。從軟體上來看,三機有各自獨立的作業系統。這樣能達到完全的三機獨立。對于“2+1”系統,“2”分為 ......

    uj5u.com 2020-09-10 02:00:44 more
  • 如何從xshell上傳檔案到centos linux虛擬機里

    如何從xshell上傳檔案到centos linux虛擬機里及:虛擬機CentOs下執行 yum -y install lrzsz命令,出現錯誤:鏡像無法找到軟體包 前言 一、安裝lrzsz步驟 二、上傳檔案 三、遇到的問題及解決方案 總結 前言 提示:其實很簡單,往虛擬機上安裝一個上傳檔案的工具 ......

    uj5u.com 2020-09-10 02:00:47 more
  • 一、SQLMAP入門

    一、SQLMAP入門 1、判斷是否存在注入 sqlmap.py -u 網址/id=1 id=1不可缺少。當注入點后面的引數大于兩個時。需要加雙引號, sqlmap.py -u "網址/id=1&uid=1" 2、判斷文本中的請求是否存在注入 從文本中加載http請求,SQLMAP可以從一個文本檔案中 ......

    uj5u.com 2020-09-10 02:00:50 more
  • Metasploit 簡單使用教程

    metasploit 簡單使用教程 浩先生, 2020-08-28 16:18:25 分類專欄: kail 網路安全 linux 文章標簽: linux資訊安全 編輯 著作權 metasploit 使用教程 前言 一、Metasploit是什么? 二、準備作業 三、具體步驟 前言 Msfconsole ......

    uj5u.com 2020-09-10 02:00:53 more
  • 游戲逆向之驅動層與用戶層通訊

    驅動層代碼: #pragma once #include <ntifs.h> #define add_code CTL_CODE(FILE_DEVICE_UNKNOWN,0x800,METHOD_BUFFERED,FILE_ANY_ACCESS) /* 更多游戲逆向視頻www.yxfzedu.com ......

    uj5u.com 2020-09-10 02:00:56 more
  • 北斗電力時鐘(北斗授時服務器)讓網路資料更精準

    北斗電力時鐘(北斗授時服務器)讓網路資料更精準 北斗電力時鐘(北斗授時服務器)讓網路資料更精準 京準電子科技官微——ahjzsz 近幾年,資訊技術的得了快速發展,互聯網在逐漸普及,其在人們生活和生產中都得到了廣泛應用,并且取得了不錯的應用效果。計算機網路資訊在電力系統中的應用,一方面使電力系統的運行 ......

    uj5u.com 2020-09-10 02:01:03 more
  • 【CTF】CTFHub 技能樹 彩蛋 writeup

    ?碎碎念 CTFHub:https://www.ctfhub.com/ 筆者入門CTF時時剛開始刷的是bugku的舊平臺,后來才有了CTFHub。 感覺不論是網頁UI設計,還是題目質量,賽事跟蹤,工具軟體都做得很不錯。 而且因為獨到的金幣制度的確讓人有一種想去刷題賺金幣的感覺。 個人還是非常喜歡這個 ......

    uj5u.com 2020-09-10 02:04:05 more
  • 02windows基礎操作

    我學到了一下幾點 Windows系統目錄結構與滲透的作用 常見Windows的服務詳解 Windows埠詳解 常用的Windows注冊表詳解 hacker DOS命令詳解(net user / type /md /rd/ dir /cd /net use copy、批處理 等) 利用dos命令制作 ......

    uj5u.com 2020-09-10 02:04:18 more
  • 03.Linux基礎操作

    我學到了以下幾點 01Linux系統介紹02系統安裝,密碼啊破解03Linux常用命令04LAMP 01LINUX windows: win03 8 12 16 19 配置不繁瑣 Linux:redhat,centos(紅帽社區版),Ubuntu server,suse unix:金融機構,證券,銀 ......

    uj5u.com 2020-09-10 02:04:30 more
  • 05HTML

    01HTML介紹 02頭部標簽講解03基礎標簽講解04表單標簽講解 HTML前段語言 js1.了解代碼2.根據代碼 懂得挖掘漏洞 (POST注入/XSS漏洞上傳)3.黑帽seo 白帽seo 客戶網站被黑帽植入劫持代碼如何處理4.熟悉html表單 <html><head><title>TDK標題,描述 ......

    uj5u.com 2020-09-10 02:04:36 more
最新发布
  • 2023年最新微信小程式抓包教程

    01 開門見山 隔一個月發一篇文章,不過分。 首先回顧一下《微信系結手機號資料庫被脫庫事件》,我也是第一時間得知了這個訊息,然后跟蹤了整件事情的經過。下面是這起事件的相關截圖以及近日流出的一萬條資料樣本: 個人認為這件事也沒什么,還不如關注一下之前45億快遞資料查詢渠道疑似在近日復活的訊息。 訊息是 ......

    uj5u.com 2023-04-20 08:48:24 more
  • web3 產品介紹:metamask 錢包 使用最多的瀏覽器插件錢包

    Metamask錢包是一種基于區塊鏈技術的數字貨幣錢包,它允許用戶在安全、便捷的環境下管理自己的加密資產。Metamask錢包是以太坊生態系統中最流行的錢包之一,它具有易于使用、安全性高和功能強大等優點。 本文將詳細介紹Metamask錢包的功能和使用方法。 一、 Metamask錢包的功能 數字資 ......

    uj5u.com 2023-04-20 08:47:46 more
  • vulnhub_Earth

    前言 靶機地址->>>vulnhub_Earth 攻擊機ip:192.168.20.121 靶機ip:192.168.20.122 參考文章 https://www.cnblogs.com/Jing-X/archive/2022/04/03/16097695.html https://www.cnb ......

    uj5u.com 2023-04-20 07:46:20 more
  • 從4k到42k,軟體測驗工程師的漲薪史,給我看哭了

    清明節一過,盲猜大家已經無心上班,在數著日子準備過五一,但一想到銀行卡里的余額……瞬間心情就不美麗了。最近,2023年高校畢業生就業調查顯示,本科畢業月平均起薪為5825元。調查一出,便有很多同學表示自己又被平均了。看著這一資料,不免讓人想到前不久中國青年報的一項調查:近六成大學生認為畢業10年內會 ......

    uj5u.com 2023-04-20 07:44:00 more
  • 最新版本 Stable Diffusion 開源 AI 繪畫工具之中文自動提詞篇

    🎈 標簽生成器 由于輸入正向提示詞 prompt 和反向提示詞 negative prompt 都是使用英文,所以對學習母語的我們非常不友好 使用網址:https://tinygeeker.github.io/p/ai-prompt-generator 這個網址是為了讓大家在使用 AI 繪畫的時候 ......

    uj5u.com 2023-04-20 07:43:36 more
  • 漫談前端自動化測驗演進之路及測驗工具分析

    隨著前端技術的不斷發展和應用程式的日益復雜,前端自動化測驗也在不斷演進。隨著 Web 應用程式變得越來越復雜,自動化測驗的需求也越來越高。如今,自動化測驗已經成為 Web 應用程式開發程序中不可或缺的一部分,它們可以幫助開發人員更快地發現和修復錯誤,提高應用程式的性能和可靠性。 ......

    uj5u.com 2023-04-20 07:43:16 more
  • CANN開發實踐:4個DVPP記憶體問題的典型案例解讀

    摘要:由于DVPP媒體資料處理功能對存放輸入、輸出資料的記憶體有更高的要求(例如,記憶體首地址128位元組對齊),因此需呼叫專用的記憶體申請介面,那么本期就分享幾個關于DVPP記憶體問題的典型案例,并給出原因分析及解決方法。 本文分享自華為云社區《FAQ_DVPP記憶體問題案例》,作者:昇騰CANN。 DVPP ......

    uj5u.com 2023-04-20 07:43:03 more
  • msf學習

    msf學習 以kali自帶的msf為例 一、msf核心模塊與功能 msf模塊都放在/usr/share/metasploit-framework/modules目錄下 1、auxiliary 輔助模塊,輔助滲透(埠掃描、登錄密碼爆破、漏洞驗證等) 2、encoders 編碼器模塊,主要包含各種編碼 ......

    uj5u.com 2023-04-20 07:42:59 more
  • Halcon軟體安裝與界面簡介

    1. 下載Halcon17版本到到本地 2. 雙擊安裝包后 3. 步驟如下 1.2 Halcon軟體安裝 界面分為四大塊 1. Halcon的五個助手 1) 影像采集助手:與相機連接,設定相機引數,采集影像 2) 標定助手:九點標定或是其它的標定,生成標定檔案及內參外參,可以將像素單位轉換為長度單位 ......

    uj5u.com 2023-04-20 07:42:17 more
  • 在MacOS下使用Unity3D開發游戲

    第一次發博客,先發一下我的游戲開發環境吧。 去年2月份買了一臺MacBookPro2021 M1pro(以下簡稱mbp),這一年來一直在用mbp開發游戲。我大致分享一下我的開發工具以及使用體驗。 1、Unity 官網鏈接: https://unity.cn/releases 我一般使用的Apple ......

    uj5u.com 2023-04-20 07:40:19 more