Advertisement
Guest User

Untitled

a guest
Jun 27th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Text;
  6.  
  7. /// <summary>
  8. /// Lazily reads a log4net style log file to parse entries
  9. /// </summary>
  10. /// <remarks>
  11. /// Handles multi-line entries so that entries containing messages
  12. /// or a stack trace with newline characters aren't dropped
  13. /// or picked out as a separate log entry the way that
  14. /// simply splitting the file on newline characters would.
  15. /// </remarks>
  16. public class LogReader
  17. {
  18. const int TIMESTAMP_LENGTH = 23;
  19. const string TIMESTAMP_FORMAT_STRING = "yyyy-MM-dd HH:mm:ss,fff";
  20.  
  21. public IEnumerable<string> Read(string filePath, Func<string, bool> newEntryPredicate = null)
  22. {
  23. // Use the provided function to determine if the string
  24. // is the first line in a log entry otherwise default it
  25. // to using the internal timestamp logic
  26. Func<string, bool> isNewEntry = null;
  27. if(newEntryPredicate == null)
  28. {
  29. isNewEntry = IsNewEntryUsingTimestamp;
  30. }
  31.  
  32. using (FileStream fStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  33. using(StreamReader stReader = new StreamReader(fStream))
  34. {
  35. StringBuilder entryBuilder = new StringBuilder();
  36. string line = stReader.ReadLine();
  37. while(line != null)
  38. {
  39. // New log entry
  40. if(isNewEntry(line))
  41. {
  42. // If the previous line included the end of an entry, remove the trailing newline and yield the value
  43. if (entryBuilder.Length > 0)
  44. {
  45. yield return entryBuilder.ToString().Trim();
  46. entryBuilder.Clear();
  47. }
  48. }
  49. entryBuilder.AppendLine(line);
  50. line = stReader.ReadLine();
  51. }
  52. }
  53. }
  54.  
  55. private bool IsNewEntryUsingTimestamp(string line)
  56. {
  57. DateTime dt;
  58. return line.Length >= 23 && DateTime.TryParseExact((line.Substring(0, TIMESTAMP_LENGTH)), TIMESTAMP_FORMAT_STRING, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement