Java实时读取日志文件

来源:互联网 发布:mvvm 知乎 编辑:程序博客网 时间:2024/05/29 18:32

 

在一台服务器上写日志文件,每当日志文件写到一定大小时,比如是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文件重命名,发现依旧可以实时读。

0 0
原创粉丝点击