Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appropriate logging in Powershell

If I have a powershell script say called caller.ps1 which looks like this

.\Lib\library.ps1

$output = SomeLibraryFunction

where library.ps1 looks like the following

function SomeLibraryFunction()
{
   Write-Output "Some meaningful function logging text"
   Write-Output "return value"
}

What I'd like to achieve is a way in which the library function can return it's value but also add some logging messages that allow the caller to process those internal messages as they see fit. The best I can think of is to write both to the pipeline and then the caller will have an array with the actual return value plus the internal messages which may be of use to a logger the calling script has.

Am I going about this problem the right way? Is there a better way to achieve this?

like image 353
user1054637 Avatar asked May 15 '26 04:05

user1054637


1 Answers

It's usually not a good idea to mix logging messages with actual output. Consumers of your function then have to do a lot of filtering to find the object they really want.

Your function should write logging messages to the verbose output stream. If the caller wants to see those messages, it can by specifying the -Verbose switch to your function.

function SomeLibraryFunction()
{
    [CmdletBinding()]
    param(
    )

    Write-Verbose "Some meaningful function logging text"
    Write-Output "return value"
}

In PowerShell 3+, consumers can redirect your verbose messages to the output stream or a file:

# Show verbose logging messages on the console
SomeLibraryFunction -Verbose 

# Send verbose logging messages to a file
SomeLibraryFunction -Verbose 4> verbose.txt

# redirect verbose message to the output stream
SomeLibraryFunction -Verbose 4>&1 

Other options include:

  • Writing to a well-known file
  • Writing to the Event Log
  • Use Start-Transcript to create a log of the session.
like image 118
Aaron Jensen Avatar answered May 18 '26 03:05

Aaron Jensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!