试图让log4net与PowerShell一起使用(混合使用log4net配置文件)

时间:2012-11-21 15:21:04

标签: powershell log4net log4net-configuration log4net-appender

我一直在努力让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>

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

BEGIN:导入模块psm_logger.psm1 BEGIN:log4net配置定义 END:log4net配置定义 BEGIN:log4net配置DEBUG定义 END:log4net DEBUG配置定义 BEGIN:模块/ Snapin导入/添加

方法调用失败,因为[System.Object []]不包含名为“Info”的方法。 在C:\ Users \ Administrator \ Desktop \ ps \ IIS \ IIS_localLogs.ps1:18 char:10 + $ log.Info&lt;&lt;&lt;&lt; (“开始:模块/ Snapin导入/添加”)     + CategoryInfo:InvalidOperation:(Info:String)[],RuntimeException     + FullyQualifiedErrorId:MethodNotFound

非常感谢任何帮助!

(仅供参考:我最初从最佳实践博客条目获得此代码:http://blog.octo.com/en/powershell-v2-my-best-practices/我觉得非常有用)

2 个答案:

答案 0 :(得分:2)

找到解决方案......

配置文件因顶部存在一些星号而损坏。删除那些修复了问题。感谢任何可能已经开始关注这个问题的人,我希望将来可以帮助其他人。

配置文件现在看起来像:

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

答案 1 :(得分:2)

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

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

没有[Void]来解决问题。