【问题标题】:Trying to get log4net working with PowerShell (with a log4net config file in the mix)试图让 log4net 与 PowerShell 一起工作(混合使用 log4net 配置文件)
【发布时间】:2023-03-19 01:27:02
【问题描述】:

我一直在努力让 log4net 与 PowerShell 一起工作。我有以下 PowerShell 代码,它使用配置文件引入 log4net,然后尝试创建一个简单的日志文件条目,但出现错误。

Clear-History
Clear-Host
#
Write-Host "BEGIN: Importing module psm_logger.psm1"
Import-Module "C:\Users\Administrator\Desktop\ps\IIS\psm_logger.psm1" -Force
Write-Host "BEGIN: log4net configuration definition"
$log = New-Logger -Configuration "C:\Users\Administrator\Desktop\ps\IIS\logging\log4net.config" -Dll "C:\Users\Administrator\Desktop\ps\IIS\logging\log4net.dll"
Write-Host "END: log4net configuration definition"
Write-Host "BEGIN: log4net configuration DEBUG definition"
#$log.DebugFormat("Logger configuration file is : '{0}'", (Resolve-Path "C:\Users\Administrator\Desktop\ps\IIS\logging\log4net.config"))
Write-Host "END: log4net DEBUG configuration definition"
#======================
$ThisHostname = $env:COMPUTERNAME
#======================
Write-Host "BEGIN: Module/Snapin import/addition"
Write-Host ""
$log.Info("BEGIN: Module/Snapin import/addition")
#======================

上面引用的psm_logger.psm1文件包含:

function New-Logger
{
#Write-Host "BEGIN: New-Logger"
<#
.SYNOPSIS
      This function creates a log4net logger instance already configured
.OUTPUTS
      The log4net logger instance ready to be used
#>
     [CmdletBinding()]
     Param
     (
          [string]
          # Path of the configuration file of log4net
          $Configuration,
          [Alias("Dll")]
          [string]
          # Log4net dll path
          $log4netDllPath
     )
     Write-Verbose "[New-Logger] Logger initialization"
     $log4netDllPath = Resolve-Path $log4netDllPath -ErrorAction SilentlyContinue -ErrorVariable Err
     if ($Err)
     {
          throw "Log4net library cannot be found on the path $log4netDllPath"
     }
     else
     {
          Write-Verbose "[New-Logger] Log4net dll path is : '$log4netDllPath'"
          [void][Reflection.Assembly]::LoadFrom($log4netDllPath) | Out-Null
          # Log4net configuration loading
          $log4netConfigFilePath = Resolve-Path $Configuration -ErrorAction SilentlyContinue -ErrorVariable Err
          if ($Err)
          {
               throw "Log4Net configuration file $Configuration cannot be found"
          }
          else
          {
               Write-Verbose "[New-Logger] Log4net configuration file is '$log4netConfigFilePath' "
               $FileInfo = New-Object System.IO.FileInfo($log4netConfigFilePath)
               [log4net.Config.XmlConfigurator]::Configure($FileInfo)
               $script:MyCommonLogger = [log4net.LogManager]::GetLogger("root")
               Write-Verbose "[New-Logger] Logger is configured"
               return $MyCommonLogger
          }
     }
}

log4net 的配置文件如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" **requirePermission="false"**/>
    </configSections>
    <log4net>
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <param name="File" value="C:\Users\Administrator\Desktop\ps\IIS\LOGS\LogTest2.txt" />
            <param name="AppendToFile" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="Header" value="[Header]\r\n" />
                <param name="Footer" value="[Footer]\r\n" />
                <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
            </layout>
        </appender>
        <root>
            <level value="ALL" />
            <appender-ref ref="LogFileAppender" />
        </root>
    </log4net>
</configuration>

运行时产生的输出和错误是:

开始:导入模块 psm_logger.psm1 BEGIN:log4net 配置定义 END:log4net 配置定义 BEGIN:log4net配置DEBUG定义 END:log4net DEBUG 配置定义 BEGIN:模块/管理单元导入/添加

方法调用失败,因为 [System.Object[]] 不包含名为“Info”的方法。 在 C:\Users\Administrator\Desktop\ps\IIS\IIS_localLogs.ps1:18 char:10 + $log.Info

任何帮助将不胜感激!

(仅供参考:我最初是从最佳实践博客条目中获得此代码的:http://blog.octo.com/en/powershell-v2-my-best-practices/,我觉得这很有帮助)

【问题讨论】:

  • PowerGui 将变量 $log 显示为具有以下错误:{log4net:ERROR XmlConfigurator: Error while loading XML configuration, log4net.Core.LogImpl}

标签: powershell log4net log4net-configuration log4net-appender


【解决方案1】:

找到解决方案...

配置文件因顶部出现一些星号而损坏。删除那些解决了这个问题。感谢任何可能已经开始关注此问题的人,我希望这对将来的其他人有所帮助。

配置文件现在看起来像:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/>
    </configSections>
    <log4net>
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <param name="File" value="C:\Users\Administrator\Desktop\ps\IIS\LOGS\LogTest2.txt" />
            <param name="AppendToFile" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="Header" value="[Header]\r\n" />
                <param name="Footer" value="[Footer]\r\n" />
                <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
            </layout>
        </appender>
        <root>
            <level value="ALL" />
            <appender-ref ref="LogFileAppender" />
        </root>
    </log4net>
</configuration>

【讨论】:

    【解决方案2】:

    New-Logger 是一个非常有用的 cmdlet,值得为更新版本的 Powershell 进行更新。 psm_logger.psm1 当前在 PS V3 及更高版本下会出现 System.Void 错误。将装配负载更改为

    [Reflection.Assembly]::LoadFrom($log4netDllPath) | Out-Null
    

    没有 [Void] 可以解决问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 2010-11-22
      • 2010-10-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      相关资源
      最近更新 更多