public static void WriteLine(string message, string level) { // create a json record var record = new TraceRecord() { //Client = TraceLog.Client, LogLevel = level, Message = message, Session = TraceLog.Session, Timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff") }; var json = JsonConvert.SerializeObject(record); lock (writeLock) { // enter a retry loop writing the record to the trace file int retryCount = 2; while (retryCount > 0) { try { if (traceFilename == null) { // create the file using (var stream = File.Create(TraceFilename)) using (var writer = new StreamWriter(stream)) { // log the file creation var createRecord = new TraceRecord() { //Client = TraceLog.Client, LogLevel = TraceLog.LevelText(TraceLog.LogLevel.Info), Message = "Created new trace file " + TraceFilename, Session = TraceLog.Session, Timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff") }; var createJson = JsonConvert.SerializeObject(createRecord); writer.WriteLine(createJson); writer.Flush(); } } // open the file using (var stream = File.Open(TraceFilename, FileMode.Append, FileAccess.Write, FileShare.Read)) using (var writer = new StreamWriter(stream)) { writer.WriteLine(json); writer.Flush(); // reset the trace filename if it exceeds the maximum file size if (writer.BaseStream.Position > MaxFileSize) { traceFilename = null; } } // success - terminate the enclosing retry loop break; } catch (Exception) { // the file wasn't opened or written to correctly - try to start with a new file in the next iteration of the retry loop traceFilename = null; retryCount--; } } } }