欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中的日志文件按天分割

 更新時間:2023年08月15日 17:14:05   作者:城先生的小白之路  
這篇文章主要介紹了python中的日志文件按天分割方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

python日志文件按天分割

在服務(wù)器的使用過程中,我經(jīng)常會有長時間運行的服務(wù),那么為了方便我們查看日志,所以會產(chǎn)生每天都能新建一個新的日志文件的需求,其實這個問題很簡單,只需要使用python的logging庫的handlers模塊的TimedRotatingFileHandler類即可

話不多說,上代碼,邊看代碼邊解釋

# #coding=utf-8
import logging,os  # 引入logging模塊
from com_tools import setting
from logging import handlers
class Logger(object):
    level_relations = {
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warning':logging.WARNING,
        'error':logging.ERROR,
        'crit':logging.CRITICAL
    }#日志級別關(guān)系映射
    def __init__(self,filename,level='info',when='MIDNIGHT',backCount=7,fmt='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'):
        self.logger = logging.getLogger(filename)
        format_str = logging.Formatter(fmt)#設(shè)置日志格式
        self.logger.setLevel(self.level_relations.get(level))#設(shè)置日志級別
        sh = logging.StreamHandler()#往控制臺輸出
        sh.setFormatter(format_str) #設(shè)置控制臺上顯示的格式
        th = handlers.TimedRotatingFileHandler(filename=filename,interval=1,when=when,backupCount=backCount,encoding='utf-8')#往文件里寫入#指定間隔時間自動生成文件的處理器
        #實例化TimedRotatingFileHandler
        #interval是時間間隔,backupCount是備份文件的個數(shù),如果超過這個個數(shù),就會自動刪除,when是間隔的時間單位,單位有以下幾種:
        # S 秒
        # M 分
        # H 小時、
        # D 天、
        # W 每星期(interval==0時代表星期一)
        # midnight 每天凌晨
        th.suffix = "%Y-%m-%d.log" #設(shè)置文件后綴
        th.setFormatter(format_str)#設(shè)置文件里寫入的格式
        self.logger.addHandler(sh) #把對象加到logger里
        self.logger.addHandler(th)
logfile = os.path.join(setting.logs_path, "daodianmockapi.txt") # 這個文件的名稱就是當(dāng)天的日志文件,過往的日志文件,會在后面追加文件后綴 th.suffix
logger = Logger(logfile,level='debug')
if __name__ == '__main__':
    #logger = Logger('all.log',level='debug')
    # filename = setting.now_time+ ".txt"
    # logfile = os.path.join(setting.logs_path,filename)
    # logger = Logger(logfile,level='debug')
    logger.logger.debug('debug') # 括號內(nèi)的內(nèi)容即為日志的文本內(nèi)容
    logger.logger.info('info')
    logger.logger.warning('警告')
    logger.logger.error('報錯')
    logger.logger.critical('嚴(yán)重')
    #Logger('error.log', level='error').logger.error('error')

日志分解分割效果

注意:

整個flask框架寫mock接口就到這里結(jié)束了,后面應(yīng)該是寫Django的學(xué)習(xí)了

python切割大日志文件幾種方式

工作線上報錯了,找運維下載了線上的日志文件排查問題,但是日志文件太大了,沒辦法用NotePad++打開,于是乎想著要切割一下日志文件

方法一:指定目標(biāo)文件數(shù)量分割

import os
# 要分割的文件
sourceFileName = 'normal-app.log'
# 分割的文件個數(shù)
fileNum = 10       
def cutFile():
    print("正在讀取文件...")
    sourceFileData = open(sourceFileName, 'r', encoding='utf-8')
    ListOfLine = sourceFileData.read().splitlines()  # 將讀取的文件內(nèi)容按行分割,然后存到一個列表中
    totalLine = len(ListOfLine)
    print("文件共有" + str(totalLine) + "行")
    print("請輸入需要將文件分割的個數(shù):") 
    p = totalLine//fileNum + 1
    print("需要將文件分成"+str(fileNum)+"個子文件")
    print("每個文件最多有"+str(p)+"行")
    print("開始進(jìn)行分割···")
    for i in range(fileNum):
        destFileName = os.path.splitext(sourceFileName)[
            0] + "_" + str(i + 1)+".log"
        print("正在生成子文件" + destFileName)
        destFileData = open(destFileName, "w", encoding='utf-8')
        if(i == fileNum-1):
            for line in ListOfLine[i*p:]:
                destFileData.write(line+'\n')
        else:
            for line in ListOfLine[i*p:(i+1)*p]:
                destFileData.write(line+'\n')
        destFileData.close()
    print("分割完成")
if __name__ == '__main__':
    cutFile()

方法二:指定文件大小分割

這種方法是按照大小分割文件,會存在同一行被分割在兩個文件中的情況

import os
filename = "normal-app.log"  # 需要進(jìn)行分割的文件
size = 10000000  # 分割大小10M
def createSubFile(srcName, sub, buf):
    [des_filename, extname] = os.path.splitext(srcName)
    filename = des_filename + '_' + str(sub) + extname
    print('正在生成子文件: %s' % filename)
    with open(filename, 'wb') as fout:
        fout.write(buf)
        return sub+1
def cutFile(filename, size):
    with open(filename, 'rb') as fin:
        buf = fin.read(size)
        sub = 1
        while len(buf) > 0:
            sub = createSubFile(filename, sub, buf)
            buf = fin.read(size)
    print("ok")
if __name__ == "__main__":
    cutFile(filename, size)

方法三:指定目標(biāo)行數(shù)分割

import os
# 要分割的文件
sourceFileName = 'normal-app.log'
 # 定義分割的行數(shù)
lineNum = 100000    
def cutFile():
    print("正在讀取文件...")
    sourceFileData = open(sourceFileName, 'r', encoding='utf-8')
    ListOfLine = sourceFileData.read().splitlines()  # 將讀取的文件內(nèi)容按行分割,然后存到一個列表中
    totalLine = len(ListOfLine)
    print("文件共有" + str(totalLine) + "行")
    print("請輸入需要將文件分割的個數(shù):") 
    fileNum = totalLine//lineNum + 1
    print("需要將文件分成"+str(fileNum)+"個子文件")
    print("開始進(jìn)行分割···")
    for i in range(fileNum):
        destFileName = os.path.splitext(sourceFileName)[
            0] + "_" + str(i + 1)+".log"
        print("正在生成子文件" + destFileName)
        destFileData = open(destFileName, "w", encoding='utf-8')
        if(i == fileNum-1):
            for line in ListOfLine[i*lineNum:]:
                destFileData.write(line+'\n')
        else:
            for line in ListOfLine[i*lineNum:(i+1)*lineNum]:
                destFileData.write(line+'\n')
        destFileData.close()
    print("分割完成")
if __name__ == '__main__':
    cutFile()

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論