Java real-time read log file __java

Source: Internet
Author: User
Tags dateformat

Write log files on a single server, whenever the log file is written to a certain size, such as 1G, the log file will be renamed to another name, and a new log file with the same file name, and then write the data to the new log file; Write a program that reads the contents of the log file in real time, and cannot affect write operations and rename operations.

The Seek method in the Randomaccessfile class can read files from a specified location and can be used to implement real-time file reads. Introduction to Randomaccessfile by JDK documentation

After each read, the close will not affect the rename operation.

Write log files, write 200 records per second, and record the time of writing

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; /** * Records information to log file * @param logFile log file * @param mesinfo information * @throws IOException * /public void Run () {if (logFile = = null) {throw new IllegalStateException ("LogFile can not 
        Be null! ");}  
	        try {if (!logfile.exists ()) {logfile.createnewfile (); //Start a thread write data to log file once every 1 seconds 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 Tmplo  
        Gfile = new File ("Mock.log");  
   
        Final Logwrite logsvr = new Logwrite (tmplogfile);  
        Start a thread write data to log file once every 5 seconds/* 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); */}}


Read log files in real time, read every 1 seconds

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;

    Last file size private static SimpleDateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
        Public LogReader (File logFile) {this.logfile = LogFile;
    Lasttimefilesize = Logfile.length (); /** * Real-time output log information */public void run () {while (true) {try {long L
                En = 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 (); The catch (IOException e) {//TODO auto-generated catch block E.printstacktra
            CE ();
            try {thread.sleep (50); 
            catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }
        }
    }

}

Open the Write thread, read the thread, and print the real-time information in the console.

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 ();
    }

In the process of reading and writing, we can manually rename the Mock.log file and find that it can still be read in real time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.