Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.IO;
- using System.Text;
- /// <summary>
- /// Lazily reads a log4net style log file to parse entries
- /// </summary>
- /// <remarks>
- /// Handles multi-line entries so that entries containing messages
- /// or a stack trace with newline characters aren't dropped
- /// or picked out as a separate log entry the way that
- /// simply splitting the file on newline characters would.
- /// </remarks>
- public class LogReader
- {
- const int TIMESTAMP_LENGTH = 23;
- const string TIMESTAMP_FORMAT_STRING = "yyyy-MM-dd HH:mm:ss,fff";
- public IEnumerable<string> Read(string filePath, Func<string, bool> newEntryPredicate = null)
- {
- // Use the provided function to determine if the string
- // is the first line in a log entry otherwise default it
- // to using the internal timestamp logic
- Func<string, bool> isNewEntry = null;
- if(newEntryPredicate == null)
- {
- isNewEntry = IsNewEntryUsingTimestamp;
- }
- using (FileStream fStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
- using(StreamReader stReader = new StreamReader(fStream))
- {
- StringBuilder entryBuilder = new StringBuilder();
- string line = stReader.ReadLine();
- while(line != null)
- {
- // New log entry
- if(isNewEntry(line))
- {
- // If the previous line included the end of an entry, remove the trailing newline and yield the value
- if (entryBuilder.Length > 0)
- {
- yield return entryBuilder.ToString().Trim();
- entryBuilder.Clear();
- }
- }
- entryBuilder.AppendLine(line);
- line = stReader.ReadLine();
- }
- }
- }
- private bool IsNewEntryUsingTimestamp(string line)
- {
- DateTime dt;
- return line.Length >= 23 && DateTime.TryParseExact((line.Substring(0, TIMESTAMP_LENGTH)), TIMESTAMP_FORMAT_STRING, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement