Serilog SelfLog 到文件错误

Serilog SelfLog to File Error

我需要启用 seri 记录器的自记录到文本文件。我的配置如下;

__serilogLogger = new LoggerConfiguration()
      .Enrich.WithProperty("ApplicationIPv4", _ipv4)
      .Enrich.WithProperty("ApplicationIPv6", _ipv6)
      .WriteTo.MSSqlServer(connectionString, tableName /*, columnOptions: columnOptions*/)
      .WriteTo
      .Seq(ConfigurationManager.AppSettings["SerilogServer"])
      .CreateLogger();

      var file = File.CreateText("Self.log");
      Serilog.Debugging.SelfLog.Enable(TextWriter.Synchronized(file));

但是运行应用程序时文件访问错误是怎么回事。请在下面找到错误详细信息;

Additional information: The process cannot access the file 'C:\Program Files (x86)\IIS Express\Self.log' because it is being used by another process.

谁能帮我解决这个问题

当涉及到这一行时,您必须有此应用程序的另一个实例运行。或者这段代码可能以某种方式被调用了两次?检查任务管理器并杀死任何可能使用它的东西。如果这是一个网络应用程序,请尝试回收应用程序池。

尝试

Serilog.Debugging.SelfLog.Enable(msg => File.AppendAllText (serilogSelfLogFilePath, msg));

用于写入文件的非锁定方式。 serilogSelfLogFilePath 是您要使用的文件的有效路径 string

不要忘记 Log.CloseAndFlush(); 当您按 https://github.com/serilog/serilog/issues/864 关闭其他日志时,否则无论如何都不会写入

请注意,如果您使用的是异步接收器,那么当文件繁忙时不同的线程争相写入该文件时,您最终会得到一个异常。

我遇到了同样的 The process cannot access the file 'X' because it is being used by another process. 错误消息。在我的例子中,每次在 IIS 8.5 中回收应用程序池时它都会出现在服务器的事件日志中,即使 Maximum worker processes 设置为 1。也许值得一提:启用自记录的代码在静态构造函数中执行。

在正确关闭 TextWriter 之后,我没有运气,即使在 File.CreateText 之前添加慷慨的 Thread.Sleep 以等待“另一个过程”完成时也是如此。

解决方案是在应用程序池的高级设置中将 Disable Overlapped Recycle 设置为 true