Click here to Skip to main content
15,867,933 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Live Log Viewer

Rate me:
Please Sign up or sign in to vote.
4.98/5 (27 votes)
14 Jun 2016CPOL2 min read 136.3K   11.5K   94   16
Monitors log files and displays text as it is appended to the file

Update: Code has been moved to GitHub

Introduction

As a member of an IT Helpdesk team, I am constantly trawling through logs trying to find out "what went wrong?" This is especially time-consuming when troubleshooting issues with Windows Services and background applications. With some applications and services producing large (50MB+) log files, I often find myself moving or renaming the old log files so I can get a small, easy-to-read file that displays the most recent entries since the service/application was restarted.

This tool eliminates these problems by monitoring the file and displaying any text that is written to it on-the-fly. It uses a custom WinForms TabPage control, called LogTabPage with a nested LogWatcher class that inherits FileSystemWatcher. The FileSystemWatcher class provides the functions for monitoring the file for changes and I simply use a FileStream/StreamReader combination to read the text and append it to a TextBox.

Image 1

LogTabPage Class

The LogTabPage class is a custom TabPage that contains a single RichTextBox and a nested LogWatcher class to monitor the log file. It contains code for creating the LogWatcher and appending text to the RichTextBox.

C#
class LogTabPage : TabPage
   {
       //The textbox where the log will be displayed
       internal RichTextBox TextBox = new RichTextBox();
       //The LogWatcher that monitors the file
       internal LogWatcher Watcher;

       //Constructor for the LogTabPage
       public LogTabPage(string FileName, string Suffix)
       {
           //Display the filename on the Tab
           this.Text = Path.GetFileName(string.Format("{0} {1}", FileName, Suffix));

           //Configure the TextBox
           TextBox.Dock = DockStyle.Fill;
           TextBox.BackColor = Color.White;
           TextBox.ReadOnly = true;

           //Add the TextBox to the LogTabPage
           this.Controls.Add(TextBox);

           //Create the LogWatcher
           CreateWatcher(FileName);
       }

       private void CreateWatcher(string FileName)
       {
           Watcher = new LogWatcher(FileName);

           //Set the directory of the file to monitor
           Watcher.Path = Path.GetDirectoryName(FileName);

           //Raise events when the LastWrite or Size attribute is changed
           Watcher.NotifyFilter = (NotifyFilters.LastWrite | NotifyFilters.Size);

           //Filter out events for only this file
           Watcher.Filter = Path.GetFileName(FileName);

           //Subscribe to the event
           Watcher.TextChanged += new LogWatcher.LogWatcherEventHandler(Watcher_Changed);

           //Enable the event
           Watcher.EnableRaisingEvents = true;
       }

       //Occurs when the file is changed
       void Watcher_Changed(object sender, LogWatcherEventArgs e)
       {
           //Invoke the AppendText method if required
           if (TextBox.InvokeRequired) this.Invoke(new Action(delegate() { AppendText(e.Contents); }));
           else AppendText(e.Contents);
       }

       private void AppendText(string Text)
       {
           //Append the new text to the TextBox
           TextBox.Text += Text;

           //If the Frozen function isn't enabled then scroll to the bottom of the TextBox
           if (!MainForm.Frozen)
           {
               TextBox.SelectionStart = TextBox.Text.Length;
               TextBox.SelectionLength = 0;
               TextBox.ScrollToCaret();
           }
       }

LogWatcher Class

The LogWatcher class is an extension of the FileSystemWatcher class that includes methods for reading the text from the file and an event for when the text is changed.

C#
internal class LogWatcher : FileSystemWatcher
   {
       //The name of the file to monitor
       internal string FileName;

       //The FileStream for reading the text from the file
       FileStream Stream;
       //The StreamReader for reading the text from the FileStream
       StreamReader Reader;

       //Constructor for the LogWatcher class
       public LogWatcher(string FileName)
       {
           //Subscribe to the Changed event of the base FileSystemWatcher class
           this.Changed += OnChanged;

           //Set the filename of the file to watch
           this.FileName = FileName;

           //Create the FileStream and StreamReader object for the file
           Stream = new System.IO.FileStream
               (FileName,FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
           Reader = new System.IO.StreamReader(Stream);

           //Set the position of the stream to the end of the file
           Stream.Position =  Stream.Length;
       }

       //Occurs when the file is changed
       public void OnChanged(object o, FileSystemEventArgs e)
       {
           //Read the new text from the file
           string Contents = Reader.ReadToEnd();

           //Fire the TextChanged event
           LogWatcherEventArgs args = new LogWatcherEventArgs(Contents);
           if (TextChanged != null) TextChanged(this, args);
       }

       public delegate void LogWatcherEventHandler(object sender, LogWatcherEventArgs e);

       //Event that is fired when the file is changed
       public event LogWatcherEventHandler TextChanged;
   }

History

I originally created the application in VB.NET with little knowledge of .NET. I have since re-written it in C#.

Update: An updated version (4.0) is now available. Extra features include support for different Encodings and Fonts as requested. Links have been provided to both the executable and the source. This is a major rewrite using C# and WPF. The code in version 4.0 is very different to the code posted in the tip.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Help desk / Support
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAlternatives? Pin
MLansdaal17-Jun-16 6:44
MLansdaal17-Jun-16 6:44 
AnswerRe: Alternatives? Pin
Alex Wiese19-Jun-16 19:13
Alex Wiese19-Jun-16 19:13 
QuestionGitHub Pin
Alex Wiese14-Jun-16 19:15
Alex Wiese14-Jun-16 19:15 
QuestionRotating logs Pin
Moyo3148-Sep-15 21:36
Moyo3148-Sep-15 21:36 
QuestionIs the timer values different in the EXE from the Source code? Pin
solutionsville28-Aug-15 8:58
solutionsville28-Aug-15 8:58 
QuestionEnhancements Pin
sam.hill4-Feb-15 11:10
sam.hill4-Feb-15 11:10 
AnswerRe: Enhancements Pin
Ivan Sørensen19-Apr-17 10:26
Ivan Sørensen19-Apr-17 10:26 
SuggestionClear file button and Initial file read Pin
Pratik Gaikwad19-Dec-14 6:02
Pratik Gaikwad19-Dec-14 6:02 
Hi Alex,

Great Application!!! Thanks for writing such a nice code... I would like to suggest couple of things... can you please add those as well?

1. Please add "Clear File" button. This should clear out the contents of text area as well as the file. Nothing more...
2. When application is started and file is loaded, nothing is displayed initially even though file has some contents in it...

Can you please modify the code per above suggestions?
Questioncannot import livelogviewer.pfx Pin
Member 1116492314-Nov-14 13:16
Member 1116492314-Nov-14 13:16 
AnswerRe: cannot import livelogviewer.pfx Pin
Alex Wiese4-Dec-14 12:59
Alex Wiese4-Dec-14 12:59 
SuggestionFile encoding Pin
Post0lka25-Sep-14 22:53
Post0lka25-Sep-14 22:53 
GeneralRe: File encoding Pin
Alex Wiese2-Nov-14 18:55
Alex Wiese2-Nov-14 18:55 
QuestionAlternative Pin
aSarafian23-Apr-12 20:30
aSarafian23-Apr-12 20:30 
QuestionFile System Watcher Pin
Bojan Sala23-Apr-12 4:35
professionalBojan Sala23-Apr-12 4:35 
AnswerRe: File System Watcher Pin
Bassam Saoud23-Apr-12 6:45
Bassam Saoud23-Apr-12 6:45 
GeneralRe: File System Watcher Pin
Alex Wiese23-Apr-12 18:01
Alex Wiese23-Apr-12 18:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.