JAVA实现读取最后几行日志

JAVA实现读取最后几行日志

1. 背景

在项目框架设计中,针对系统产生的日志,有线上查看日志的需求.日志文件本身很大.线上查看时,开发人员只想了解当前系统产生的错误信息.

2. POM依赖

主要使用 ReversedLinesFileReader 实现到读日志文件,需要引入commons-io依赖,底层使用 RandomAccessFile 实现.

xml 复制代码
 <dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
 </dependency>

3. 代码实现

先倒序读取每行数据,放入集合中.然后集合倒序,返回符合阅读习惯的文本日志.

java 复制代码
public String readLastLines(String filePath, int lines) throws IOException {
  if(StringUtils.isBlank(filePath)|| lines<=0){
    return "";
  }
  List<String> lastLine = new ArrayList<String>();
  ReversedLinesFileReader reader = null;
  try {
    reader = new ReversedLinesFileReader(filePath, StandardCharsets.UTF_8);
    String line = "";
    while ((line = reader.readLine()) != null && lastLine.size() < lines) {
      lastLine.add(line);
    }
    Collections.reverse(lastLine);
  } catch (IOException e) {
    System.out.println("读取文件失败,公众号:小满小慢,小游戏:地心侠士");
  } finally {
    if (reader != null) {
      try {
        reader.close();
      } catch (IOException e) {
        System.out.println("关闭文件失败,,公众号:小满小慢,小游戏:地心侠士");
      }
    }
  }
  return StringUtils.join(lastLine, "\r\n");
}

4. RandomAccessFile 基本使用

使用 RandomAccessFile类,实现倒序读取内容

java 复制代码
@Test
   public void testReadLogFile() {
   	File logFile = new File("./logs/spring.log");
   	RandomAccessFile reader = null;
   	try {
   		reader = new RandomAccessFile(logFile, "r");
   		System.out.println(reader.readUTF());
   		reader.seek(logFile.length() - 1);
   		byte c = -1;
   		List<Byte> l = new ArrayList<Byte>();
   		do {
   			c = reader.readByte();
   			if (c == '\r' || c == '\n') {
   				byte[] bytes = new byte[l.size()];
   				for (int i = 0; i < l.size(); i++) {
   					bytes[i] = l.get(i);
   				}
   				String line = new String(bytes, StandardCharsets.UTF_8);
   				System.out.println("地心侠士:"+ line);
   				l = new ArrayList<Byte>();
   			}
   		} while (reader.getFilePointer() != logFile.length());
   		System.out.println("地心侠士:" +logFile.length());
   	} catch (IOException e) {
   		e.printStackTrace();
   	} finally {
   		if (reader != null) {
   			try {
   				reader.close();
   			} catch (IOException e) {

   			}
   		}
   	}
   }