Streaming Logs Using Windows PowerShell



WHY SHOULD YOU IMPLEMENT LOGGING?

Log data helps technical personnel quickly drill down on application related issues including:

  • Pinpointing areas of poor performance
  • Assessing application health and troubleshooting
  • Diagnosing and identifying the root cause of application installation and run-time errors

There are a lot of tools available in the market which help you stream logs. But with most of them, I have personally experienced if they are easy to use they are paid and most of open source is too complex to configure. In this blog, I will explain how you can implement a simple log streaming tool using Powershell. This is more of a dev/debug helper tool, although if you invest time in the building then you can take it to a product level tool.

To start with,  below is a simple one-line Powershell which will read log file data in real time. The best part is it will WAIT for any more logs to be written on file and will stream it as soon as it completes on the file.

Get-Content "****LOG FILE PATH***" -WAIT

To take it to the next level let's manipulate the logs written before they are presented on screen. In the below code sample if you provide a log with the message containing "*" then the script will change all "*" to "@" before presenting.
Sample log message: INFO InfoLog - ***************CONFIG READ***************
  1. $file = "*******LOG FILE PATH********"  
  2. Get - Content $file - Wait | ForEach - Object - Begin {  
  3.     $counter = 1  
  4.     $lines = @(Get - Content $file).Count  
  5. } - Process {  
  6.     if ($counter++ - gt $lines) {  
  7.         Write - host $_.ToString().Replace("*""@")  
  8.     }  
  9. }  
Let's take it a bit further. Suppose we need to present Error type messages to be highlighted with RED. And the rest of the message must be in GREEN.
Sample log message: INFO InfoLog - ***************CONFIG READ****************
Sample log message: ERROR ErrorLog - ************CONFIG READ****************
  1. $file = "*******LOG FILE PATH********"  
  2. Get - Content $file - Wait | ForEach - Object - Begin {  
  3.     $counter = 1  
  4.     $lines = @(Get - Content $file).Count  
  5. } - Process {  
  6.     if ($counter++ - gt $lines) {  
  7.         if ($_.ToString().Contains("ERROR")) {  
  8.             Write - host $_.ToString() - foregroundcolor "red"  
  9.         } else {  
  10.             Write - host $_.ToString() - foregroundcolor "green"  
  11.         }  
  12.     }  
  13. }  
There are endless possibilities and use cases which can be implemented, the sky is the limit. But for a quick start, you can use scripts which will help you to get rid of reading those dumb text files using Notepad: