記錄執行時間裝飾器(代碼)

import datetime
import time

from common import Log


class GetTime:
    '''不帶參數的裝飾器,獲取花費時間'''

    def use_time(func):
        def _func(self, *args, **kwargs):
            start = datetime.datetime.now()
            func(self)
            end = datetime.datetime.now()
            func_name = self.__class__.__name__
            Log.i(func_name,'cost:{}s'.format((end - start).seconds))

        return _func
    '''帶參數的裝飾器,獲取花費時間'''
    def use_time_by_func(func_name):
        def use_time(func):
            def _func(self, *args, **kwargs):
                start = datetime.datetime.now()
                func(self)
                end = datetime.datetime.now()
                Log.i(func_name,'cost:{}s'.format((end - start).seconds))
            return _func
        return use_time

    @use_time
    def sleep(self):
        time.sleep(1)

    @use_time_by_func(func_name='sleep_func')
    def sleep_func(self):
        time.sleep(1)


if __name__ == '__main__':
    GetTime().sleep()
    GetTime().sleep_func()

log記錄:

import datetime
import os
import threading

'''
Log封裝
'''
class Log:
    def log_info(self, func_name, state, info):
        '''
        :param state: info/error
        :param info: 日誌內容
        :return:
        '''
        log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'log')
        file_name = datetime.datetime.now().strftime('%Y%m%d')
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        thread_name = threading.currentThread().name
        info_title = '_'.join([thread_name, state, now,func_name])
        print('{info_title}=====>{info}'.format(info_title=info_title, info=info))
        with open(os.path.join(log_path, file_name + '_{}.txt'.format(state)), 'a+') as f:
            f.write('\n{info_title}=====>{info}'.format(info_title=info_title, info=info))

    @staticmethod
    def e(func_name, error):
        Log().log_info(func_name, 'error', error)

    @staticmethod
    def i(func_name, info):
        Log().log_info(func_name, 'info', info)

    @staticmethod
    def a(func_name,info):
        Log().log_info(func_name,'info', info)
        Log().log_info(func_name,'error', info)

3、結果:

MainThread_info_2020-06-22 20:52:24_GetTime=====>cost:1s
MainThread_info_2020-06-22 20:52:25_sleep_func=====>cost:1s

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章