在日志中获取函数名称的干燥方法

问题描述 投票:1回答:1

我正在捕获函数的名称,以便在每个函数中使用$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
powershell
1个回答
2
投票

您可以通过查看callstack来推断调用命令的名称:

function Write-Log {
    [CmdletBinding()]
    Param(
        # ...
    )

    $FunctionName = (Get-PSCallStack |Select-Object -Skip 1 -First 1).Command
    # ...
}

callstack上的第一个项目将始终是Write-Log函数本身,因此-Skip 1

© www.soinside.com 2019 - 2024. All rights reserved.