JAVA實現讀取最后幾行日志
JAVA實現讀取最后幾行日志
1. 背景
在項目框架設計中,針對系統產生的日志,有線上查看日志的需求.日志文件本身很大.線上查看時,開發人員只想了解當前系統產生的錯誤信息.
2. POM依賴
主要使用 ReversedLinesFileReader 實現到讀日志文件,需要引入commons-io依賴,底層使用 RandomAccessFile 實現.
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
3. 代碼實現
先倒序讀取每行數據,放入集合中.然后集合倒序,返回符合閱讀習慣的文本日志.
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類,實現倒序讀取內容
@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) {
}
}
}
}
- 轉載請注明來源
- 作者:楊瀚博
- QQ:464884492

浙公網安備 33010602011771號