Created
April 16, 2018 11:04
-
-
Save karanjitsingh/f81017cf8ba3e8ec725d89a2b1b9dfb4 to your computer and use it in GitHub Desktop.
Custom log sanitizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| param( | |
| [string] $logfile | |
| ) | |
| $nonProtocolRegex = "^(?!.*PROTOCOL).*$" | |
| $protocolRegex = "^.*(send|receive):(.*)" | |
| function Format-Json([Parameter(Mandatory, ValueFromPipeline)][String] $json) { | |
| $indent = 0; | |
| ($json -Split '\r\n' | | |
| % { | |
| if ($_ -match '^\s*[\}\]]') { | |
| # This line contains ] or }, decrement the indentation level | |
| $indent-- | |
| } | |
| $line = (' ' * $indent * 4) + $_.TrimStart().Replace(': ', ': ') | |
| if ($_ -match '(^\s*[\[\{]$)|(^\s*".*":\s*[\{\[])') { | |
| # This line contains [ or {, increment the indentation level | |
| $indent++ | |
| } | |
| $line | |
| }) -Join "`r`n" | |
| } | |
| if(Test-Path $logfile) { | |
| $json = "{" | |
| foreach($line in Get-Content $logfile) { | |
| if(!($line -cmatch $nonProtocolRegex)) { | |
| if($line -match $protocolRegex) { | |
| $prettyvalue = $Matches[2] | ConvertFrom-Json | ConvertTo-Json | |
| $prettyvalue = $prettyvalue -replace '\r\n', "`r`n " -join "`r`n" | |
| $jsonvalue = "`"$($Matches[1])`": $prettyvalue" | |
| if($json -eq "{") { | |
| $json = "$json`r`n $jsonvalue" | |
| } | |
| else { | |
| $json = "$json,`r`n $jsonvalue" | |
| } | |
| } | |
| } | |
| } | |
| $json = "$json`r`n}" | |
| $json = Format-Json $json | |
| $json = $json -replace "\{[\s\n]*\}", "{}" | |
| $json | Out-File -LiteralPath $logfile -Force | |
| Write-Host $json | |
| } | |
| else { | |
| Write-Error "Not such file."; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment