Jump to content

Check String Exist in Txt File Every 5min


levila
 Share

Recommended Posts

Hi guys, really need your help. How can i check every 5 min if my text file include String "Markus". Btw i need this function to run on my Logs file that are updated whenever some event is triggered (logs appear in same txt file). So i did test some codding to test isit possible.

But somehow, it only detect for the 1st time String check, and keep coming the same output every time, it didnt check/read on the current txt file that has been updated.

For this purpose i update txt file manually so i put String "Markus" and check, and try to remove it agn.

Here is my code:

 

$file = FileOpen("c:\hello.txt", 0)
$read = FileRead($file)

func _CheckString()
   If StringInStr($read, "Markus") Then
      $position = StringInStr($read, "Markus")
      MsgBox(0,"","Alert Found - Logs Line No "&$position, 5)
      FileClose($file)
   Else
      MsgBox(0,"","No Alert found", 5)
      FileClose($file)
   EndIf
EndFunc

$Mins = 0.5 ; i change to fewer min for testing purpose
$Timer = TimerInit()

While 1
    If TimerDiff($Timer) > ($Mins * 60000) Then ; count per minute multiplied by 60sec.
       _CheckString()
       ConsoleWrite("30 Sec have passed!" & @CRLF) ; console to see if its running.
       $Timer = TimerInit()
    EndIf
 WEnd

 

Edited by levila
add more information
Link to comment
Share on other sites

29 minutes ago, levila said:

But somehow, it only detect for the 1st time String check, and keep coming the same output every time

close the file in the function

FileClose($file)

but not attempt to open and read again when time is up the second time around. should place these in the func

$file = FileOpen("c:\hello.txt", 0)
$read = FileRead($file)

 

Edited by zeenmakr
Link to comment
Share on other sites

I would also change the part that you use to execute the function every 5 minutes:

$Mins = 0.5 ; i change to fewer min for testing purpose
$Timer = TimerInit()

While 1
    If TimerDiff($Timer) > ($Mins * 60000) Then ; count per minute multiplied by 60sec.
       _CheckString()
       ConsoleWrite("30 Sec have passed!" & @CRLF) ; console to see if its running.
       $Timer = TimerInit()
    EndIf
 WEnd

to

AdlibRegister("_CheckString", 30000)

And if you do need any kind of console or log output, put it into the checkstring funtion:

func _CheckString()
    Consolewrite("Entering at the function at " & @HOUR & ":" & @MIN & @CRLF)
    
   If StringInStr($read, "Markus") Then
      $position = StringInStr($read, "Markus")
      MsgBox(0,"","Alert Found - Logs Line No "&$position, 5)
      FileClose($file)
   Else
      MsgBox(0,"","No Alert found", 5)
      FileClose($file)
   EndIf
EndFunc

 

Link to comment
Share on other sites

You might use in StringInStr the 'occurence' parameter and increment it
Something like this (untested)

func _CheckString()
    Local Static $occ = 1
    Consolewrite("Entering at the function at " & @HOUR & ":" & @MIN & @CRLF)
    
   If StringInStr($read, "Markus", 0, $occ) Then
      $position = StringInStr($read, "Markus", 0, $occ)
      $occ += 1
      MsgBox(0,"","Alert Found - Logs Line No "&$position, 5)
      FileClose($file)
   Else
      MsgBox(0,"","No Alert found", 5)
      FileClose($file)
   EndIf
EndFunc

This could also be done using the 'start' parameter

Link to comment
Share on other sites

47 minutes ago, levila said:

Let say logs appear "Markus" in line no 5, and next new event triggered and new "markus" string on different line.

not tested, if you meant checking log only for the latest line appended for 'markus', i would start looking from the bottom of the file up

tip for naming variable practice: $iLineCount - the 'i' is for interger; $sFileName - 's'=string, $hFileOpen - h=handle, a=array, c=control ect...

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <File.au3>

Global Const $sFileName_Log = @ScriptDir & '\log.txt'

;~ _CheckLog("Markus")

