简体   繁体   English

读取由NLog创建的日志文件并同时写入

[英]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. 我有一个将日志写入由NLog创建的文件中的应用程序。 And I have another application called Log Viewer. 我还有另一个名为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 我不想在每个方法调用中读取文件中的所有文本,我只需要读取其中的新日志行

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. 知道日志行是唯一的唯一方法是知道文件上次读取的位置(例如“ int lastposition = 0;”。您需要从该位置读取直到文件末尾。) “文件结尾”与文件长度相同。读取文件块后;在查看器中显示读取的内容,然后将最后一个位置保存到变量lastposition中;下次需要从此处开始时,查看器为读。

But if the viewer can't open the file... that's an other story. 但是,如果查看器无法打开文件,那就另当别论了。

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). 两者都访问同一个文件将需要锁定,如果文件无法写入(可能阻止,丢失日志条目或生成异常),则可能会导致应用程序出现问题。

Best solution is to set up a NLog target for a database. 最好的解决方案是为数据库设置NLog目标。 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. 如何设置NLog数据库目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM