You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

log.py 2.3 kB

5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Copyright 2019 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Log collection function:
  16. import logging plugin, achieve all-round log printing.
  17. You can arbitrarily choose the required log level as
  18. it is divided by the logging module.
  19. such as:
  20. 2019-09-09 15:17:15 INFO *.py: func name: line
  21. 2019-09-09 14:32:57 WARNING *.py: func name: line
  22. 2019-09-09 15:11:41 ERROR *.py: func name: line
  23. """
  24. import os
  25. import logging
  26. import logging.handlers
  27. from logging.handlers import TimedRotatingFileHandler
  28. import traceback
  29. import random
  30. import string
  31. import sys
  32. class Log(logging.Logger):
  33. def __init__(self, case_name, case_path):
  34. super(Log, self).__init__(case_name)
  35. self.log = logging.getLogger(case_name + ''.join([random.choice(string.digits + string.ascii_letters) for _ in range(8)]))
  36. self.log.setLevel(logging.DEBUG)
  37. fmt = '%(levelname)s %(asctime)s - %(filename)s:%(funcName)s:%(lineno)s - %(message)s'
  38. datefmt = '%Y-%m-%d %H:%M:%S'
  39. formatter = logging.Formatter(fmt, datefmt)
  40. logfile = os.path.join(case_path, '{0}.log'.format(case_name))
  41. fh = TimedRotatingFileHandler(logfile, when='D', interval=1, backupCount=10)
  42. fh.setLevel(logging.DEBUG)
  43. fh.setFormatter(formatter)
  44. self.log.removeHandler(fh)
  45. self.log.addHandler(fh)
  46. ch = logging.StreamHandler(sys.stdout)
  47. ch.setLevel(logging.INFO)
  48. ch.setFormatter(formatter)
  49. self.log.removeHandler(ch)
  50. self.log.addHandler(ch)
  51. def traceback(self):
  52. """
  53. The traceback module prints out the details of the case execution failure.
  54. """
  55. self.log.error("There are something error appear.")
  56. traceback.print_exc()