powershell - 在 PowerShell 中使用 NLog ${callsite} 和 ${callsite-linenumber}

标签 powershell nlog

我正在尝试像在 PowerShell 方法中一样配置 NLog .NET,但没有包含两个日志文件的配置文件。它也很完美。我的问题是 ${callsite} 和 ${callsite-linenumber} 没有在日志文件中正确输出。 示例:

05-06-2020 21:07:01.489 :: (WARN) :: <no type>.CallSite.Target :: 0 :: sdfsdfgsdfghsdfg
05-06-2020 21:07:01.489 :: (WARN) :: <no type>.CallSite.Target :: 0 :: sdfsdfgsdfghsdfg
05-06-2020 21:07:01.489 :: (WARN) :: <no type>.CallSite.Target :: 0 :: sdfsdfgsdfghsdfg

我的 NLog 初始化在方法上类似于 .NET,因为我不想在我的 ps1 之外使用配置。

我的方法:

Function Initialize-Nlog()
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName = $true, Position=0, ParameterSetName = "INIT")][switch]$Initialize,
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName = $true, Position=1, ParameterSetName = "INIT")][ValidateNotNullOrEmpty()][string]$LoggingFileName,
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName = $true, Position=2,ParameterSetName = "GETLOGGER")][switch]$GetLoggerI,
        [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName = $true, Position=3,ParameterSetName = "GETLOGGER")][switch]$GetLoggerF
    )

    process {

        if(!$LoggingFileName.ToLower().Contains(".log"))
        {
            $LoggingFileName += ".log"
        }

        if($Initialize.IsPresent)
        {
            [Void] [System.Reflection.Assembly]::LoadFile("$env:windir\NLog.dll")

            $logLayout_NORMAL = [string]::Format("{0}", '${message}')
            $logLayout_INTERN = [string]::Format("{0} :: {1} :: {2} :: {3} :: {4}", '${date:format=dd\-MM\-yyyy HH\:mm\:ss\.fff}', '(${uppercase:${level}})', '${callsite}', '${callsite-linenumber}',  '${message} ${exception}')


            #region NORMAL to Console
            $tagetC_INFO                  = New-Object NLog.Targets.ConsoleRowHighlightingRule
            $tagetC_INFO.Condition        = [NLog.Conditions.ConditionParser]::ParseExpression("level == LogLevel.Info")
            $tagetC_INFO.ForegroundColor  = [NLog.Targets.ConsoleOutputColor]::White

            $tagetC_DEBUG                 = New-Object NLog.Targets.ConsoleRowHighlightingRule
            $tagetC_DEBUG.Condition       = [NLog.Conditions.ConditionParser]::ParseExpression("level == LogLevel.Debug")
            $tagetC_DEBUG.ForegroundColor = [NLog.Targets.ConsoleOutputColor]::Green

            $tagetC_WARN                  = New-Object NLog.Targets.ConsoleRowHighlightingRule
            $tagetC_WARN.Condition        = [NLog.Conditions.ConditionParser]::ParseExpression("level == LogLevel.Warn")
            $tagetC_WARN.ForegroundColor  = [NLog.Targets.ConsoleOutputColor]::Yellow

            $tagetC_TRACE                 = New-Object NLog.Targets.ConsoleRowHighlightingRule
            $tagetC_TRACE.Condition       = [NLog.Conditions.ConditionParser]::ParseExpression("level == LogLevel.Trace")
            $tagetC_TRACE.ForegroundColor = [NLog.Targets.ConsoleOutputColor]::Gray

            $tagetC_ERROR                 = New-Object NLog.Targets.ConsoleRowHighlightingRule
            $tagetC_ERROR.Condition       = [NLog.Conditions.ConditionParser]::ParseExpression("level == LogLevel.Error")
            $tagetC_ERROR.ForegroundColor = [NLog.Targets.ConsoleOutputColor]::Red

            $targetC                      = New-Object NLog.Targets.ColoredConsoleTarget
            $targetC.Name                 = "console"
            $targetC.Layout               = $logLayout_NORMAL

            $targetC.RowHighlightingRules.Add($tagetC_INFO)
            $targetC.RowHighlightingRules.Add($tagetC_DEBUG)
            $targetC.RowHighlightingRules.Add($tagetC_WARN)
            $targetC.RowHighlightingRules.Add($tagetC_TRACE)
            $targetC.RowHighlightingRules.Add($tagetC_ERROR)
            #endregion

            #region INTERN for Internal Error log
            $targetI                         = New-Object NLog.Targets.FileTarget
            $targetI.Name                    = "intern"
            $targetI.Encoding                = [System.Text.Encoding]::UTF8
            $targetI.FileName                = [System.IO.Path]::Combine($env:LoggingDirectory, "InstallTools_ERROR.log")
            $targetI.ConcurrentWrites        = $true
            $targetI.ArchiveOldFileOnStartup = $false
            $targetI.KeepFileOpen            = $false
            $targetI.CreateDirs              = $true
            $targetI.DeleteOldFileOnStartup  = $false
            $targetI.MaxArchiveFiles         = 0
            $targetI.Layout                  = $logLayout_INTERN
            #endregion

            #region NORMAL to File
            $targetF                         = New-Object NLog.Targets.FileTarget
            $targetF.Name                    = "file"
            $targetF.Encoding                = [System.Text.Encoding]::UTF8
            $targetF.ArchiveOldFileOnStartup = $true
            $targetF.ArchiveNumbering        = [NLog.Targets.ArchiveNumberingMode]::Date
            $targetF.FileName                = [System.IO.Path]::Combine($env:LoggingDirectory, $LoggingFileName)
            $targetF.ArchiveDateFormat       = "yyyy.MM.dd HH.mm.ss"
            $targetF.ArchiveFileName         = [System.IO.Path]::Combine($env:LoggingDirectory, [System.IO.Path]::GetFileNameWithoutExtension($filePath) + '__{#}.log')
            $targetF.ConcurrentWrites        = $true
            $targetF.ArchiveOldFileOnStartup = $true
            $targetF.KeepFileOpen            = $false
            $targetF.MaxArchiveFiles         = -1
            $targetF.CreateDirs              = $true
            $targetF.Layout                  = $logLayout_NORMAL
            #endregion

            #region LoggingRules
            $LoggingRuleF = New-Object NLog.Config.LoggingRule
            $LoggingRuleF.LoggerNamePattern = "logNormal"
            $LoggingRuleF.SetLoggingLevels([NLog.LogLevel]::Trace, [NLog.LogLevel]::Fatal)
            $LoggingRuleF.Targets.Add($targetF)
            $LoggingRuleF.Targets.Add($targetC)

            $LoggingRuleI = New-Object NLog.Config.LoggingRule
            $LoggingRuleI.LoggerNamePattern = "logIntern"
            $LoggingRuleI.SetLoggingLevels([NLog.LogLevel]::Trace, [NLog.LogLevel]::Fatal)
            $LoggingRuleI.Targets.Add($targetI)

            $LoggingConfig = New-Object NLog.Config.LoggingConfiguration
            $LoggingConfig.AddTarget("normal", $targetF)
            $LoggingConfig.LoggingRules.Add($LoggingRuleF)
            $LoggingConfig.AddTarget("intern", $targetI)
            $LoggingConfig.LoggingRules.Add($LoggingRuleI)
            #endregion

            [NLog.LogManager]::Configuration = $LoggingConfig
        }

        if($GetLoggerI.IsPresent)
        {
            return [NLog.LogManager]::GetLogger("logIntern")
        }

        if($GetLoggerF.IsPresent)
        {
            return [NLog.LogManager]::GetLogger("logNormal")
        }
    }
}

