Mohsen
Mohsen

Reputation: 206

Read a log file created by NLog and write in it simultanously

I have an application that writes logs into a file created by NLog. And I have another application called Log Viewer. It can open and read the log file mentioned above. But there is some problem here. While log viewer is reading the log file, and first application is writing in it , some of the log line can not be seen in log viewer. for example if first application write log in every milisecond , log viewer can not track new log lines and miss some of them , you know ? I need an online log viewer that can track any new log lines. I do not want to read all text in file every method call, I need just to read new log line in it

Upvotes: 3

Views: 4253

Answers (3)

Dhanuka777
Dhanuka777

Reputation: 8636

Best solution is to set up a NLog target for a database. Keep track of the last updated row is easier and safer than tracking the file position. I wouldn't recommend sharing a file active log file both read and write.

How to set up NLog Database target.

Upvotes: 1

STW
STW

Reputation: 46394

Having both applications share the same log is likely to be problematic. Probably the easiest solution is to have your viewer copy the original log file, and view it's own dedicated copy. You can occasionally check to see if the actual log file has updates and make new copies accordingly.

Having both access the same file will require locking, and risks causing issues in your application if the file is unavailable to write to (possibly blocking, losing log entries, or generating exceptions).

Upvotes: 3

The only way you can know that a log line is new is by knowing which position in the file you last read (eg. "int lastposition=0;". You need to read from that position until the end of file. The position of "End of file" is the same as the filelength. When the file block has been read; you show what you read in the viewer, and save the last position into the variable lastposition; where you need to start next time, the viewer is reading.

But if the viewer can't open the file... that's an other story.

Upvotes: 3

Related Questions