Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 461
theAlse Avatar asked Dec 30 '25 00:12

theAlse


1 Answers

logfile can be any object that has write(), flush() methods:

from datetime import datetime

class TimestampedFile(object):
    def __init__(self, file):
        self.file = file

    def write(self, data):
        # .. filter data however you like
        ts = datetime.utcnow().isoformat()  # generate timestamp
        return self.file.write("%s %s\n" % (ts, data))  # write to original file

    def flush(self):
        self.file.flush()

Example

with open(filename, 'w') as file:
    pexpect.run('echo "hello world!"', logfile=TimestampedFile(file))    

Your logging example could be simplified:

class FileAdapter(object):
    def __init__(self, logger):
        self.logger = logger
    def write(self, data):
        # NOTE: data can be a partial line, multiple lines
        data = data.strip() # ignore leading/trailing whitespace
        if data: # non-blank
           self.logger.info(data)
    def flush(self):
        pass  # leave it to logging to flush properly

Example

# setup logging to include a timestamp
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.INFO)
# ... run command sometime later
pexpect.run('echo "hello world!"', logfile=FileAdapter(logging.getLogger('foo')))
like image 148
jfs Avatar answered Jan 01 '26 12:01

jfs