Adrian Nier Code

Back to overview

Newest log entry

Last modification: Thursday, June 11, 2009 08:02 pm

Filters the contents of a given log file with grep and returns the last occurrence of the result. If no match is found in the specified log file, archived versions, if any, are searched as well.

Required parameters
_filter (string)
A regular expression that the grep tool uses to filter the contents of the log file

_logFilePosixPath (string)
Unquoted and unescaped posix path to the log file
 

Function Calls

-- Display the most recent Time Machine backup failed message
newestLogEntry("backupd.*backup failed", "/var/log/system.log")

-- Display the most recent Time Machine backup completed message
newestLogEntry("backupd.*backup completed", "/var/log/system.log")

-- Display the most recent Showing Login window message
newestLogEntry("showing login window", "/var/log/secure.log")

-- Display the most recent System Wake message
newestLogEntry("kernel.*system.*wake", "/var/log/system.log")

Implementation

on newestLogEntry(_filter, _logFilePosixPath)
   
   set _logLine to false
   
   try
      -- Return the last occurrence of the matching log message
      set _logLine to last paragraph of (do shell script "grep -i " & quoted form of _filter & " " & quoted form of _logFilePosixPath)
      
   on error
      
      try
         -- Check for archived log files
         set _logFiles to (paragraphs of (do shell script "ls " & quoted form of _logFilePosixPath & ".*.bz2"))
      on error
         return false
      end try
      
      -- Try to find a matching message in the archived log files
      repeat with _logFile in _logFiles
         set _logFileQPP to quoted form of (_logFile as string)
         try
            set _logLine to (last paragraph of (do shell script "bzcat " & _logFileQPP & " | grep -i " & quoted form of _filter))
            exit repeat
         end try
      end repeat
      
   end try
   
   return _logLine
   
end newestLogEntry