python實現根據當前時間創建目錄並輸出日志


舉個例子:比如我們要實現根據當前時間的年月日來新建目錄來存放每天的日志,當前時間作為日志文件名稱;代碼如下:

  

#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
import logging
import os.path
import time

project_path = 'Exercise'  #定義項目目錄

class Logger(object):
    def __init__(self):
        '''''
            指定保存日志的文件路徑,日志級別,以及調用文件
            將日志存入到指定的文件中
        '''
        current_time=time.strftime('%Y%m%d%H%M',
                                   time.localtime(time.time()))  # 返回當前時間
        current_path=os.path.dirname(os.path.abspath(project_path))  # 返回當前目錄
        path1=current_path.split(project_path)  #指定分隔符對字符串進行切片
        path2=[path1[0], project_path]
        path3=''
        new_name=path3.join(path2) + '/logs/' #在該路徑下新建下級目錄

        dir_time = time.strftime('%Y%m%d', time.localtime(time.time()))  #返回當前時間的年月日作為目錄名稱
        isExists=os.path.exists(new_name + dir_time)   #判斷該目錄是否存在
        if not isExists:
            os.makedirs(new_name + dir_time)
            print(new_name + dir_time + "目錄創建成功")

        else:
            # 如果目錄存在則不創建,並提示目錄已存在
            print(new_name + "目錄 %s 已存在" % dir_time)


        try:
            # 創建一個logger(初始化logger)
            self.log = logging.getLogger()
            self.log.setLevel(logging.DEBUG)

            # 創建一個handler,用於寫入日志文件


            # 如果case組織結構式 /testsuit/featuremodel/xxx.py , 那么得到的相對路徑的父路徑就是項目根目錄
            log_name = new_name  + dir_time + '/' + current_time + '.log'  #定義日志文件的路徑以及名稱

            fh = logging.FileHandler(log_name)
            fh.setLevel(logging.INFO)

            # 再創建一個handler,用於輸出到控制台
            ch = logging.StreamHandler()
            ch.setLevel(logging.INFO)

            # 定義handler的輸出格式
            formatter = logging.Formatter('[%(asctime)s] - %(name)s - %(levelname)s - %(message)s')
            fh.setFormatter(formatter)
            ch.setFormatter(formatter)

            # 給logger添加handler
            self.log.addHandler(fh)
            self.log.addHandler(ch)
        except Exception as e:
            print("輸出日志失敗! %s" % e)

    # 日志接口,用戶只需調用這里的接口即可,這里只定位了INFO, WARNING, ERROR三個級別的日志,可根據需要定義更多接口

    def info(cls,msg):
        cls.log.info(msg)
        return


    def warning(cls,msg):
        cls.log.warning(msg)
        return


    def error(cls, msg):
        cls.log.error(msg)
        return

if __name__ == '__main__':

    logger = Logger()
    logger.info('This is info')
    logger.warning('This is warning')
    logger.error('This is error')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM