Ignore:
Timestamp:
15 Mar 2007, 10:46:22 (18 years ago)
Author:
uli
Message:

Added func in WAeUPTool to get last lines of logfiles securely.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • WAeUP_SRP/branches/uli/WAeUPTool.py

    r1467 r1550  
    478478    ###)
    479479
     480    security.declareProtected(ModifyPortalContent,'getLogfileLines') ###(
     481    def getLogfileLines(self,filename="event.log",numlines=20):
     482        """Get last NUMLINES lines of logfile FILENAME.
     483   
     484        Return last lines' of a file in the instances logfile directory as
     485        a list. The number of returned lines equals `numlines' or less. If
     486        less than `numlines' lines are available, the whole file ist
     487        returned. If the file can not be opened or some other error
     488        occurs, empty list is returend.
     489        """
     490        result = []
     491        lines_hit = 0
     492
     493        # We only handle files in instances' log directory...
     494        logpath = os.path.join(i_home, "log")
     495        filename = str(os.path.abspath( os.path.join( logpath, filename )))
     496        if not filename.startswith( logpath ):
     497            # Attempt to access file outside log-dir...
     498            return []
     499       
     500        try:
     501            fd = file( filename, "rb" )
     502        except IOError:
     503            return []
     504        if not fd:
     505            return []
     506   
     507        if os.linesep == None:
     508            linesep = '\n'
     509        else:
     510            linesep = os.linesep
     511   
     512        # Try to find 'numlines' times a lineseparator, searching from end
     513        # and moving to the beginning of file...
     514        fd.seek( 0, 2) # Move to end of file...
     515        while lines_hit < numlines:
     516            if fd.read(1) == linesep[-1]: # This moves filedescriptor
     517                                          # one step forward...
     518                lines_hit += 1
     519            try:
     520                fd.seek( -2, 1) # Go two bytes back from current pos...
     521            except IOError:
     522                # We cannot go back two bytes. Maybe the file is too small...
     523                break
     524        fd.seek(2,1)
     525
     526        # Read all lines from current position...
     527        result = fd.readlines()
     528        # Remove line endings...
     529        result = [x.strip() for x in result]
     530        fd.close()   
     531        return result
     532    ###)
     533
    480534
    481535InitializeClass(WAeUPTool)
Note: See TracChangeset for help on using the changeset viewer.