调用:

function Test-Me() {

    [string]$env:Publisher      = 'Citrix'
    [string]$env:DisplayName    = 'WebSpinner'
    [string]$env:DisplayVersion = '1.3.4.675'


    $env:LoggingDirectory = "C:\Logs"
    $env:LogFileName = $($env:Publisher + " " + $env:DisplayName + " " + $env:DisplayVersion)

    Initialize-Nlog -Initialize -LoggingFileName $env:LogFileName
    $log = Initialize-Nlog -GetLoggerF
    $logError = Initialize-Nlog -GetLoggerI

    $log.Info("sdfsdfsdf")
    $log.Info("sdfsdfsdf")
    $log.Info("sdfsdfsdf")
    $log.Info("sdfsdfsdf")
    $log.Info("sdfsdfsdf")

    $logError.warn("sdfsdfgsdfghsdfg")
    $logError.warn("sdfsdfgsdfghsdfg")
    $logError.warn("sdfsdfgsdfghsdfg")
    $logError.warn("sdfsdfgsdfghsdfg")
    $logError.warn("sdfsdfgsdfghsdfg")
    $logError.warn("sdfsdfgsdfghsdfg")
}

Test-Me

如何在 PowerShell 中使用它?

最佳答案

感谢@所有人的帮助!

我放弃了 PowerShell 中的 callsite 和 callsite-linennumber,因为我切换回了 C# 二进制 cmdlet。

关于powershell - 在 PowerShell 中使用 NLog ${callsite} 和 ${callsite-linenumber},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62223012/

相关文章:

email - powershell send-mailmessage错误-helo命令被拒绝:需要标准主机名

powershell - powershell 中 pushd、popd 和 robocopy 命令的确切用途是什么?

dependency-injection - 将 NLog 提供程序添加到 ILoggerFactory

javascript - 无法实现 JSNLog 到 ASP.NET MVC 解决方案

powershell - 如何在不耗尽内存的情况下删除 Powershell 中的重复项?

c# - Powershell不调用C#对象中的方法

azure - 需要在SharePoint Api组中找到Sites.FullControl.All的id

c# - 在配置中设置 NLog RichTextBox 目标

asp.net-mvc - Azure 网站中的 ASP.NET MVC4 + Ninject + NLog = 问题

c# - 应该只记录错误消息吗?