2010-04-09 200 views
0

我目前正在观看像这样tail -f这样的日志文件,并且每隔一段时间我按下一个键,然后按回车,以便日志打印到控制台中的新更改,如何在更改时自行打印在日志文件中发生?这里是要求:如何为日志创建shell脚本

START loop 
1. Check file.log 
2. If file.log has changed print the changes 
3. else print nothing 
END 

我写的Windows类似的东西从Java执行:

import java.io.FileInputStream; 
import java.io.DataInputStream; 
import java.io.InputStreamReader; 
import java.io.BufferedReader; 

class LogWatch { 
    public static void main(String args[]) { 
     try { 

      FileInputStream fstream = new FileInputStream("C:\\file.log"); 

      DataInputStream in = new DataInputStream(fstream); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      String line; 

      while (true) { 

       line = br.readLine(); 
       if (line == null) { 
        Thread.sleep(500); 
       } else { 
        System.out.println(line); 
       } 

      } 

     } catch (Exception e) { 
      System.err.println("Error: " + e.getMessage()); 
     } 
    } 
} 

这是不必要的开销,因为这可以从shell脚本来完成,没有任何人有任何建议,如何去做吧 ?

+1

Errr ...的'-f'开关装置“关注”,任何改变应当自动打印到控制台(除非文件被删除(或移动),并创建具有相同名称的一个新的,在其中如果您需要终止后续行动并重新开始(但您并未说您必须终止此流程)。 – Quentin 2010-04-09 09:35:04

回答

4

使用-F而不是-f

假设-f心不是”工作,因为你打的logrotate并没有提到有杀尾的前一个实例。

-f  The -f option causes tail to not stop when end of file is 
     reached, but rather to wait for additional data to be appended to 
     the input. The -f option is ignored if the standard input is a 
     pipe, but not if it is a FIFO. 

-F  The -F option implies the -f option, but tail will also check to 
     see if the file being followed has been renamed or rotated. The 
     file is closed and reopened when tail detects that the filename 
     being read from has a new inode number. The -F option is ignored 
     if reading from standard input rather than a file.