Last active
September 23, 2024 12:45
-
-
Save Calvindd2f/c8995c90f59b52db3b723ff371aa9288 to your computer and use it in GitHub Desktop.
All in one logging solution. Not intended to get to complex, just get the job done and done right. Includes a switch named show, which - if present, will also print the log to console. If Write-Log is called with the Verbose parameter it will always print to console
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
| Function Write-Log | |
| { | |
| [Alias('log')] | |
| [CmdletBinding()] | |
| param | |
| ( | |
| [string]$log, # Log message | |
| [switch]$show, # Show log message in console | |
| [string]$logfile # Optional log file path, defaults to current script name with timestamp | |
| ) | |
| [string]$logtime = (Get-Date -Format "[dd/MM/yyyy HH:mm:ss zz] |"); | |
| if (-not $logfile) | |
| { | |
| $scriptName = $MyInvocation.MyCommand.Name; | |
| $timestamp = Get-Date -Format "dd_MM_yyyy_HH_mm"; | |
| $logfile = "$env:TEMP\$timestamp-$scriptName.log"; | |
| } | |
| foreach ($line in ($log -split "`n")) | |
| { | |
| if ($VerbosePreference -eq 'Continue' -or $show.IsPresent) | |
| { | |
| [console]::WriteLine("$logtime $line"); | |
| } | |
| try | |
| { | |
| $logEntry = [string]::Concat($logtime, " ", $line, [Environment]::NewLine); | |
| $logEntry >> $llogfile; | |
| } | |
| catch | |
| { | |
| Write-Error "Failed to write log entry to file: $($_.Exception.Message)" | |
| } | |
| } | |
| } |
Author
Author
FINAL NOTE:
You can append this function to your profile by executing the following in either PowerShell Core or Windows PowerShell - ideally both.
@'
Function Write-Log
{
[Alias('log')]
[CmdletBinding()]
param
(
[string]$log, # Log message
[switch]$show, # Show log message in console
[string]$logfile # Optional log file path, defaults to current script name with timestamp
)
[string]$logtime = (Get-Date -Format "[dd/MM/yyyy HH:mm:ss zz] |");
if (-not $logfile)
{
$scriptName = $MyInvocation.MyCommand.Name;
$timestamp = Get-Date -Format "dd_MM_yyyy_HH_mm";
$logfile = "$env:TEMP\$timestamp-$scriptName.log";
}
foreach ($line in ($log -split "`n"))
{
if ($VerbosePreference -eq 'Continue' -or $show.IsPresent)
{
[console]::WriteLine("$logtime $line");
}
try
{
$logEntry = [string]::Concat($logtime, " ", $line, [Environment]::NewLine);
$logEntry >> $llogfile;
}
catch
{
Write-Error "Failed to write log entry to file: $($_.Exception.Message)"
}
}
}
'@ >> $profile
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Refactoring Write-Log to implement improvements and additional features like setting a default logfile name format and supporting flexible calls.
Key Refactoring:
Refactored Function:
Key Changes and Enhancements:
Alias log: Added
Set-Alias -Name log -Value Write-Logto allow calling the function as log for convenience.Flexible Invocation: The function can now be called as
log('example log msg', $true)orlog('example log msg'), where$trueis optional and enables the$showswitch to print to the console.Default Log File Name: If the
$logfileparameter is not provided, it will default to a log file named in the format"DD_MM_YYYY_HH_MM-$PowerShellScriptName.log"located in$env:TEMP.The script name is derived from
$MyInvocation.MyCommand.Name.Improved String Handling: Used
[string]::Concat()for efficient string concatenation and[Environment]::NewLinefor platform-independent line breaks.Efficient Appending to Log File: The log entries are appended using Add-Content, ensuring the log file grows as new entries are added.
Added a try-catch block to handle file I/O errors gracefully.
Optional Console Output:
The
$show parameter(switch) determines whether the log message is printed to the console. If$showis provided or$VerbosePreferenceis enabled, the log will be printed to the console.Usage Examples:
Example 1: Logging with Console Output
Example 2: Logging without Console Output
Example 3: Custom Log File Path
Sample Output in the Log File:
[23/09/2024 14:53:00 +00] | example log msgAdditional Enhancements:
Verbose Logging: The function respects $VerbosePreference, so if you run the script with -Verbose, it will automatically print logs to the console.
Customizable Log Path: Users can specify their own log file path if needed.
This provides clean and effective logging, with flexible invocation, robust log hanndling & streamlined file I/O.