How to write to a txt file when several processes use it? WITH#

I have a log that is trying to write log files. It seems that the problem is that several processes are accessing the same log file, the logger cannot write to the log file the error message "Another process is using the file ...", as a result of which critical information will be lost. I tried using locks, but it does not seem to work, as they are separate processes (I think that is why they do not work). Is there a way for multiple processes to access a file without losing information? If not, are there any other alternatives? Thanks.

+6
source share
3 answers

Your parameters are not in a specific order:

  • Different processes are written to different log files. If necessary, these processes collapse files at some point (for example, at midnight) and have another process that takes logs yesterday and combines them together.
  • If you own / manage your registrar infrastructure and need to write to the same log file, look at the name mutex . Named mutexes are system mutexes and can be shared between process boundaries. The sample code in the link shows how to share the same mutec between processes.
    • As Florian F suggests in the comments, use log4net, which can do this (in more than one way, including using named mutex). Their FAQ correctly states that there is a performance issue if you do.
  • There are ways to share a shared record and share a file, and then the ability to lock certain areas of the file. You can try several processes and synchronize who writes to which areas of the file, block accordingly, etc. But it is very painful to get better and recommend against it.
  • Use syslog server.
  • Use the remote logging capabilities of log4net.
+5
source

Log4Net is the option that Florian talked about.

Another option is to use a separate file as a lock. If a lock file is present, other processes wait actively, otherwise they create a lock file, write, and then delete the lock file.

If you were unable to create the lock file, then you have another process before you, and you continue to wait.

+2
source

If you insist on reinventing the wheel and not use other parameters (log4net or memory mapped files), you will need to delay the record in the file itself and just try if you come across another thread that does the same thing.

A lightweight version using a task to obtain a non-blocking function and an indication as an example (not used as is).

public Task FlushLog(string filePath) { var task = new Task( () => while (true) { try { var file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)); WriteLogToFileInTheUsualWay(file); file.Close(); file.Dispose(); break; } catch (UnauthorizedAccessException exception) { // Sleep randomly and try again Thread.Sleep(new Random(DateTime.Now.Milliseconds).Next(1000)); } } ); task.Start(); return task; } 
0
source

All Articles