1

Windows 8 で F# を使用して解析する必要がある大きなログ ファイルがあります。新しい行を追加してログ ファイルの末尾に書き込むサーバーが常に実行されています。ログ ファイルは、変更がないか毎分チェックされます。ファイル全体を再解析するのではなく、最後から読み取って、新しく追加された行を前の解析の結果に結合します。さらに良いことに、ファイルが変更されるたびにコールバックを登録できるようにしたいと考えています。それは可能ですか?

4

1 に答える 1

1

Seek()これは、ファイルストリームを介して行うことができます。このようなもの:

open System.IO

let WatchLog directory file =
    // Keep track of last read position
    let lastRead = ref 0L

    // Function that's called whenever the file changes
    let processLog (e : FileSystemEventArgs) =
        // Open file, and seek to the last read location
        use fs = new FileStream(Path.Combine(directory, file), FileMode.Open, FileAccess.Read)
        fs.Seek(!lastRead, SeekOrigin.Begin) |> ignore

        // Read the rest of the file
        use sr = new StreamReader(fs)
        printfn "Reading log: %A" (sr.ReadToEnd())

        // Store the length so that we know how much to seek over next time
        lastRead := fs.Length
        ()

    // Create a FS watched to be notified when a file changes
    let fs = new FileSystemWatcher(directory, file)
    fs.Changed.Add(processLog)
    fs.EnableRaisingEvents <- true

WatchLog "M:\Coding\" "TestLog.txt"

ただし、何らかの理由で、私のマシンでは「別のプロセスで使用されているため、プロセスはファイルにアクセスできません」というエラーが表示され、追跡できません。useステートメントはスコープ外になったときに処分する必要があり、明示的な呼び出しでさえ修正されませCloseん:/

于 2013-10-27T15:44:13.097 に答える