I'm trying to write the request response traces to a file in an EWS Managed API client application. The problem is, at a time there are multiple requests/response (multiple emails) traces logged in a file, due to which race condition occurs resulting in "The process cannot access the file because it is being used by another process." error.
Adding lock worked , but I wanted check if there's any other better way to handle this scenario
public class TraceListener : ITraceListener
{
private static object leadLock = new object();
private readonly string traceFilePath;
private readonly ILogger _logger;
private readonly string traceFileName;
private readonly bool enableTrace;
public TraceListener(ILogger<TraceListener> logger, IConfiguration configuration)
{
traceFilePath = configuration["TraceFilePath"];
traceFileName = configuration["TraceFileName"];
bool.TryParse(configuration["EnableTrace"], out enableTrace);
_logger = logger;
}
#region ITraceListener Members
public void Trace(string traceType, string traceMessage)
{
if (enableTrace)
CreateTextFile(traceType, traceMessage.ToString());
}
#endregion
public void CreateTextFile(string fileName, string traceContent)
{
try
{
lock (leadLock)
{
Directory.CreateDirectory(traceFilePath);
File.AppendAllText(Path.Combine(traceFilePath, fileName + ".txt"), traceContent);
}
}
catch (Exception ex)
{
_logger.LogWarning("Error occured while writing traces to the file");
}
finally
{
_logger.LogInformation("TraceListner ended");
}
}
}