Merge "Update Configuration guide"
[functest.git] / functest / utils / functest_logger.py
1 #!/usr/bin/env python
2 #
3 # jose.lausuch@ericsson.com
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Logging levels:
10 #  Level     Numeric value
11 #  CRITICAL  50
12 #  ERROR     40
13 #  WARNING   30
14 #  INFO      20
15 #  DEBUG     10
16 #  NOTSET    0
17 #
18 # Usage:
19 #  import functest_logger as fl
20 #  logger = fl.Logger("script_name").getLogger()
21 #  logger.info("message to be shown with - INFO - ")
22 #  logger.debug("message to be shown with - DEBUG -")
23 import logging
24 import logging.config
25 import os
26
27 import json
28
29 from functest.utils.constants import CONST
30
31 logger = logging.getLogger(__name__)
32
33
34 def is_debug():
35     if CONST.CI_DEBUG and CONST.CI_DEBUG.lower() == "true":
36         return True
37     return False
38
39
40 def setup_logging(default_path=CONST.dir_functest_logging_cfg,
41                   default_level=logging.INFO,
42                   env_key='LOG_CFG'):
43     path = default_path
44     value = os.getenv(env_key, None)
45     if value:
46         path = value
47     if os.path.exists(path):
48         with open(path, 'rt') as f:
49             config = json.load(f)
50             if (config['handlers'] and
51                     config['handlers']['console']):
52                 stream_level = logging.INFO
53                 if is_debug():
54                     stream_level = logging.DEBUG
55                 config['handlers']['console']['level'] = stream_level
56             logging.config.dictConfig(config)
57     else:
58         logging.basicConfig(level=default_level)
59
60
61 setup_logging()
62
63
64 class Logger:
65     def __init__(self, logger_name):
66         self.logger = logging.getLogger(logger_name)
67
68     def getLogger(self):
69         return self.logger