1

When reading and following log files on a system where logrotate is installed, it happens at certain times that the existing log file is renamed and a new file with the same name is created. The application will then write new log entries into the new file. When I'm still reading the old file and waiting for new data to be appended there, I'll have to know when the file with that name was replaced so that I can stop reading at the end of the file and restart reading the new file.

My log reader is written in C# (.NET Core 3.1) and will run on Linux. I can use native functions through the Mono.Posix.NETStandard package. But I'm not sure how to do that properly.

Should I fetch the inode number from the file name before I start reading? Or should I compare on other data like the size or time? What's the most robust approach to detecting when the file I've currently opened for reading is replaced?

The solution should ideally still work if the log file was replaced exactly at or around the moment when I opened the file for reading, and also if the old file was very small and the new file will be big from the start (because suddenly a lot happens). I couldn't find any information about this topic at all.

ygoe
  • 18,655
  • 23
  • 113
  • 210
  • Something like this? https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.renamed?view=net-5.0 – gunr2171 Dec 21 '20 at 20:56
  • 1
    Does this answer your question? [Notification when a file changes?](https://stackoverflow.com/questions/721714/notification-when-a-file-changes) – gunr2171 Dec 21 '20 at 21:03
  • I'm still on my way to try that out. I've totally forgotten about FileSystemWatcher now. I need some time until I've put enough of it together to see how well it works. – ygoe Dec 22 '20 at 22:23
  • @gunr2171 Yes, the FileSystemWatcher solution works. Thank you for the reminder! – ygoe Jan 08 '21 at 23:03

0 Answers0