Skip to content

Commit

Permalink
Converted to environment variables
Browse files Browse the repository at this point in the history
  • Loading branch information
VertigoRay committed Jan 13, 2023
1 parent 8391063 commit 00a2fdf
Show file tree
Hide file tree
Showing 11 changed files with 136 additions and 160 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
SerializationVersion: 1.1.0.1
**********************
#>
function Write-InvocationHeader {
function Get-InvocationHeader {
[CmdletBinding()]
param()

Expand Down Expand Up @@ -56,7 +56,7 @@ function Write-InvocationHeader {
}

$tmp.FullName | Remove-Item -ErrorAction 'SilentlyContinue' -Force

Write-Log -Message $header
$env:PSWriteLogIncludeInvocationHeader = $null

return $header
}
75 changes: 39 additions & 36 deletions PSWriteLog/Private/Write-Log.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,12 @@ function global:Write-Log {
)

begin {
# Microsoft.PowerShell.Utility\Write-Information "[Write-Log] BoundParameters: $($MyInvocation.BoundParameters | Out-String)" -Tags 'VertigoRay\PSWriteLog','Write-Log'
if ($IncludeInvocationHeader) {
Write-InvocationHeader
Microsoft.PowerShell.Utility\Write-Debug ('[Write-Log] BoundParameters: {0}' -f $($MyInvocation.BoundParameters | Out-String))

if ($env:PSWriteLogDisableLogging) {
# If logging is not currently disabled, get out now!
Microsoft.PowerShell.Utility\Write-Debug ('[Write-Log] env:PSWriteLogDisableLogging: {0}' -f $env:PSWriteLogDisableLogging)
return $null
}

# Get the name of this function
Expand All @@ -119,11 +122,11 @@ function global:Write-Log {

[System.Collections.ArrayList] $legacyMessage = @()

$legacyMessage.Add("[$(& $logDate) $(& $logTime)]") | Out-Null
$legacyMessage.Add(('[{0}]' -f (Get-Date -Format 'O'))) | Out-Null
if ($Source) {
$legacyMessage.Add("[${Source}]") | Out-Null
}
$legacyMessage.Add("[${Component}]") | Out-Null
# $legacyMessage.Add("[${Component}]") | Out-Null
$legacyMessage.Add("[${Severity}]") | Out-Null
$legacyMessage.Add(($lMessage.Trim() | Out-String)) | Out-Null

Expand All @@ -136,7 +139,7 @@ function global:Write-Log {
[string]
$lMessage
)
# Microsoft.PowerShell.Utility\Write-Information "[Write-Log] Source (sb): ${Source}" -Tags 'VertigoRay\PSWriteLog','Write-Log'
Microsoft.PowerShell.Utility\Write-Debug "[Write-Log] Source (sb): ${Source}"
$severityMap = @{ # Vaguely based on POSH stream numbers
Debug = 5
Error = 3
Expand All @@ -162,17 +165,19 @@ function global:Write-Log {
))
}

[scriptblock] $getLogLine = {
[scriptblock] $logLine = {
param(
[string]
$sMsg
)
## Choose which log type to write to file
if ($LogType -ieq 'CMTrace') {
return & $cmTraceLogString -lMessage ($sMsg | Out-String).Trim() -lSource $Source
$line = if ($LogType -ieq 'CMTrace') {
& $cmTraceLogString -lMessage ($sMsg | Out-String).Trim() -lSource $Source
} else {
return & $legacyLogString -lMessage ($sMsg | Out-String).Trim() -lSource $Source
& $legacyLogString -lMessage ($sMsg | Out-String).Trim() -lSource $Source
}

$line | Out-File -FilePath $FilePath.FullName -Append -NoClobber -Force -Encoding 'UTF8' -ErrorAction 'Stop'
}

# Create the directory where the log file will be saved
Expand All @@ -182,28 +187,26 @@ function global:Write-Log {
}

process {
# Exit function if it is a debug message and 'LogDebugMessage' option is not $true, or if the log directory was not successfully created in 'Begin' block.
if (($DebugMessage -and -not $LogDebugMessage)) { Return }
if ($IncludeInvocationHeader) {
& $logLine -sMsg ("{1}`n{0}`n{1}" -f (Get-InvocationHeader),('#' * 40))
}

foreach ($msg in $Message) {
# Microsoft.PowerShell.Utility\Write-Information "[Write-Log] Source: $Source" -Tags 'VertigoRay\PSWriteLog','Write-Log'
# Write the log entry to the log file if logging is not currently disabled
if (-not $DisableLogging) {
try {
& $getLogLine -sMsg $msg | Out-File -FilePath $FilePath.FullName -Append -NoClobber -Force -Encoding 'UTF8' -ErrorAction 'Stop'
} catch {
if (-not $ContinueOnError) {
throw ('[{0} {1}] [{2}] [{3}] :: Failed to write message [{4}] to the log file [{5}].{6}{7}' -f @(
& $logDate
& $logTime
$CmdletName
$Component
$Msg
$FilePath.FullName
"`n"
Resolve-Error | Out-String
))
}
Microsoft.PowerShell.Utility\Write-Debug ('[Write-Log] Source: {0}' -f $Source)
try {
& $logLine -sMsg $msg
} catch {
if (-not $ContinueOnError) {
throw ('[{0} {1}] [{2}] [{3}] :: Failed to write message [{4}] to the log file [{5}].{6}{7}' -f @(
& $logDate
& $logTime
$CmdletName
$Component
$Msg
$FilePath.FullName
"`n"
Resolve-Error | Out-String
))
}
}
}
Expand All @@ -214,29 +217,29 @@ function global:Write-Log {
if ($MaxLogFileSizeMB) {
try {
[decimal] $LogFileSizeMB = $FilePath.Length/1MB
# Microsoft.PowerShell.Utility\Write-Information "[Write-Log] LogFileSizeMB: $LogFileSizeMB / $MaxLogFileSizeMB" -Tags 'VertigoRay\PSWriteLog','Write-Log'
Microsoft.PowerShell.Utility\Write-Debug "[Write-Log] LogFileSizeMB: $LogFileSizeMB / $MaxLogFileSizeMB"
if ($LogFileSizeMB -gt $MaxLogFileSizeMB) {
# Microsoft.PowerShell.Utility\Write-Information "[Write-Log] Log File Needs to be archived ..." -Tags 'VertigoRay\PSWriteLog','Write-Log'
Microsoft.PowerShell.Utility\Write-Debug "[Write-Log] Log File Needs to be archived ..."
# Change the file extension to "lo_"
[string] $archivedOutLogFile = [IO.Path]::ChangeExtension($FilePath.FullName, 'lo_')

# Log message about archiving the log file
if ((Get-PSCallStack)[1].Command -ne 'Write-Log') {
# Prevent Write-Log from looping more than once.
& $getLogLine -sMsg "Maximum log file size [${MaxLogFileSizeMB} MB] reached. Rename log file to: ${archivedOutLogFile}" | Out-File -FilePath $FilePath.FullName -Append -NoClobber -Force -Encoding 'UTF8' -ErrorAction 'Stop'
& $logLine -sMsg "Maximum log file size [${MaxLogFileSizeMB} MB] reached. Rename log file to: ${archivedOutLogFile}"
}

# Archive existing log file from <filename>.log to <filename>.lo_. Overwrites any existing <filename>.lo_ file. This is the same method SCCM uses for log files.
Move-Item -Path $FilePath.FullName -Destination $archivedOutLogFile -Force -ErrorAction 'Stop'

# Start new log file and Log message about archiving the old log file
& $getLogLine -sMsg "Maximum log file size [${MaxLogFileSizeMB} MB] reached. Previous log file was renamed to: ${archivedOutLogFile}" | Out-File -FilePath $FilePath.FullName -Append -NoClobber -Force -Encoding 'UTF8' -ErrorAction 'Stop'
& $logLine -sMsg "Maximum log file size [${MaxLogFileSizeMB} MB] reached. Previous log file was renamed to: ${archivedOutLogFile}"
} else {
# Microsoft.PowerShell.Utility\Write-Information "[Write-Log] Log File does not need to be archived." -Tags 'VertigoRay\PSWriteLog','Write-Log'
Microsoft.PowerShell.Utility\Write-Debug "[Write-Log] Log File does not need to be archived."
}
} catch {
# If renaming of file fails, script will continue writing to log file even if size goes over the max file size
# Microsoft.PowerShell.Utility\Write-Information "[Write-Log] Archive Error: ${_}" -Tags 'VertigoRay\PSWriteLog','Write-Log'
Microsoft.PowerShell.Utility\Write-Debug "[Write-Log] Archive Error: ${_}"
}
}
}
Expand Down
17 changes: 5 additions & 12 deletions PSWriteLog/Public/Write-Debug.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,7 @@ function global:Write-Debug {
[Alias('Msg')]
[AllowEmptyString()]
[string]
${Message},

[switch]
$NoLog,

[switch]
$Silent
${Message}
)

begin
Expand All @@ -28,14 +22,13 @@ function global:Write-Debug {
'Source' = "${invoFile}:$($MyInvocation.ScriptLineNumber)";
}

if (-not $Silent) {
if (-not ($env:PSWriteLogDebugSilent -as [bool])) {
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$PSBoundParameters.Remove('NoLog') | Out-Null
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Microsoft.PowerShell.Utility\Write-Debug', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = { & $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
Expand All @@ -48,13 +41,13 @@ function global:Write-Debug {

process
{
if (-not $NoLog.isPresent) {
if (-not ($env:PSWriteLogDebugNoLog -as [bool])) {
if ((Get-Command 'Write-Log' -ErrorAction 'Ignore') -and ($DebugPreference -ine 'SilentlyContinue')) {
Write-Log @writeLog -Message $Message
}
}

if (-not $Silent) {
if (-not ($env:PSWriteLogDebugSilent -as [bool])) {
try {
$steppablePipeline.Process($_)
} catch {
Expand All @@ -65,7 +58,7 @@ function global:Write-Debug {

end
{
if (-not $Silent) {
if (-not ($env:PSWriteLogDebugSilent -as [bool])) {
try {
$steppablePipeline.End()
} catch {
Expand Down
11 changes: 4 additions & 7 deletions PSWriteLog/Public/Write-Error.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,7 @@ function global:Write-Error {

[Alias('TargetType')]
[string]
${CategoryTargetType},

[switch]
$Silent
${CategoryTargetType}
)

begin
Expand All @@ -69,7 +66,7 @@ function global:Write-Error {
'Source' = "${invoFile}:$($MyInvocation.ScriptLineNumber)";
}

if (-not $Silent) {
if (-not ($env:PSWriteLogErrorSilent -as [bool])) {
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
Expand Down Expand Up @@ -117,7 +114,7 @@ function global:Write-Error {
Write-Log @writeLog -Message ($msg -join ' ') -ErrorAction 'Stop'
}

if (-not $Silent) {
if (-not ($env:PSWriteLogErrorSilent -as [bool])) {
try {
$steppablePipeline.Process($_)
} catch {
Expand All @@ -128,7 +125,7 @@ function global:Write-Error {

end
{
if (-not $Silent) {
if (-not ($env:PSWriteLogErrorSilent -as [bool])) {
try {
$steppablePipeline.End()
} catch {
Expand Down
11 changes: 4 additions & 7 deletions PSWriteLog/Public/Write-Host.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@ function global:Write-Host {
${ForegroundColor},

[System.ConsoleColor]
${BackgroundColor},

[switch]
$Silent
${BackgroundColor}
)

begin
Expand All @@ -34,7 +31,7 @@ function global:Write-Host {
'Source' = "${invoFile}:$($MyInvocation.ScriptLineNumber)";
}

if (-not $Silent) {
if (-not ($env:PSWriteLogHostSilent -as [bool])) {
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
Expand All @@ -57,7 +54,7 @@ function global:Write-Host {
Write-Log @writeLog -Message $Object
}

if (-not $Silent) {
if (-not ($env:PSWriteLogHostSilent -as [bool])) {
try {
$steppablePipeline.Process($_)
} catch {
Expand All @@ -68,7 +65,7 @@ function global:Write-Host {

end
{
if (-not $Silent) {
if (-not ($env:PSWriteLogHostSilent -as [bool])) {
try {
$steppablePipeline.End()
} catch {
Expand Down
13 changes: 5 additions & 8 deletions PSWriteLog/Public/Write-Information.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ function global:Write-Information {

[Parameter(Position=1)]
[string[]]
${Tags},

[switch]
$Silent
${Tags}
)

begin
Expand All @@ -27,7 +24,7 @@ function global:Write-Information {
'Source' = "${invoFile}:$($MyInvocation.ScriptLineNumber)";
}

if (-not $Silent) {
if (-not ($env:PSWriteLogInformationSilent -as [bool])) {
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
Expand All @@ -48,13 +45,13 @@ function global:Write-Information {
{
if ((Get-Command 'Write-Log' -ErrorAction 'Ignore') -and ($InformationPreference -ine 'SilentlyContinue')) {
if ($Tags.isPresent) {
Write-Log @writeLog -Message "$MessageData {$($Tags -join ',')}"
Write-Log @writeLog -Message "{$($Tags -join ',')} $MessageData"
} else {
Write-Log @writeLog -Message "$MessageData"
}
}

if (-not $Silent) {
if (-not ($env:PSWriteLogInformationSilent -as [bool])) {
try {
$steppablePipeline.Process($_)
} catch {
Expand All @@ -65,7 +62,7 @@ function global:Write-Information {

end
{
if (-not $Silent) {
if (-not ($env:PSWriteLogInformationSilent -as [bool])) {
try {
$steppablePipeline.End()
} catch {
Expand Down
7 changes: 2 additions & 5 deletions PSWriteLog/Public/Write-Output.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@ function global:Write-Output {
${InputObject},

[switch]
${NoEnumerate},

[switch]
$Log
${NoEnumerate}
)

begin
Expand Down Expand Up @@ -45,7 +42,7 @@ function global:Write-Output {

process
{
if ((Get-Command 'Write-Log' -ErrorAction 'Ignore') -and $Log.IsPresent) {
if ((Get-Command 'Write-Log' -ErrorAction 'Ignore') -and ($env:PSWriteLogOutputLog -as [bool])) {
Write-Log @writeLog -Message ($InputObject | Out-String)
}

Expand Down
Loading

0 comments on commit 00a2fdf

Please sign in to comment.