various cosmetic changes
[nodemanager.git] / logger.py
1 #
2 # Something relevant
3 #
4 """A very simple logger that tries to be concurrency-safe."""
5
6 import os, sys
7 import subprocess
8 import time
9 import traceback
10
11
12 LOG_FILE = '/var/log/nm'
13 LOG_SLIVERS = '/var/log/getslivers.txt'
14
15 # Thierry - trying to debug this for 4.2
16 # basically define 3 levels
17 LOG_NONE=0
18 LOG_NODE=1
19 LOG_VERBOSE=2
20 # default is to log a reasonable amount of stuff for when running on operational nodes
21 LOG_LEVEL=1
22
23 def set_level(level):
24     global LOG_LEVEL
25     assert level in [LOG_NONE,LOG_NODE,LOG_VERBOSE]
26     LOG_LEVEL=level
27
28 def verbose(msg):
29     log(msg,LOG_VERBOSE)
30
31 def log(msg,level=LOG_NODE):
32     """Write <msg> to the log file if level >= current log level (default LOG_NODE)."""
33     if (level > LOG_LEVEL):
34         return
35     try:
36         fd = os.open(LOG_FILE, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0600)
37         if not msg.endswith('\n'): msg += '\n'
38         os.write(fd, '%s: %s' % (time.asctime(time.gmtime()), msg))
39         os.close(fd)
40     except OSError:
41         sys.stderr.write(msg)
42         sys.stderr.flush()
43
44 def log_call(*args):
45     log('running command %s' % ' '.join(args))
46     try: subprocess.call(args, close_fds=True)
47     except: log_exc()
48
49 def log_exc(name = None):
50     """Log the traceback resulting from an exception."""
51     if name:  
52         log("operation on %s failed.  \n %s" %(name, traceback.format_exc()))
53     else:
54         log(traceback.format_exc())
55
56 def log_slivers (data):
57     import pprint, time
58     try:
59         f=open(LOG_SLIVERS,'w')
60         now=time.strftime("GetSlivers stored on %Y.%m.%d at %H:%M:%S", time.localtime())
61         f.write(now+'\n')
62         pp=pprint.PrettyPrinter(stream=f,indent=2)
63         pp.pprint(data)
64         f.close()
65     except:
66         log_verbose('Cannot save GetSlivers in %s'%LOG_SLIVERS)