/// <summary> /// Method to whatch <see cref="MemoryAppenderWithEvents"/> logs events. /// </summary> public MemoryLogWatcher() { // Get the memory appender memoryAppender = (MemoryAppenderWithEvents)Array.Find(LogManager.GetRepository().GetAppenders(), IsMemoryAppender); if (memoryAppender == null) { throw new NullReferenceException("Log4net memory appender not found !"); } // Read in the log content LogContent = GetEvents(memoryAppender); // Add an event handler to handle updates from the MemoryAppender memoryAppender.Updated += HandleUpdate; }
/// <summary> /// Method te get the events formated into a string. /// </summary> /// <param name="memoryAppender">The memory appender with logs events <see cref="MemoryAppenderWithEvents"/></param> /// <returns>The events formated into a string.</returns> public string GetEvents(MemoryAppenderWithEvents memoryAppender) { StringBuilder output = new StringBuilder(); // Get any events that may have occurred LoggingEvent[] events = memoryAppender.GetEvents(); // Check that there are events to return if (events != null && events.Length > 0) { // If there are events, we clear them from the logger, since we're done with them memoryAppender.Clear(); // Iterate through each event foreach (LoggingEvent ev in events) { #if DEBUG // Construct the line we want to trace Trace.WriteLine($"{ev.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss,fff")} [{ev.ThreadName}] {ev.Level} {ev.LoggerName} : {ev.RenderedMessage}"); // Append to the StringBuilder output.Append($"{ev.TimeStamp.ToString("HH:mm:ss,fff")} {ev.Level} : {ev.RenderedMessage}\r\n"); #else if (ev.Level >= Level.Warn) { // Construct the line we want to trace Trace.WriteLine($"{ev.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss,fff")} [{ev.ThreadName}] {ev.Level} {ev.LoggerName} : {ev.RenderedMessage}"); // Append to the StringBuilder output.Append($"{ev.RenderedMessage}\r\n"); } #endif } } // Return the constructed output return(output.ToString()); }