80392f59a01b9723dd5e0cb44704bf0dfcbbf8d0
[bottlenecks.git] / utils / logger.py
1 #!/usr/bin/env python
2 ##############################################################################
3 # Copyright (c) 2017 Huawei Technologies Co.,Ltd and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9 ##############################################################################
10 # Logging levels:
11 #  Level     Numeric value
12 #  CRITICAL  50
13 #  ERROR     40
14 #  WARNING   30
15 #  INFO      20
16 #  DEBUG     10
17 #  NOTSET    0
18
19 import logging
20 import os
21
22 from utils.parser import Parser as conf
23
24
25 class Logger:
26     def __init__(self, logger_name):
27
28         # if user set --debug as a cli parameter
29         # we will set this variable "Debug" to output debug info.
30         DEBUG = os.getenv('DEBUG')
31
32         self.logger = logging.getLogger(logger_name)
33         self.logger.propagate = 0
34         self.logger.setLevel(logging.DEBUG)
35
36         ch = logging.StreamHandler()
37         log_formatter = ('%(asctime)s '
38                          '%(name)s %(filename)s:%(lineno)d '
39                          '%(levelname)s %(message)s')
40
41         formatter = logging.Formatter(log_formatter)
42
43         ch.setFormatter(formatter)
44         if DEBUG is not None and DEBUG.lower() == "true":
45             ch.setLevel(logging.DEBUG)
46         else:
47             ch.setLevel(logging.INFO)
48         self.logger.addHandler(ch)
49
50         result_path = conf.bottlenecks_config["log_dir"]
51         if not os.path.exists(result_path):
52             os.makedirs(result_path)
53         result_file = os.path.join(result_path, 'bottlenecks.log')
54         hdlr = logging.FileHandler(result_file)
55
56         hdlr.setFormatter(formatter)
57         hdlr.setLevel(logging.DEBUG)
58         self.logger.addHandler(hdlr)
59
60     def getLogger(self):
61         return self.logger