torek, 26. januar 2016

Powershell seach for error in application Logs

In the performance testing is good to have fast and readable results.  One of the most important results are application log. Application logs are creating when application is executing an creates a log. Logs are saved in specific location defined by log4net  in my case or in other tools for logging. In system under test can be used more than one application server, searching for errors is time consuming job.

First is good to define path where are located log files. Mostly this powershell script is executed on each application servers because it can do in parallel. And results are from each application server to global folder location of the tests results.

Write a script

First we need to define on which server is executing script.  To get a computer name:
    $ComputerName = host
# serach for errors in log and save them into one file


now we open a file where all errors will be saved in file:

    $stream = [System.IO.StreamWriter] "$TCLogPath\$($ComputerName)_AllErrors.txt"


to search recursively in local computers log folder for specific string, in our case is '] ERROR'. When file is opened
          $file = New-Object System.IO.StreamReader -Arg $_.FullName

 
then powershell scripts check for string '] ERROR' and save line into $stream defined upper.
           while ($line = $file.ReadLine()) {
                if ($line.Contains("] ERROR"))
                {
                    #$line
                    $stream.WriteLine($line)
                }



when file was searched completely the file must be closed:

        $file.close()

After all files are checked  then $stream must be also close:
   $stream.close()

 
Below is a completely script  just define you log file folder and execute a script:
    $ComputerName = host
    # sreach for errors in log and save them into one file
    $stream = [System.IO.StreamWriter] "$TCLogPath\$($ComputerName)_AllErrors.txt"
    $TCLogPath ="c:"
    Get-ChildItem "$TCLogPath\logs" -recurse | `
    Foreach-Object{
      if( (Get-Item $_.FullName) -isnot [System.IO.DirectoryInfo])
       {
         $stream.WriteLine($_.FullName)
          $file = New-Object System.IO.StreamReader -Arg $_.FullName
           while ($line = $file.ReadLine()) {
                if ($line.Contains("] ERROR"))
                {
                    #$line
                    $stream.WriteLine($line)
                }

           }
           $file.close()
     }
    }
    $stream.close()



If you thinks this blog improve you work please add a comment. Thank you.

Ni komentarjev:

Objava komentarja