RootITUp / Logging

Powershell Logging Module
https://www.powershellgallery.com/packages/Logging
222 stars 49 forks source link

File Target with Relative Path #91

Closed mabster closed 3 years ago

mabster commented 4 years ago

This sort of thing has been working for me without any issue until I scheduled the script to run on a server, where it failed:

Set-Location $PSScriptRoot

Add-LoggingTarget -Name File -Configuration @{
    Level = 'INFO'
    Path  = '..\Logs\' + (Get-Date -format yyyyMMdd) + '-' + ($MyInvocation.MyCommand.Name -replace '.ps1$', '.log')
}
# ... rest of script

When I ran the script on a different machine, it complained that it couldn't get to a path under my user profile folder (C:\Users\mabster\Logs) rather than a path relative to where the script lives.

Of course I was able to fix it by using "$PSScriptRoot..\Logs" in the Path property so it resolves to an absolute path, but is this a known issue? Does the RunSpace that the log processing happens in not inherit the location of the script?

EsOsO commented 4 years ago

You're right, I had the same issue, resorted to full path. I think could be more a problem with the Resolve-Token function.

HINT: the module support a sort of string inerpolation, you could write the log name like this: C:\Temp\example_%{+%Y%m%d}.log. See here

mabster commented 4 years ago

Oh that's cool - I didn't realise the token replacement also worked in the target filename. That's a handy tip!

Tadas commented 4 years ago

Log processing runspace starts up when the module is being imported. It's entirely possible you might cd to some other location before calling Add-LoggingTarget -Name File so relying on working folder when the runspace starts up IMHO isn't great.

It feels like relative paths should be relative to the working folder when Add-LoggingTarget is being called, but others might feel differently. In any case, current Add-LoggingTarget implementation doesn't know anything about the Configuration hashtable. It would have to be made smarter to know that certain properties are paths and that relative paths need to be resolved. That doesn't look straightforward.

Tadas commented 4 years ago

On second thought, file logging target Init block could be used to resolve relative paths

https://github.com/EsOsO/Logging/blob/aa99080271cf700a26273cb89f3b22a7a93d906f/Logging/public/Add-LoggingTarget.ps1#L38

Unless there are any better ideas I'll give that a go