问题
I've created simple WPF control to monitor changes in log file. I used FileSystemWatcher to watch specific file. My configuration:
Directory = System.IO.Path.GetDirectoryName(logFileFullPath);
Filter = System.IO.Path.GetFileName(logFileFullPath);
NotifyFilter = (NotifyFilters.LastWrite | NotifyFilters.Size);
EnableRaisingEvents = true;
The problem is that changes are displayed only after refreshing the directory manually or opening log file.
I use RollingFileAppender in my log4net configuration so changes should be written immediately.
The question is: why dosn't it work and how to make it work?
EDIT :
Also when I update manually other monitored file the watcher works fine. So it must be some log4net issue.
回答1:
I've finally come up with solution. The problem had little to do with FileSystemWatcher. My log4net configuration was lacking the line:
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
It's still quite interesting as I had no problem with opening log file from text editor.
回答2:
Try this code,
FileSystemWatcher watcher = new FileSystemWatcher(@"logFileDirectoryPath");
watcher.Filter = "LogFileNameWithExtension";
watcher.EnableRaisingEvents = true;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
Changed Event
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
//Do Something
}
来源:https://stackoverflow.com/questions/20529019/watching-log4net-log-file-with-filesystemwatcher