Badgerati / Pode

Pode is a Cross-Platform PowerShell web framework for creating REST APIs, Web Sites, and TCP/SMTP servers
https://badgerati.github.io/Pode
MIT License
865 stars 92 forks source link

File logging cleanup does not work #1433

Closed DoLearnWhileAlive closed 4 weeks ago

DoLearnWhileAlive commented 1 month ago

Describe the Bug

Pode's inbuilt file logging logic does not cleanup the old log files, but creates below exception/error:

Date: 2024-10-24 03:07:46
Level: Error
ThreadId: 0
Server: iantstm9t1ctx01
Category: InvalidData: (:) [Invoke-PodeScriptBlock], ParameterBindingValidationException
Message: Cannot bind argument to parameter 'Path' because it is null.
StackTrace: at <ScriptBlock>, C:\Program Files\WindowsPowerShell\Modules\Pode\2.11.0\Private\Logging.ps1: line 69
at Invoke-PodeScriptBlock, C:\Program Files\WindowsPowerShell\Modules\Pode\2.11.0\Public\Utilities.ps1: line 581
at <ScriptBlock>, <No file>: line 59

Steps To Reproduce

Steps to reproduce the behavior:

# Create old log files
New-Item -Path .\logs -ItemType Directory -Force | Out-Null
(New-Item -Path .\logs\Log_2024-09-24_001.log -ItemType File -Force).CreationTime = '2024-09-24' | Get-Date
(New-Item -Path .\logs\Log_2024-09-25_001.log -ItemType File -Force).CreationTime = '2024-09-25' | Get-Date
(New-Item -Path .\logs\Log_2024-09-26_001.log -ItemType File -Force).CreationTime = '2024-09-26' | Get-Date
(New-Item -Path .\logs\Log_2024-09-27_001.log -ItemType File -Force).CreationTime = '2024-09-27' | Get-Date
(New-Item -Path .\logs\Log_2024-09-28_001.log -ItemType File -Force).CreationTime = '2024-09-28' | Get-Date

Import-Module -Name Pode

Start-PodeServer {

    New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging
    New-PodeLoggingMethod -File -Name 'Log' -MaxDays 4 | Add-PodeLogger -Name 'Log' -ScriptBlock {
        param($message)
        return ("{0}`t{1}" -f (Get-Date -format o), $message)
    }

    Add-PodeTimer -Name 'LogTimer' -Interval 2 -ScriptBlock {
        "NextClearDown: $($PodeContext.Server.Logging.Types.Log.Method.Arguments.NextClearDown)" | Write-PodeLog -Name 'Log'

        # Force cleanup cycle by setting NextClearDown
        $PodeContext.Server.Logging.Types.Log.Method.Arguments.NextClearDown = [DateTime]::Now.Date.AddDays(-1)
    }
}

Expected Behavior

Pode should cleanup file accoring -MaxDays parameter without throwing an exception.

Proposed Fix

Issue can be fixed by removing $_ from the Remove-Item command in Get-PodeLoggingFileMethod:

            $null = Get-ChildItem -Path $options.Path -Filter '*.log' -Force |
                Where-Object { $_.CreationTime -lt $date } |
                Remove-Item $_ -Force

I'll prepare a pull request.

Platform