在C#.NET中创建日志文件并动态更新状态

3
我想在我的控制台应用程序中创建格式为(Log + datetime.Now).txt的日志文件。
对于我想记录的第一个状态,我想要创建这个日志文件。 我需要不断地将最新的状态消息(大约50到60条消息)附加到这个文件中,在10到20分钟的时间范围内。
同时,在此时间范围内,如果用户打开此文件,他应该能够自由地打开它。
任何代码示例将不胜感激。
谢谢

您希望用户在应用程序仍在记录日志时能够打开并编辑文件吗?或者用户仅需要在应用程序记录日志时对文件进行只读访问? - NerdFury
用户在登录时只需要只读访问权限。我注意到即使用户打开文件,文件也会更新。 - Rita
看一下成熟的日志记录系统,可以轻松实现这个功能。企业库拥有您所寻找的内容,并且非常容易使用。 - Steven Evers
重复的问题:https://dev59.com/AFHTa4cB1Zd3GeqPTrLF - user415789
6个回答

2

不要自己编写日志记录类,而是使用现有的日志框架。例如Log4Net可以使用最小化锁定方法,使其他进程能够读取文件:

<appender name="FileAppender" type="log4net.Appender.FileAppender">
    <file value="log-file.txt" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%message %date%newline" />
    </layout>
</appender>

如果您希望以后更改所使用的日志记录器,应尝试使用日志记录抽象层(NetCommonLogging)。


0
尝试使用StreamWriter。类似这样的代码:
using (StreamWriter writer = new StreamWriter("log.txt"))
{
            writer.WriteLine("Text here");
}

0

您可以使用 StreamWriter 类来写入甚至追加文件中的文本。

几天前,我写了一篇关于日志记录的文章,在这里查看博客文章

我的博客文章中的代码片段

        // Open the file using stream write.
        // If file does not exist, StreamWriter will create it.
        // Use the overloaded constructor of StreamWriter and 
        // pass second parameter as true for appending text to file.
        using (StreamWriter writer = new StreamWriter(@"D://myfile.txt", true))
        {
            // write the text to writer
            writer.WriteLine("Your text here" + " - " + DateTime.Now);

            // clear all the buffer and 
            // write the buffered data to text file.
            writer.Flush();
        }

注意:我已经根据原博客文章稍微修改了代码,以满足原帖作者的要求。


0

旋转文件

跟踪当前文件打开的时间,如果超过给定的TimeSpam(即“10-20分钟”),则关闭它,创建一个名为filename的文件并打开它。

允许他人读取文件

这完全是关于控制文件共享选项,虽然其他方法会使用正确的默认值,但如果我需要特定的内容,我宁愿明确说明。FileShare.Read具有正确的语义:

允许随后打开文件进行读取。

解决方案

class FileLogger {
  private TimeSpan timeout;

  private DateTime openedFile;
  private Stream output;
  private StreamWriter writer;

  public Dispose() {
    if (writer != null) {
      writer.Dispose();
      writer = null;
    };
    if (output != null) {
      output.Dispose();
      output = null;
    }
  }

  public void Log(string message) {
    if (output == null
        || ((DateTime.UtcNow - openedFile) > timeout) {
      Dispose();

      string filename = MakeFileName();
      output = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.Read);
      writer = new StreamWriter(output);
      openedFile = DateTime.UtcNow;
    }

    writer.WriteLine(writer);
  }
}

但是,通过实现MakeFileName和一个构造函数来设置timeout


0
public static Boolean CreateLogFile(String message)
        {
            try
      {
                //string location = @"C://IRPC//myfile1.txt";
                string location = System.Environment.CurrentDirectory + "\\log " + LogTime + ".txt";
                if (!File.Exists(location))
                {
                    FileStream fs;
                    using (fs = new FileStream(location, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                    {
                    }
                    fs.Close();
                }

                Console.WriteLine(message);
                //Release the File that is created
                StreamWriter sw = new StreamWriter(location, true);
                sw.Write(message + Environment.NewLine);
                sw.Close();
                sw = null;
                return true;
      }
      catch(Exception ex)
            {
                EventLog.WriteEntry("MIDocShare", "Error in CreateLogFile" + ex.Message.ToString(), EventLogEntryType.Error, 6000);
       return false;
      }
     }

0

使用FileMode.Append创建FileStream。
当其他人正在写入文本文件时,记事本可以打开它(尽管它只是当前打开的时间)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接