首页 > 解决方案 > Dry method for getting function name in logs

问题描述

I am capturing the name of a function for the purpose of logging using $functionName = $MyInvocation.MyCommand in every function, then allowing my Write-Log function to get this value.

Log Function:

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
    }
}

Currently I'm just going through each urgent function and adding $functionName = $MyInvocation.MyCommand to keep it in the proper scope, and this does work, but it seems very dirty to me. Is there a more dry method while maintaining proper scope?

Example of log output when putting $functionName in individual function:

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

解决方案


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

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

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

调用堆栈上的第一项将始终是Write-Log函数本身,因此-Skip 1


推荐阅读