2010-04-09 199 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.