Func _CheckLogFile($sSearchTerm)
    If Not FileExists($sFileName_Log) Then
        ConsoleWrite('!>!'&@ScriptLineNumber&': File not found ['&$sFileName_Log&']'&@CRLF) ;Red/Brown
    Else
        Local $iLineCount = _FileCountLines($sFileName_Log)
        If Not $iLineCount Then
            ConsoleWrite('!>!'&@ScriptLineNumber&': File is empty ['&$iLineCount&']'&@CRLF) ;Red/Brown
        Else
            Local $hFileOpen = FileOpen($sFileName_Log, $FO_READ)
            If $hFileOpen = -1 Then
                MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.")
                Return False
            EndIf

            ;read file from bottom up - assuming log file appending new line at the end of the file
            For $i = $iLineCount To 1 Step -1
                Local $sFileRead = FileReadLine($hFileOpen, $i)
                Local $iPosition  = StringInStr($sFileRead, $sSearchTerm)
                
                Local $sStr = @ScriptLineNumber&': line-'& $i &' | position-'& $iPosition &' | found-'& $sSearchTerm
                ConsoleWrite($iPosition > 0 ? '   '& $sStr &' &@CRLF : '!>!'& $sStr &' ' &@CRLF) ;White/Red
                
                ;If Not $iPosition Then
                    ;MsgBox(0,"Fails", "No ["& $sSearchTerm &"] Found", 5) ;<---warning endless MsgBox() popup
                ;Else
                    ;MsgBox(0,"Found", "["& $sSearchTerm &"] is located @"& $iPosition, 5) ;<---warning endless MsgBox() popup
                ;EndIf
            Next
            
            FileClose($hFileOpen)
        EndIf
    EndIf
EndFunc

 

Edited by zeenmakr
Link to comment
Share on other sites

On 9/26/2020 at 4:42 PM, zeenmakr said:

not tested, if you meant checking log only for the latest line appended for 'markus', i would start looking from the bottom of the file up

tip for naming variable practice: $iLineCount - the 'i' is for interger; $sFileName - 's'=string, $hFileOpen - h=handle, a=array, c=control ect...

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <File.au3>

Global Const $sFileName_Log = @ScriptDir & '\log.txt'

;~ _CheckLog("Markus")

Func _CheckLogFile($sSearchTerm)
    If Not FileExists($sFileName_Log) Then
        ConsoleWrite('!>!'&@ScriptLineNumber&': File not found ['&$sFileName_Log&']'&@CRLF) ;Red/Brown
    Else
        Local $iLineCount = _FileCountLines($sFileName_Log)
        If Not $iLineCount Then
            ConsoleWrite('!>!'&@ScriptLineNumber&': File is empty ['&$iLineCount&']'&@CRLF) ;Red/Brown
        Else
            Local $hFileOpen = FileOpen($sFileName_Log, $FO_READ)
            If $hFileOpen = -1 Then
                MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.")
                Return False
            EndIf

            ;read file from bottom up - assuming log file appending new line at the end of the file
            For $i = $iLineCount To 1 Step -1
                Local $sFileRead = FileReadLine($hFileOpen, $i)
                Local $iPosition  = StringInStr($sFileRead, $sSearchTerm)
                
                Local $sStr = @ScriptLineNumber&': line-'& $i &' | position-'& $iPosition &' | found-'& $sSearchTerm
                ConsoleWrite($iPosition > 0 ? '   '& $sStr &' &@CRLF : '!>!'& $sStr &' ' &@CRLF) ;White/Red
                
                ;If Not $iPosition Then
                    ;MsgBox(0,"Fails", "No ["& $sSearchTerm &"] Found", 5) ;<---warning endless MsgBox() popup
                ;Else
                    ;MsgBox(0,"Found", "["& $sSearchTerm &"] is located @"& $iPosition, 5) ;<---warning endless MsgBox() popup
                ;EndIf
            Next
            
            FileClose($hFileOpen)
        EndIf
    EndIf
EndFunc

 

For this method it will only execute for the latest line appended for String "markus", and keep looping the Alert/Msgbox until he find new line that have same String.

I want it to detect the 1st string and will go for another string if exist and ignore the 1st string.

And the logs are updated in every 5 min, and sometimes in 5 min there is 2 Logs appear with the same string that i want to be alert.

 

Link to comment
Share on other sites

On 9/26/2020 at 4:28 PM, mikell said:

You might use in StringInStr the 'occurence' parameter and increment it
Something like this (untested)

func _CheckString()
    Local Static $occ = 1
    Consolewrite("Entering at the function at " & @HOUR & ":" & @MIN & @CRLF)
    
   If StringInStr($read, "Markus", 0, $occ) Then
      $position = StringInStr($read, "Markus", 0, $occ)
      $occ += 1
      MsgBox(0,"","Alert Found - Logs Line No "&$position, 5)
      FileClose($file)
   Else
      MsgBox(0,"","No Alert found", 5)
      FileClose($file)
   EndIf
EndFunc

This could also be done using the 'start' parameter

Thx for this, i did test this script, but it keep looping after all string check. so i did some changes and it work like charm.

func _CheckString()
   $file = FileOpen("c:\hello.log", 0)
   $read = FileRead($file)
   Local Static $occ = 1
   $position = StringInStr($read, "logged in", 0, $occ)

   If $position > 0 Then
      $occ += 1
      MsgBox(0,"","Alert Found - Logs Line No "&$position)
   Else
      MsgBox(0,"","No Alert found")
   EndIf
   FileClose($file)
EndFunc

It will detect the String and will ignore it until new string appear in new line.

Wink2 😍, thx all for the help. but if u think there is still error in my script would love if u correct me.

Link to comment
Share on other sites

4 hours ago, levila said:

And the logs are updated in every 5 min, and sometimes in 5 min there is 2 Logs appear with the same string that i want to be alert.

this update only check for changes made to log file recently -within the last 5mins- and report all instances found. 

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <File.au3>
#include <Array.au3>

Global Const $_FILEPATH_LOG = @ScriptDir & '\_CheckLogFile.txt'
Global Const $_FILEPATH_INI = @ScriptDir & '\_CheckLogFile.ini'
Global $_LAST_LOG_LINE_POSITION = IniRead($_FILEPATH_INI,"Options","Last checked position", 0)

;for testing purposes
FileWrite($_FILEPATH_LOG, 'Markus is late again'&@CRLF&'Today is a fine day'&@CRLF&'And where is Markus'&@CRLF)

_CheckLogFile("Markus")

Func _CheckLogFile($sSearchTerm)
    Local $sFileRead
    Local $iPosition
    Local $aResults[0]
    Local $iTotalFound = 0
            
    If Not FileExists($_FILEPATH_LOG) Then
        ConsoleWrite('!>!'&@ScriptLineNumber&': File not found ['&$_FILEPATH_LOG&']'&@CRLF) ;Red/Brown
    Else
        Local $iLineCount = _FileCountLines($_FILEPATH_LOG)
        If Not $iLineCount Or $iLineCount = $_LAST_LOG_LINE_POSITION Then
            Local $sStr = @ScriptLineNumber&': '
            ConsoleWrite($iLineCount > 0 ?  '>-> '& $sStr &'NO NEW LOG UPDATED - ['&$_FILEPATH_LOG&']' &@CRLF : '' & _ ;Yellow
                                            '!>! '& $sStr &'Log File is Emptied - ['&$_FILEPATH_LOG&']'&@CRLF) ;Red
        Else
            ; making sure log file new or got reset
            If $iLineCount < $_LAST_LOG_LINE_POSITION Then
              $_LAST_LOG_LINE_POSITION = 0
              IniWrite($_FILEPATH_INI, "Options", "Last checked position", 0)
            EndIf
            
            Local $hFileOpen = FileOpen($_FILEPATH_LOG, $FO_READ)
            If $hFileOpen = -1 Then
                MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.")
                Return False
            EndIf

            ; only check from: previous line position + 1 to: end of file
            Local $iReposition = $_LAST_LOG_LINE_POSITION + 1 ;<--- prevent from re-checking the last known line position
            For $i = $iReposition To $iLineCount
;~             For $i = $iLineCount To 1 Step -1
                $sFileRead = FileReadLine($hFileOpen, $i)
                $iPosition  = StringInStr($sFileRead, $sSearchTerm)
                ;debug
                Local $sStr = @ScriptLineNumber&': line-'& $i &' | position-'& $iPosition &' | '
                ConsoleWrite($iPosition > 0 ? '    '& $sStr &'found-'& $sSearchTerm &@CRLF : '!>! '& $sStr &'NOT FOUND'&@CRLF) ;White/Red
                ;--opt 1---
                ;keep track all
;~                 $iTotalFound += 1
;~                 _ArrayAdd($aResults,    '#'& $iTotalFound &' - line: '    & $i &'/'& $iLineCount & _
;~                                         ' pos: '     & $iPosition & _
;~                                         ' str: '     & $sSearchTerm)
                ;--opt 2---
                ;keep track only found
                If Not $iPosition Then ContinueLoop
                $iTotalFound += 1
                _ArrayAdd($aResults,    '#'& $iTotalFound &' - line: '    & $i &'/'& $iLineCount & _
                                        ' pos: '     & $iPosition & _
                                        ' str: '     & $sSearchTerm)
            Next
                
            ; remember and prevent from reading old log lines in case of system crash/shutdown/or script terminated
            If $iLineCount > $_LAST_LOG_LINE_POSITION Then
              $_LAST_LOG_LINE_POSITION = $iLineCount
              IniWrite($_FILEPATH_INI, "Options", "Last checked position", $_LAST_LOG_LINE_POSITION)
            EndIf
            FileClose($hFileOpen)
            
            _ArrayInsert($aResults, 0, $iTotalFound)
            If UBound($aResults)-1 Then
                ;MsgBox(0,"Found", $iTotalFound &" ["& $sSearchTerm &"] found", 5)
                _ArrayDisplay($aResults, @ScriptLineNumber&' | Found '&$iTotalFound)
            Else
                MsgBox($MB_ICONWARNING,"Not Found", $iTotalFound &" ["& $sSearchTerm &"] found", 5)
                
            EndIf
        EndIf
    EndIf
EndFunc

 

Link to comment
Share on other sites

  • 3 weeks later...
  • 4 weeks later...
On 10/13/2020 at 10:15 PM, levila said:

Guys, how can i check for multiple strings,

Let say i wan it trigger if Markus, Ben, Tammy string exist.

 

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIFiles.au3>
#include <File.au3>
#include <Array.au3>

Global Const $_FILEPATH_LOG = @ScriptDir & '\_CheckLogFile.txt'
Global Const $_FILEPATH_INI = @ScriptDir & '\_CheckLogFile.ini'
Global $_LAST_LOG_LINE_POSITION = IniRead($_FILEPATH_INI,"Options","Last checked position", 0)

;for testing purposes
FileWrite($_FILEPATH_LOG, 'Markus and Ben are late again'&@CRLF&'Today is a fine day'&@CRLF&'And where are Markus, Ben and Tammy'&@CRLF)

_CheckLogFile("Markus|Ben|Tammy")

Func _CheckLogFile($sSearchTerms)
    Local $sFileRead
    Local $iPosition
    Local $aResults[0]
    Local $iTotalFound = 0
    Local $aSearchTerms = StringSplit($sSearchTerms, '|', 2)
            
    If Not FileExists($_FILEPATH_LOG) Then
        ConsoleWrite('!>!'&@ScriptLineNumber&': File not found ['&$_FILEPATH_LOG&']'&@CRLF) ;Red/Brown
    Else
        Local $iLineCount = _FileCountLines($_FILEPATH_LOG)
        If Not $iLineCount Or $iLineCount = $_LAST_LOG_LINE_POSITION Then
            Local $sStr = @ScriptLineNumber&': '
            ConsoleWrite($iLineCount > 0 ?  '>-> '& $sStr &'NO NEW LOG UPDATED - ['&$_FILEPATH_LOG&']' &@CRLF : '' & _ ;Yellow
                                            '!>! '& $sStr &'Log File is Emptied - ['&$_FILEPATH_LOG&']'&@CRLF) ;Red
        Else
            ; making sure log file new or got reset
            If $iLineCount < $_LAST_LOG_LINE_POSITION Then
              $_LAST_LOG_LINE_POSITION = 0
              IniWrite($_FILEPATH_INI, "Options", "Last checked position", 0)
            EndIf
            
            Local $hFileOpen = FileOpen($_FILEPATH_LOG, $FO_READ)
            If $hFileOpen = -1 Then
                MsgBox($MB_SYSTEMMODAL, "", "An error occurred when reading the file.")
                Return False
            EndIf

            ; only check from: previous line position + 1 to: end of file
            Local $iReposition = $_LAST_LOG_LINE_POSITION + 1 ;<--- prevent from re-checking the last known line position
            For $i = $iReposition To $iLineCount
;~             For $i = $iLineCount To 1 Step -1
                $sFileRead = FileReadLine($hFileOpen, $i)
;~                 $iPosition  = StringInStr($sFileRead, $sSearchTerms)
                
                Local $iPosition = False
                Local $jPosition = 0
                Local $sPosition = ''
                Local $sSearchTerms_result = ''
;~                 _ArrayDisplay($aSearchTerms, UBound($aSearchTerms))
                For $j = 0 To UBound($aSearchTerms)-1
                    $jPosition  = StringInStr($sFileRead, $aSearchTerms[$j])
                    If $jPosition Then 
                        $iPosition = True
                        $sPosition  = $sPosition &','& $jPosition
                        $sSearchTerms_result = $sSearchTerms_result&','&$aSearchTerms[$j]
                        ConsoleWrite('>->'&@ScriptLineNumber&': Line# '&$i&' | Item# '&$j&' - '&$jPosition&'='&$aSearchTerms[$j]&@CRLF) ;Blue/Cyan
                    EndIf
                Next
                If $iPosition Then
                    $sPosition = StringTrimLeft($sPosition, 1)
                    $sSearchTerms_result = StringTrimLeft($sSearchTerms_result, 1)
                EndIf
                    
                
                ;debug
                Local $sStr = @ScriptLineNumber&': line-'& $i &' | position-('& $sPosition &') | '
                ConsoleWrite($iPosition > 0 ? '    '& $sStr &'found-('& $sSearchTerms_result &')'&@CRLF : '!>! '& $sStr &'NOT FOUND for neither [' &$sSearchTerms&']'&@CRLF) ;White/Red
                ;--opt 1---
                ;keep track all
;~                 $iTotalFound += 1
;~                 _ArrayAdd($aResults,    '#'& $iTotalFound &' - line: '    & $i &'/'& $iLineCount & _
;~                                         ' pos: '     & $sPosition & _
;~                                         ' str: '     & $sSearchTerms)
                ;--opt 2---
                ;keep track only found
                If Not $iPosition Then ContinueLoop
                $iTotalFound += 1
                _ArrayAdd($aResults,    'result #'& $iTotalFound &')|'&@CRLF& _
                                        '   log_line: ('    & $i &'/'& $iLineCount &')|'& _
                                        '   at_pos: ('     & $sPosition &')|'& _
                                        '   matched: ('     & $sSearchTerms_result &')')
            Next
                
            ; remember and prevent from reading old log lines in case of system crash/shutdown/or script terminated
            If $iLineCount > $_LAST_LOG_LINE_POSITION Then
              $_LAST_LOG_LINE_POSITION = $iLineCount
              IniWrite($_FILEPATH_INI, "Options", "Last checked position", $_LAST_LOG_LINE_POSITION)
            EndIf
            FileClose($hFileOpen)
            
            _ArrayInsert($aResults, 0, $iTotalFound)
            If UBound($aResults)-1 Then
                ;MsgBox(0,"Found", $iTotalFound &" ["& $sSearchTerms &"] found", 5)
                _ArrayDisplay($aResults, @ScriptLineNumber&' | Found '&$iTotalFound)
            Else
                MsgBox($MB_ICONWARNING,"Not Found", $iTotalFound &" ["& $sSearchTerms &"] found", 5)
                
            EndIf
        EndIf
    EndIf
EndFunc

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...