fix to get logfile
[doctor.git] / doctor_tests / logger.py
1 ##############################################################################
2 # Copyright (c) 2016 ZTE Corporation and others.
3 #
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 # Usage:
10 #  import doctor_logger
11 #  logger = doctor_logger.Logger("script_name").getLogger()
12 #  logger.info("message to be shown with - INFO - ")
13 #  logger.debug("message to be shown with - DEBUG -")
14
15 import logging
16 import os
17
18 from doctor_tests.common.utils import get_doctor_test_root_dir
19
20
21 class Logger(object):
22     def __init__(self, logger_name):
23
24         CI_DEBUG = os.getenv('CI_DEBUG')
25
26         self.logger = logging.getLogger(logger_name)
27         self.logger.propagate = 0
28         self.logger.setLevel(logging.DEBUG)
29
30         formatter = logging.Formatter('%(asctime)s %(filename)s %(lineno)d '
31                                       '%(levelname)-6s %(message)s')
32
33         ch = logging.StreamHandler()
34         ch.setFormatter(formatter)
35         if CI_DEBUG is not None and CI_DEBUG.lower() == "true":
36             ch.setLevel(logging.DEBUG)
37         else:
38             ch.setLevel(logging.INFO)
39         self.logger.addHandler(ch)
40
41         test_dir = get_doctor_test_root_dir()
42         self.filename = '{0}/{1}.log'.format(test_dir, logger_name)
43         file_handler = logging.FileHandler(self.filename, mode='w')
44         file_handler.setFormatter(formatter)
45         file_handler.setLevel(logging.DEBUG)
46         self.logger.addHandler(file_handler)
47
48     def getLogger(self):
49         return self.logger
50
51     def getLogFilename(self):
52         return self.filename