• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4#
5# Copyright (c) 2023 Huawei Device Co., Ltd.
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
19import codecs
20import sys
21import time
22import os
23import json
24import logging.config
25from logging import FileHandler
26
27
28class SafeFileHandler(FileHandler):
29    def __init__(self, filename, mode="a", encoding="utf-8", delay=0, suffix="%Y-%m-%d_%H"):
30        if codecs is None:
31            encoding = None
32        current_time = time.strftime(suffix, time.localtime())
33        FileHandler.__init__(self, filename + "." + current_time, mode, encoding, delay)
34
35        self.filename = os.fspath(filename)
36
37        self.mode = mode
38        self.encoding = encoding
39        self.suffix = suffix
40        self.suftime = current_time
41
42    def emit(self, record):
43        try:
44            if self.parse_file_name():
45                self.gen_file_name()
46            FileHandler.emit(self, record)
47        except Exception as e:
48            print(e)
49            self.handleError(record)
50
51    def parse_file_name(self):
52        time_tuple = time.localtime()
53
54        if self.suftime != time.strftime(self.suffix, time_tuple) or not os.path.exists(
55                os.path.abspath(self.filename) + '.' + self.suftime):
56            return 1
57        else:
58            return 0
59
60    def gen_file_name(self):
61        if self.stream:
62            self.stream.close()
63            self.stream = None
64
65        if self.suftime != "":
66            index = self.baseFilename.find("." + self.suftime)
67            if index == -1:
68                index = self.baseFilename.rfind(".")
69            self.baseFilename = self.baseFilename[:index]
70
71        cur_time = time.localtime()
72        self.suftime = time.strftime(self.suffix, cur_time)
73        self.baseFilename = os.path.abspath(self.filename) + "." + self.suftime
74
75        if not self.delay:
76            self.stream = open(self.baseFilename, self.mode, encoding=self.encoding)
77
78
79def get_logger(class_name, level="info"):
80    formate = "%(asctime)s -%(levelname)s - %(name)s - %(message)s"
81    formatter = logging.Formatter(formate)
82    log_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "log")
83    if not os.path.exists(log_path):
84        os.makedirs(log_path)
85    tfr_handler = SafeFileHandler(os.path.join(log_path, class_name + ".log"))
86    tfr_handler.setFormatter(formatter)
87
88    sh = logging.StreamHandler()
89    sh.setFormatter(formatter)
90
91    logger = logging.getLogger(class_name)
92    logger.addHandler(tfr_handler)
93    logger.addHandler(sh)
94
95    if level == 'info':
96        logger.setLevel(logging.INFO)
97    elif level == 'error':
98        logger.setLevel(logging.ERROR)
99    return logger
100
101
102def parse_json():
103    config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "build_example.json")
104    try:
105        with open(config_path, "r", encoding="utf-8") as json_file:
106            data = json.load(json_file)
107            return data
108    except Exception as e:
109        print(e)
110
111