Open mabster opened 4 years ago
I guess I can do:
(Get-LoggingTarget).Clear()
... but that's relying on the internal implementation of Get-LoggingTarget (if you were to change it to return something without a .Clear() method, my code would break) and doesn't feel very "PowerShelly".
The module objects are globally scoped, maybe we can provide a function to clear the targets. You could try removing the module, it should cleanup all the vars used.
Yeah I kinda like the idea of being able to add logging targets inside a script, but then also add my own from the host PowerShell instance before calling the script. Like:
> Add-LoggingTarget -Name Console
> .\Foo.ps1 # which has a File target defined inside it
... but when the script finishes, I don't want the File target still active.
What if Add-LoggingTarget were to return the added target instance, and then we had a Remove-LoggingTarget so that scripts could clean up after themselves?
$file = Add-LoggingTarget -Name File # etc
try {
# do stuff that writes to the log
}
finally {
Remove-LoggingTarget $file
}
Just spitballing!
Hmm ... I guess that would need some pretty heavy refactoring since it looks like you can only have one target for each "name". So if I'd added a Console target outside of the script and then added it again inside the script, there's still only one target defined. Is that right?
I think it is possible for Add-LoggingTarget
and Remove-LoggingTarget
to figure our the scope the are being called from e.g. directly from console, from Foo.ps1 and etc. Remove could then only remove targets added in this scope. Two question come to mind - handling nested scopes and duplicate targets (think Add-LoggingTarget -Name Console
is called from console and .\Foo.ps1
)
Yeah and it's entirely possible that I would have added the console target from the host before calling the script.
Perhaps each target keeps track of the outermost scope that it was added from, and Remove-LoggingTarget only removes targets that were added from this scope or lower?
If I'm doing some testing with a script, and at the top of the script I have something like this:
... then when I run the script, the logging targets persist even after the script ends. If I subsequently call Write-Log, the output goes to the console and to the configured file.
This might be a feature request but maybe I'm just missing something obvious. Is there a way to scope the logging targets to just the script? Or is there a way to reset them, thereby clearing the list of active targets?
Thanks, Matt