use*_*637 3 powershell logging
如果我有一个名为caller.ps1的powershell脚本,它看起来像这样
.\Lib\library.ps1
$output = SomeLibraryFunction
Run Code Online (Sandbox Code Playgroud)
其中library.ps1如下所示
function SomeLibraryFunction()
{
Write-Output "Some meaningful function logging text"
Write-Output "return value"
}
Run Code Online (Sandbox Code Playgroud)
我想要实现的是库函数可以返回它的值的方式,但也添加一些日志消息,允许调用者在他们认为合适时处理这些内部消息.我能想到的最好的方法是将两者写入管道,然后调用者将拥有一个具有实际返回值的数组以及可能对调用脚本具有的记录器有用的内部消息.
我是以正确的方式解决这个问题吗?有没有更好的方法来实现这一目标?
将记录消息与实际输出混合通常不是一个好主意.然后,您的函数的消费者必须进行大量过滤才能找到他们真正想要的对象.
您的函数应将日志消息写入详细输出流.如果调用者想要查看这些消息,可以通过指定-Verbose切换到您的函数.
function SomeLibraryFunction()
{
[CmdletBinding()]
param(
)
Write-Verbose "Some meaningful function logging text"
Write-Output "return value"
}
Run Code Online (Sandbox Code Playgroud)
在PowerShell 3+中,消费者可以将详细消息重定向到输出流或文件:
# 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
Run Code Online (Sandbox Code Playgroud)
其他选择包括:
Start-Transcript创建日志的会话.| 归档时间: |
|
| 查看次数: |
7954 次 |
| 最近记录: |