Skip to content

Instantly share code, notes, and snippets.

@chriskuech
Last active April 2, 2020 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriskuech/c952504aef2e73fce9ff7a7155fff3de to your computer and use it in GitHub Desktop.
Save chriskuech/c952504aef2e73fce9ff7a7155fff3de to your computer and use it in GitHub Desktop.
# ContextLogger.psm1
$ContextStack = [System.Collections.Stack]::new()
function Invoke-InContext {
Param(
[ValidateNotNullOrEmpty()]
[string] $Name,
[ValidateNotNullOrEmpty()]
[scriptblock] $ScriptBlock
)
Write-Log "<$Name>"
$ContextStack.Push($Name)
$start = Get-Date
& $ScriptBlock | % {Write-Log $_} # format each line of output
$stop = Get-Date
$ContextStack.Pop()
Write-Log "</$Name> $($stop - $start)"
}
function Write-Log {
Param(
[ValidateNotNullOrEmpty()]
[string] $Message
)
$timestamp = Get-Date -Format 'MM/dd hh:mm:ss'
$contextArray = $ContextStack.ToArray()
[array]::Reverse($contextArray)
Write-Output "$timestamp [$($contextArray -join ">")] $Message"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment