Akhil
Akhil

Reputation: 2030

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

Upvotes: 3

Views: 7955

Answers (3)

liviriniu
liviriniu

Reputation: 116

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.

enter image description here

Upvotes: 2

CAD bloke
CAD bloke

Reputation: 8828

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.

Upvotes: 11

Paul
Paul

Reputation: 3326

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.

Upvotes: 1

Related Questions