【问题标题】:Monitor the latest log with PowerShell使用 PowerShell 监控最新日志
【发布时间】:2021-08-19 08:51:39
【问题描述】:

我正在尝试监控应用程序的日志并在发生错误时发送警报。这很简单。

$file = Get-ChildItem "X:\Log\" | Where-Object {$_.Name -match "log"} | Select-Object -Last 1    
Get-Content $file.FullName -Tail 0 -Wait | `
ForEach-Object {
    if($_ -match "ERROR") {
     Send-Alert -Subject "ERROR in $file on $env:COMPUTERNAME" -Body $_
    }    
}

不那么简单的是,应用程序创建了一个名为 log-DD-MM.log 的文件,这意味着如果服务崩溃并且应用程序启动一个新的日志文件,PowerShell 仍将尝试跟踪旧的 $file,即仍然存在,但没有写入数据。

有什么方法可以处理这个并且总是检查最后一个文件吗?我想了一会儿,但在重新检查时可能会错过一些信息。

【问题讨论】:

    标签: powershell logging error-handling


    【解决方案1】:

    使用 try/catch 并将 -Stop 参数添加到 Get-Content cmdlet,如下所示:

    try {
    Get-Content $file.FullName -Wait -ErrorAction Stop
    }
    
    catch {
    "File Deleted Do something else..." ## Find the new name and read it again with Get-Content...
    }
    

    【讨论】:

      【解决方案2】:

      只需选择最新的 .log 文件使用

      $file = Get-ChildItem -Path "X:\Log" -Filter '*.log'| Sort-Object LastWriteTime | Select-Object -Last 1
      

      使用 -Filter '*.log' 比之后使用 Where-Object 子句要快得多。

      【讨论】:

        【解决方案3】:

        最终代码:

        $MonitorLog = { 
            Param($Path)
            function Send-Alert {
            Removed-Code
        }
            Get-Content $Path -Tail 0 -Wait | ForEach-Object {
                if($_ -match "ERROR") {
                    Send-Alert -Subject "ERROR in $Path on $env:COMPUTERNAME" -Body $_
                }
            }
        }
        while($true) {
            $file = Get-ChildItem "X:\Log\" | Where-Object {$_.Name -match "log"} | Select-Object -Last 1
           if ($currentFile.fullname -ne $file.fullname) {
               if ($job) { $job | Stop-Job -PassThru | Remove-Job }
               $job = Start-Job $MonitorLog -ArgumentList $File.FullName
               $currentFile = $file
           }
        
           Start-Sleep ([timespan]'00:00:30.00').TotalSeconds
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多