Java实时读取日志文件

 

在一台服务器上写日志文件,每当日志文件写到一定大小时,比如是1G,会将这个日志文件改名成另一个名字,并新建一个与原文件名相同的日志文件,再往这个新建的日志文件里写数据;要求写一个程序能实时地读取日志文件中的内容,并且不能影响写操作与重命名操作。

RandomAccessFile类中seek方法可以从指定位置读取文件,可以用来实现文件实时读取。JDK文档对RandomAccessFile的介绍

在每一次读取后,close一下就不会影响重命名操作了。

写日志文件,每秒写200条记录,并且记录写的时间

import java.io.File;  
import java.io.FileWriter;  
import java.io.IOException;  
import java.io.Writer;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.concurrent.Executors;  
import java.util.concurrent.ScheduledExecutorService;  
import java.util.concurrent.TimeUnit;  
 
public class LogWrite implements Runnable {  

    private File logFile = null;
    private SimpleDateFormat dateFormat =   
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    public LogWrite(File logFile) {
    	this.logFile = logFile;
	}
  
    /** 
     * 将信息记录到日志文件 
     * @param logFile 日志文件 
     * @param mesInfo 信息 
     * @throws IOException  
     */  
    public void run(){  
        if(logFile == null) {  
            throw new IllegalStateException("logFile can not be null!");  
        } 
        try {    
	        if(!logFile.exists()) {  
	        	logFile.createNewFile();  
	        } 
	        //启动一个线程每1秒钟向日志文件写一次数据  
            ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);  
            exec.scheduleWithFixedDelay(new Runnable(){  
               public void run() {  
                   try {  
                	   Writer txtWriter = new FileWriter(logFile,true);
	           	       txtWriter.write(dateFormat.format(new Date()) +"\t 99bill test ! \n");  
	           	       txtWriter.flush();    
                   } catch (IOException e) {  
                       throw new RuntimeException(e);  
                   }  
               }  
           }, 0, 1, TimeUnit.SECONDS); 
	        
		} catch (IOException e) { 
			e.printStackTrace();
		}  
    }  
      
    
    public static void main(String[] args) throws Exception{  
          
        final File tmpLogFile = new File("mock.log");  
        final LogWrite logSvr = new LogWrite(tmpLogFile);  
   
        //启动一个线程每5秒钟向日志文件写一次数据  
 /*       ScheduledExecutorService exec =   
            Executors.newScheduledThreadPool(1);  
        exec.scheduleWithFixedDelay(new Runnable(){  
            public void run() {  
                try {  
                    logSvr.logMsg(tmpLogFile, " 99bill test !");  
                } catch (IOException e) {  
                    throw new RuntimeException(e);  
                }  
            }  
        }, 0, 5, TimeUnit.NANOSECONDS);*/  
    }  
}  


实时读取日志文件,每隔1秒读一次

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogReader implements Runnable {
    private File logFile = null;
    private long lastTimeFileSize = 0; // 上次文件大小
    private static SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    public LogReader(File logFile) {
        this.logFile = logFile;
        lastTimeFileSize = logFile.length();
    }

    /**
     * 实时输出日志信息
     */
    public void run() {
        while (true) {
            try {
                long len = logFile.length();
                if (len < lastTimeFileSize) {
                    System.out.println("Log file was reset. Restarting logging from start of file.");
                    lastTimeFileSize = len;
                } else if(len > lastTimeFileSize) {
                    RandomAccessFile randomFile = new RandomAccessFile(logFile, "r");
                    randomFile.seek(lastTimeFileSize);
                    String tmp = null;
                    while ((tmp = randomFile.readLine()) != null) {
                        System.out.println(dateFormat.format(new Date()) + "\t"
                                + tmp);
                    }
                    lastTimeFileSize = randomFile.length();
                    randomFile.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

开启写线程、读线程,将实时信息打印在控制台。

import java.io.File;

public class RunRun {
    public static void main(String[] args) {
        File logFile = new File("mock.log");
        Thread wthread = new Thread(new LogWrite(logFile));
        wthread.start();
        Thread rthread = new Thread(new LogReader(logFile));
        rthread.start();
    }
}

在读写的过程中,我们可以手动将mock.log文件重命名,发现依旧可以实时读。

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值