How to monitor a logfile that seems to be open all the time (much like notepad++ does)?

1.2k views Asked by At

I'm trying to build a small program to monitor my pfirewall.log, but I can't seem to open it. I found quite many (simple) answers, that all kinda say

// use FilesystemWatcher
// open FileStream
// read from last position to end
// output new lines

The problem here is: The file seems to always be opened by another process already. I guess that's the windows process writing to the file, since it's getting written to all the time, as Notepad++ shows me.

Which means, Notepad++ can for some reason do what I can not: Read the file despite it being opened already.

I initialize my monitor in the constructor:

    public FirewallLogMonitor(string path)
    {
        if (!File.Exists(path))
            throw new FileNotFoundException("Logfile not found");

        this.file = path;
        this.lastPosition = 0;
        this.monitor = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path));
        this.monitor.NotifyFilter = NotifyFilters.Size;

    }

And try to read the file on monitor.Changed event:

    private void LogFileChanged(object sender, FileSystemEventArgs e)
    {
        using (FileStream stream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (StreamReader reader = new StreamReader(stream))
        {
            stream.Seek(this.lastPosition, SeekOrigin.Begin);
            var newLines = reader.ReadToEnd();
            this.lastPosition = stream.Length;
            var filteredLines = filterLines(newLines);
            if (filteredLines.Count > 0)
                NewLinesAvailable(this, filteredLines);
        }
    }

It always throws the IOException on new FileStream(...) to tell me the file is already in use.

Since Notepad++ does it, there has to be a way I can do it too, right?

**Edit: ** A button does this:

    public void StartLogging()
    {
        this.IsRunning = true;
        this.monitor.Changed += LogFileChanged;
        this.monitor.EnableRaisingEvents = true;
    }

**Edit2: ** This is not a duplicate of FileMode and FileAccess and IOException: The process cannot access the file 'filename' because it is being used by another process, since that one assumes I have control over the writing process. Will try the other suggestions, and report back with results.

1

There are 1 answers

1
Moshe D On

If i understand your question you can use the notepad++ itself with a plugin to monitor you need to go to:

plugins -> Document Moniter -> Start to monitor

if you dont have this plugin you can download it here:

http://sourceforge.net/projects/npp-plugins/files/DocMonitor/