Search code examples
c#serviceconsolewindows-services

How to monitor windows service text output


For my windows service, I have a procedure that outputs log entries to a text file. That all works well, but I can not see it live. As soon as I open the file to see the log, it stops writing to it, because the service can't write to an open file, I'm assuming.

My question: Is there a way to monitor this text output with something like the console? This solution will only be used for debugging purposes. I don't want a GUI or anything like that--just something simple to watch what my logger is doing.

Right now to write to the text file I'm doing:

RecordDataToLog("Log this");

private void RecordDataToLog(string txtData)
{
    using (System.IO.StreamWriter file = new System.IO.StreamWriter(logFileDir, true))
        file.WriteLine(txtData);
}

I tried to use Console like this, but it didn't work--no console window showed.

Console.WriteLine("Log this");

Or is there another text editor or text file type that supports writing to an open file?


Solution

  • I opened the file with notepad and Notepad++ and was still able to write to the file with StreamWriter, so it must be the editor you are opening the file with. Notepad doesn't refresh the contents at all. You need to reopen the file. Notepadd++ should prompt you and ask if you want to reload.

    PowerShell v3 includes an option on the Get-Content cmdlet to open a file and print new content as it is added, similar to tail on *nix OSes:

    Get-Content "C:\path\to\log\file" -Wait