Setting tag nodemanager-1.8-39
[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: 
47         child = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
48         child.wait() # wait for proc to hang up
49         if child.returncode:
50                 raise Exception("command failed:\n stdout - %s\n stderr - %s" % \
51                         (child.stdout.readlines(), child.stderr.readlines()))
52     except: log_exc()
53
54 def log_exc(name = None):
55     """Log the traceback resulting from an exception."""
56     if name:  
57         log("operation on %s failed.  \n %s" %(name, traceback.format_exc()))
58     else:
59         log(traceback.format_exc())
60
61 def log_slivers (data):
62     import pprint, time
63     try:
64         f=open(LOG_SLIVERS,'w')
65         now=time.strftime("GetSlivers stored on %Y.%m.%d at %H:%M:%S", time.localtime())
66         f.write(now+'\n')
67         pp=pprint.PrettyPrinter(stream=f,indent=2)
68         pp.pprint(data)
69         f.close()
70     except:
71         log_verbose('Cannot save GetSlivers in %s'%LOG_SLIVERS)