First version. Most definitely a work in progress.
[nodemanager.git] / logger.py
1 import fcntl
2 import os
3 import subprocess
4 import time
5 import traceback
6
7 from config import LOG_FILE
8
9
10 def log(msg):
11     """Write <msg> to the log file."""
12     # the next three lines ought to be an atomic operation but aren't
13     fd = os.open(LOG_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
14     flags = fcntl.fcntl(fd, fcntl.F_GETFD)
15     fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
16     if not msg.endswith('\n'): msg += '\n'
17     os.write(fd, '%s: %s' % (time.asctime(time.gmtime()), msg))
18     os.close(fd)
19
20 def log_call(*args):
21     log('running command %s' % ' '.join(args))
22     try: subprocess.call(args)
23     except: log_exc()
24
25 def log_exc():
26     """Log the traceback resulting from an exception."""
27     log(traceback.format_exc())