简体   繁体   中英

Serilog SelfLog to File Error

I need to enable self log of seri logger to text file. My configuration are follows;

__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));

But is hows File access error when run the application. Please find the error details below;

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

Can anyone help me on this

try

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

for a non-locking way to write to a file. serilogSelfLogFilePath is a valid path string to the file you want to use.

Don't forget Log.CloseAndFlush(); when you're closing your other logs per https://github.com/serilog/serilog/issues/864 or it won't get written anyway

Note, if you are using an async Sink then you will eventually get an exception when different threads contend to write to that file if it gets busy.

You must have another instance of this application running when it comes to this line. Or maybe this code is somehow being invoked twice? Check taskmanager and kill anything that maybe using it. If this is a web app try recycling the app pool.

I was facing a problem manifesting this same The process cannot access the file 'X' because it is being used by another process. error message. In my case it appeared in the server's event log every time the application pool recycled in IIS 8.5, even though Maximum worker processes was set to 1 . Maybe worth saying: the code enabling self log executes in a static constructor.

No luck did I have after properly closing the TextWriter , not even when adding generous Thread.Sleep before File.CreateText in hope of waiting for that "another process" to finish.

The solution was to set Disable Overlapped Recycle to true in Advanced Settings for the application pool.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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