logs for when PLC is unreachable
[nodemanager.git] / logger.py
1 # $Id$
2 # $URL$
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('(v) '+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('failed to run command %s' % ' '.join(args))
53
54 def log_exc(msg="",name=None):
55     """Log the traceback resulting from an exception."""
56     if name: 
57         log("%s: EXCEPTION caught <%s> \n %s" %(name, msg, traceback.format_exc()))
58     else:
59         log("EXCEPTION caught <%s> \n %s" %(msg, traceback.format_exc()))
60
61 # for some reason the various modules are still triggered even when the
62 # data from PLC cannot be reached
63 # we show this message instead of the exception stack instead in this case
64 def log_missing_data (msg,key):
65     log("%s: could not find the %s key in data (PLC connection down?) - IGNORED"%(msg,key))
66
67 def log_data_in_file (data, file, message=""):
68     import pprint, time
69     try:
70         f=open(file,'w')
71         now=time.strftime("Last update: %Y.%m.%d at %H:%M:%S %Z", time.localtime())
72         f.write(now+'\n')
73         if message: f.write('Message:'+message+'\n')
74         pp=pprint.PrettyPrinter(stream=f,indent=2)
75         pp.pprint(data)
76         f.close()
77     except:
78         log_verbose('log_data_in_file failed - file=%s - message=%r'%(file,message))
79
80 def log_slivers (data):
81     log_data_in_file (data, LOG_SLIVERS, "raw GetSlivers")