Pieter Coene
Pieter Coene

Reputation: 11

Using log4net in Powershell: setting a property works, but is not used

I have an PowerShell module that initializes a log4net with a default config file so I can use this in my PS Scripts. This works fine. My module has a parameter so i can specify to with file the RollingFileAppender should write. My module updates this value (when debugging, I can see that the File-property is changed). But when returning the 'logger' object, it still logs to the file that configured in my default config file.

This used to work some time ago, but now it does not any more. Basically, this is the code of the module (I removed all the try-catch code for clarity).

This is my module 'log4net.psm1'

function InitLog4Net {
    param(
        [string]$Logfile,
        [string]$FileThreshold
    )

    $ErrorActionPreference = "Stop"

    [void][Reflection.Assembly]::LoadFile("$PSScriptRoot\log4net.dll");
    $fileInfo = New-Object System.IO.FileInfo("$PSScriptRoot\log4net.config")
    [log4net.Config.XmlConfigurator]::Configure($fileInfo)

    $log = [log4net.LogManager]::GetLogger("Logger")

    if ($PSBoundParameters.ContainsKey("Logfile")) {
        foreach ($appender in $log.Logger.Appenders) {
            if ($appender.Name -eq "file") {
                $appender.File = $Logfile
                $appender.ActivateOptions()                         
            }
        }
    }

    # I can see the $appender.File is updated here

    return $log
}

I simply call from a PS Script this module that return the 'log4net' object and I start logging. The log is written to the file that is defined in my default log4net.config.

Import-Module c:\<path-to-module>\log4net.psm1 -Force

$file = $PSScriptRoot + "\Do-Monitor.log"
$log = InitLog4Net -Logfile $file

$log.Info("Started!")

What am i doing wrong here? Am i returning the original object without my modification?

Greetz Pieter

I'm using Powershell 7.4.6 on a Windows Server 2019, log4net.dll is version 2.0.15.0

UPDATE: just rebooted the server and it worked perfectly. We run several Powershell scripts on a daily basis on this server. After the reboot, my script was the first to run. I started another PowerShell script that is using the same module I created and then it was broke again. So it goes wrong when running multiple powershell scripts that are using my module.

Upvotes: 1

Views: 57

Answers (0)

Related Questions