LoginSignup
0
0

NewRelicでのログ監視(stream使用)

Posted at

概要

newrelicでログ監視を設定したときに確認したことをメモ書きする。

logファイルはつかんでおく必要がある

5分間隔でpingを行い結果をファイルに出力し、エラーが出た場合にアラートを上げたいという状況の場合

 $logfile = "C:\Users\mou34\logs\test.log"

while ($true) {
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $result = Test-NetConnection -ComputerName "localhost" -Port 80

    if ($result.TcpTestSucceeded) {
        $status = "ok"
    } else {
        $status = "error"
    }

    $logEntry = "$timestamp - Connection test result: $status"
    Add-Content -Path $logfile -Value $logEntry

    # Sleep for 5 minutes (300 seconds)
    Start-Sleep -Seconds 300
}

newrelicのエージェントにより以下のエラーとなってしまう。

Add-Content : 別のプロセスで使用されているため、プロセスはファイル 'C:\Users\mou34\logs\test.log' にアクセスできません
。

そのため下記のようにstreamを使用する。

 $logfile = "C:\Users\mou34\logs\test.log"

while ($true) {
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $result = Test-NetConnection -ComputerName "localhost" -Port 80

    if ($result.TcpTestSucceeded) {
        $status = "ok"
    } else {
        $status = "error"
    }

    $stream = [System.IO.StreamWriter]::new($logfile, $true)

    $stream.WriteLine("[$timestamp] - Connection test result: $status")

    $stream.Close()

    # Sleep for 5 minutes (300 seconds)
    Start-Sleep -Seconds 300
}
 

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0