Updates ODL Pipeline scripts for CSIT
[sdnvpn.git] / odl-pipeline / lib / utils / utils_log.py
1 #
2 # Copyright (c) 2015 All rights reserved
3 # This program and the accompanying materials
4 # are made available under the terms of the Apache License, Version 2.0
5 # which accompanies this distribution, and is available at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #
10 import logging
11 import datetime
12 import os
13 import sys
14 import types
15
16 LOG = logging.getLogger(__name__)
17 LOG_LEVEL = logging.DEBUG
18 LOG_PATH = "./tmp/%s.log" % os.path.basename(sys.argv[0])
19 logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
20                     filename=LOG_PATH, level=LOG_LEVEL)
21 #                    datefmt='%Y-%m-%dT:%H:%M:%s', level=LOG_LEVEL)
22 console = logging.StreamHandler()
23 console.setLevel(logging.INFO)
24 formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
25 console.setFormatter(formatter)
26 LOG.addHandler(console)
27
28
29 def log_enter_exit(func):
30
31     def inner(self, *args, **kwargs):
32         LOG.debug(("Entering %(cls)s.%(method)s "
33                    "args: %(args)s, kwargs: %(kwargs)s") %
34                   {'cls': self.__class__.__name__,
35                    'method': func.__name__,
36                    'args': args,
37                    'kwargs': kwargs})
38         start = datetime.datetime.now()
39         if isinstance(func, types.FunctionType):
40             ret = func(*args, **kwargs)
41         else:
42             ret = func(self, *args, **kwargs)
43         end = datetime.datetime.now()
44         LOG.debug(("Exiting %(cls)s.%(method)s. "
45                    "Spent %(duration)s sec. "
46                    "Return %(return)s") %
47                   {'cls': self.__class__.__name__,
48                    'duration': end - start,
49                    'method': func.__name__,
50                    'return': ret})
51         return ret
52     return inner
53
54
55 def for_all_methods(decorator):
56     # @for_all_methods(log_enter_exit)
57     # class ...
58
59     def decorate(cls):
60         for attr in cls.__dict__:
61             if callable(getattr(cls, attr)):
62                 setattr(cls, attr, decorator(getattr(cls, attr)))
63         return cls
64     return decorate
65
66
67 def dict_to_nice_string(dict):
68     return_string = []
69     for key, value in dict.iteritems():
70         return_string.append('%s: %s' % (key, value))
71     return ', '.join(return_string)