簡體   English   中英

如何為日志創建外殼腳本

[英]how to create shell script for logs

我當前正在查看我的日志文件,例如tail -f ,然后不時按下向上鍵並按回車鍵,以便將日志打印中的新更改打印到控制台中,如何在發生日志文件更改時使其自動打印? 這是要求:

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腳本完成,有人對它的使用有任何建議嗎?

使用-F而不是-f

假設-f不起作用是因為您遇到了logrotate並且沒有提及必須殺死前一個tail實例。

 -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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM