f453c5745da630ff2ed185441ce7c4b7362b2942
[samplevnf.git] / VNFs / DPPD-PROX / helper-scripts / rapid / rapid_log.py
1 #!/usr/bin/python
2
3 ##
4 ## Copyright (c) 2020 Intel Corporation
5 ##
6 ## Licensed under the Apache License, Version 2.0 (the "License");
7 ## you may not use this file except in compliance with the License.
8 ## You may obtain a copy of the License at
9 ##
10 ##     http://www.apache.org/licenses/LICENSE-2.0
11 ##
12 ## Unless required by applicable law or agreed to in writing, software
13 ## distributed under the License is distributed on an "AS IS" BASIS,
14 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 ## See the License for the specific language governing permissions and
16 ## limitations under the License.
17 ##
18
19 import logging
20 from logging.handlers import RotatingFileHandler
21 from logging import handlers
22 import os
23 import sys
24 import time
25
26 class bcolors(object):
27     HEADER = '\033[95m'
28     OKBLUE = '\033[94m'
29     OKGREEN = '\033[92m'
30     WARNING = '\033[93m'
31     FAIL = '\033[91m'
32     ENDC = '\033[0m'
33     BOLD = '\033[1m'
34     UNDERLINE = '\033[4m'
35     FLASH = '\033[5m'
36
37 class RapidLog(object):
38     """
39     Class to deal with rapid logging
40     """
41     log = None
42
43     @staticmethod
44     def log_init(log_file, loglevel, screenloglevel, version):
45         log = logging.getLogger(__name__)
46         makeFileHandler = True
47         makeStreamHandler = True
48         if len(log.handlers) > 0:
49             for handler in log.handlers:
50                 if isinstance(handler, logging.FileHandler):
51                     makeFileHandler = False
52                 elif isinstance(handler, logging.StreamHandler):
53                     makeStreamHandler = False
54         if makeStreamHandler:
55             # create formatters
56             screen_formatter = logging.Formatter("%(message)s")
57             # create a console handler
58             # and set its log level to the command-line option 
59             # 
60             console_handler = logging.StreamHandler(sys.stdout)
61             #console_handler.setLevel(logging.INFO)
62             numeric_screenlevel = getattr(logging, screenloglevel.upper(), None)
63             if not isinstance(numeric_screenlevel, int):
64                 raise ValueError('Invalid screenlog level: %s' % screenloglevel)
65             console_handler.setLevel(numeric_screenlevel)
66             console_handler.setFormatter(screen_formatter)
67             # add handler to the logger
68             #
69             log.addHandler(console_handler)
70         if makeFileHandler:
71             # create formatters
72             file_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
73             # get a top-level logger,
74             # set its log level,
75             # BUT PREVENT IT from propagating messages to the root logger
76             #
77             numeric_level = getattr(logging, loglevel.upper(), None)
78             if not isinstance(numeric_level, int):
79                 raise ValueError('Invalid log level: %s' % loglevel)
80             log.setLevel(numeric_level)
81             log.propagate = 0
82
83
84             # create a file handler
85             # and set its log level
86             #
87             file_handler = logging.handlers.RotatingFileHandler(log_file, backupCount=10)
88             file_handler.setLevel(numeric_level)
89             file_handler.setFormatter(file_formatter)
90
91             # add handler to the logger
92             #
93             log.addHandler(file_handler)
94
95             # Check if log exists and should therefore be rolled
96             needRoll = os.path.isfile(log_file)
97
98
99             # This is a stale log, so roll it
100             if needRoll:    
101                 # Add timestamp
102                 log.debug('\n---------\nLog closed on %s.\n---------\n' % time.asctime())
103
104                 # Roll over on application start
105                 file_handler.doRollover()
106
107         # Add timestamp
108         log.debug('\n---------\nLog started on %s.\n---------\n' % time.asctime())
109
110         log.debug("rapid version: " + version)
111         RapidLog.log = log
112
113     @staticmethod
114     def log_close():
115         for handler in RapidLog.log.handlers:
116             if isinstance(handler, logging.FileHandler):
117                 handler.close()
118                 RapidLog.log.removeHandler(handler)
119
120     @staticmethod
121     def exception(exception_info):
122         RapidLog.log.exception(exception_info)
123         raise Exception(exception_info)
124
125     def critical(critical_info):
126         RapidLog.log.critical(critical_info)
127         raise Exception(critical_info)
128
129     @staticmethod
130     def error(error_info):
131         RapidLog.log.error(error_info)
132
133     @staticmethod
134     def debug(debug_info):
135         RapidLog.log.debug(debug_info)
136
137     @staticmethod
138     def info(info):
139         RapidLog.log.info(info)