public void WriteLog(LogLevel level, string msg) { if (isInitialized && isRunning) { if (IsLogLevelEnabled(level)) { try { NLogMsg logmsg = Pool.Checkout(); if (logmsg == null) { logger.Fatal(msgWithTime("LibraryLogger logmsg == null")); return; } logmsg.level = level; logmsg.msg = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "|" + level + "|" + Thread.CurrentThread.ManagedThreadId + " " + msg; queue.Enqueue(logmsg); } catch (Exception ex) { logger.Fatal(ex, msgWithTime("LibraryLogger Exception")); } } } }
private void WriteToFile() { StringBuilder sb = new StringBuilder(); NLogMsg logmsg = null; while (isRunning || !queue.IsQueueEmpty) { try { sb.Clear(); bool gotItem = true; while (gotItem) { gotItem = queue.TryDequeue(out logmsg); if (gotItem && logmsg != null && !string.IsNullOrEmpty(logmsg.msg)) { if (sb.Length > 0) { sb.AppendLine(); } sb.Append(logmsg.msg); } if (logmsg != null) { Pool.Checkin(logmsg); logmsg = null; } if (sb.Length > 1024 * 1024 || queue.IsQueueEmpty) { break; } } if (sb.Length > 0) { logger.Info(sb.ToString()); } } catch (OperationCanceledException) { logger.Info(msgWithTime("LibraryLogger Shutdown in progress")); } catch (Exception ex) { logger.Error(ex, msgWithTime("LibraryLogger Exception")); } finally { if (logmsg != null) { Pool.Checkin(logmsg); logmsg = null; } } } }