Search code examples
pythonpython-2.7pexpect

How do I get timestamps in logfile of pexpect


I am using pexpect to handle my telnet and ssh communication. I am also writing all request/response in a logfile. using pexpect.logfile(filename).

I would like to have timestamps in the logfile as well. I can not find it anywhere in the documentation! Does anyone have any idea how to implement this functionality?


Solution

  • After some searching I found the below code which works for me! Take a look at the below code:

    import logging
    import pexpect
    import re
    
    # this is the method called by the pexpect object to log
    def _write(*args, **kwargs):
        content = args[0]
        # Ignore other params, pexpect only use one arg
        if content in [' ', '', '\n', '\r', '\r\n']:
            return # don't log empty lines
        for eol in ['\r\n', '\r', '\n']:
            # remove ending EOL, the logger will add it anyway
            content = re.sub('\%s$' % eol, '', content)
        return logger.info(content) # call the logger info method with the reworked content
    
    # our flush method
    def _doNothing():
        pass
    
    logger = logging.getLogger('foo')
    hdlr = logging.FileHandler('/bar.log')
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    
    # give the logger the methods required by pexpect
    logger.write = _write
    logger.flush = _doNothing
    
    p = pexpect.spawn('echo "hello world !"', logfile=logger)