Powershell 在日志中获取函数名的Dry方法
我在每个函数中使用Powershell 在日志中获取函数名的Dry方法,powershell,Powershell,我在每个函数中使用$functionName=$MyInvocation.MyCommand捕获函数名,以便进行日志记录,然后允许我的Write Log函数获取此值 日志功能: Function Write-Log { [CmdletBinding()] Param( [Parameter(Mandatory=$False)] [ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")] [String]
$functionName=$MyInvocation.MyCommand
捕获函数名,以便进行日志记录,然后允许我的Write Log函数获取此值
日志功能:
Function Write-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$False)]
[ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
[String]
$Level = "INFO",
[Parameter(Mandatory=$True)]
[string]
$Message,
[Parameter(Mandatory=$False)]
[string]
$logfile
)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$Line = "$Stamp $Level $Message Function: $functionName User: $tech"
If($logfile) {
Add-Content $logfile -Value $Line
}
Else {
Write-Output $Line
}
}
目前,我正在检查每个紧急函数,并添加$functionName=$MyInvocation.MyCommand
以将其保持在适当的范围内,这确实有效,但对我来说似乎非常脏。在保持适当范围的同时,是否有更干燥的方法
将$functionName
放入单个函数时的日志输出示例:
2018/09/03 13:11:36 INFO Store ID object received: https://******/webacs/api/v1/data/Sites/5290873 Function: Management-AfterAll User: admin-dksc104694
2018/09/03 13:11:36 INFO Stores found: 1 Function: Management-AfterAll User: admin-dksc104694
2018/09/03 13:11:36 INFO Get-AllAp started for Store 0925 Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:37 INFO Making Get request to https://cpist/webacs/api/v3/data/AccessPointDetails.json?.group=0925 Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:37 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:37 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:38 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:38 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:38 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:38 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:39 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:39 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:39 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:40 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:40 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
您可以通过查看callstack推断调用命令的名称:
function Write-Log {
[CmdletBinding()]
Param(
# ...
)
$FunctionName = (Get-PSCallStack |Select-Object -Skip 1 -First 1).Command
# ...
}
调用堆栈上的第一项始终是
写入日志
函数本身,因此-Skip 1
做得很好;比(Get PSCallStack | Select Object-Skip 1-First 1)更短的替代方法。命令是(Get PSCallStack)[1]。命令(后者首先收集内存中的所有Get PSCallStack
输出对象)。