Realtime View of Sitecore development logs
In linux environments I typically monitor logs using the tail
command. It’s often installed by default and proves quite useful for viewing the latest log entries in realtime.
Windows, on the other hand, does not come with this functionality. Here’s a simple powershell script that works very similar to the tail command and has highlighting enabled for typical log4j logs. It loads the latest log file the given prefix. In this case it will load the latest log file starting with the Sitecore
prefix.
The script is called like this: .\tail.ps1 .\App_Data\logs\Sitecore
param (
[Parameter(Mandatory = $true)]
[string]$Stem
)
function Get-LatestLogFile {
$directory = Split-Path $Stem
$filename = Split-Path $Stem -Leaf
$pattern = "$filename*.log"
$files = Get-ChildItem -Path $directory -Filter $pattern -File | Sort-Object LastWriteTime -Descending
if ($files.Count -eq 0) {
Write-Host "No log files found with stem '$Stem'" -ForegroundColor Red
exit 1
}
return $files[0].FullName
}
function Write-ColoredEntry {
param ([string[]]$entry)
$text = $entry -join "`n"
switch -Regex ($text) {
'\bFATAL\b' { Write-Host $text -ForegroundColor Magenta; break }
'\bERROR\b' { Write-Host $text -ForegroundColor Red; break }
'\bWARN\b' { Write-Host $text -ForegroundColor Yellow; break }
'\bDEBUG\b' { Write-Host $text -ForegroundColor Cyan; break }
default { Write-Host $text }
}
}
function Tail-Follow {
param (
[string]$FilePath,
[int]$Lines = 10,
[int]$Interval = 1
)
$encoding = [System.Text.Encoding]::UTF8
$fs = [System.IO.File]::Open($FilePath, 'Open', 'Read', 'ReadWrite')
$reader = New-Object System.IO.StreamReader($fs, $encoding)
# Read last N lines
$content = Get-Content -Path $FilePath -Tail $Lines
$buffer = @()
foreach ($line in $content) {
if ($line -match '^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}') {
if ($buffer.Count -gt 0) {
Write-ColoredEntry -entry $buffer
$buffer = @()
}
}
$buffer += $line
}
if ($buffer.Count -gt 0) {
Write-ColoredEntry -entry $buffer
}
# Move to end of file
$reader.BaseStream.Seek(0, [System.IO.SeekOrigin]::End) | Out-Null
$entryBuffer = @()
while ($true) {
$line = $reader.ReadLine()
if ($line -ne $null) {
if ($line -match '^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}') {
if ($entryBuffer.Count -gt 0) {
Write-ColoredEntry -entry $entryBuffer
$entryBuffer = @()
}
}
$entryBuffer += $line
} else {
if ($entryBuffer.Count -gt 0) {
Write-ColoredEntry -entry $entryBuffer
$entryBuffer = @()
}
Start-Sleep -Seconds $Interval
}
}
}
# Main
$logFile = Get-LatestLogFile
Write-Host "Following log file: $logFile" -ForegroundColor Cyan
Tail-Follow -FilePath $logFile