python日志切割
㈠ 如何用 python 分析网站日志
日志的记录
Python有一个logging模块,可以用来产生日志。
(1)学习资料
http://blog.sina.com.cn/s/blog_4b5039210100f1wv.html
http://blog.donews.com/limodou/archive/2005/02/16/278699.aspx
http://kenby.iteye.com/blog/1162698
http://blog.csdn.NET/fxjtoday/article/details/6307285
前边几篇文章仅仅是其它人的简单学习经验,下边这个链接中的内容比较全面。
http://www.red-dove.com/logging/index.html
(2)我需要关注内容
日志信息输出级别
logging模块提供了多种日志级别,如:NOTSET(0),DEBUG(10),
INFO(20),WARNING(30),WARNING(40),CRITICAL(50)。
设置方法:
logger = getLogger()
logger.serLevel(logging.DEBUG)
日志数据格式
使用Formatter设置日志的输出格式。
设置方法:
logger = getLogger()
handler = loggingFileHandler(XXX)
formatter = logging.Formatter("%(asctime)s %(levelname) %(message)s","%Y-%m-%d,%H:%M:%S")
%(asctime)s表示记录日志写入时间,"%Y-%m-%d,%H:%M:%S“设定了时间的具体写入格式。
%(levelname)s表示记录日志的级别。
%(message)s表示记录日志的具体内容。
日志对象初始化
def initLog():
logger = logging.getLogger()
handler = logging.FileHandler("日志保存路径")
formatter = logging.Formatter("%(asctime)s %(levelname) %(message)s","%Y-%m-%d,%H:%M:%S")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel
写日志
logging.getLogger().info(), logging.getLogger().debug()......
2. 日志的分析。
(1)我的日志的内容。(log.txt)
2011-12-12,12:11:31 INFO Client1: 4356175.0 1.32366309133e+12 1.32366309134e+12
2011-12-12,12:11:33 INFO Client1: 4361320.0 1.32366309334e+12 1.32366309336e+12
2011-12-12,12:11:33 INFO Client0: 4361320.0 1.32366309389e+12 1.32366309391e+12
2011-12-12,12:11:39 INFO Client1: 4366364.0 1.32366309934e+12 1.32366309936e+12
2011-12-12,12:11:39 INFO Client0: 4366364.0 1.32366309989e+12 1.32366309991e+12
2011-12-12,12:11:43 INFO Client1: 4371416.0 1.32366310334e+12 1.32366310336e+12
2011-12-12,12:11:43 INFO Client0: 4371416.0 1.32366310389e+12 1.32366310391e+12
2011-12-12,12:11:49 INFO Client1: 4376450.0 1.32366310934e+12 1.32366310936e+12
我需要将上述内容逐行读出,并将三个时间戳提取出来,然后将其图形化。
(2) 文件操作以及字符串的分析。
打开文件,读取出一行日志。
file = file("日志路径",“r”)
while True:
line = file.readline()
if len(len) == 0:
break;
print line
file.close()
从字符串中提取数据。
字符串操作学习资料:
http://reader.you.com/sharelite?itemId=-4646262544179865983&method=viewSharedItemThroughLink&sharedBy=-1137845767117085734
从上面展示出来的日志内容可见,主要数据都是用空格分隔,所以需要使用字符串的
split函数对字符串进行分割:
paraList = line.split(),该函数默认的分割符是空格,返回值为一个list。
paraList[3], paraList[4], paraList[5]中分别以字符串形式存储着我需要的时间戳。
使用float(paraList[3])将字符串转化为浮点数。
(3)将日志图形化。
matplotlib是python的一个绘图库。我打算用它来将日志图形化。
matplotlib学习资料。
matplotlib的下载与安装:
http://yexin218.iteye.com/blog/645894
http://blog.csdn.Net/sharkw/article/details/1924949
对matplotlib的宏观介绍:
http://apps.hi..com/share/detail/21928578
对matplotlib具体使用的详细介绍:
http://blog.sina.com.cn/s/blog_4b5039210100ie6a.html
在matplotlib中设置线条的颜色和形状:
http://blog.csdn.net/kkxgx/article/details/python
如果想对matplotlib有一个全面的了解,就需要阅读教程《Matplotlib for Python developers》,教程下载地址:
http://download.csdn.net/detail/nmgfrank/4006691
使用实例
import matplotlib.pyplot as plt
listX = [] #保存X轴数据
listY = [] #保存Y轴数据
listY1 = [] #保存Y轴数据
file = file("../log.txt","r")#打开日志文件
while True:
line = file.readline()#读取一行日志
if len(line) == 0:#如果到达日志末尾,退出
break
paraList = line.split()
print paraList[2]
print paraList[3]
print paraList[4]
print paraList[5]
if paraList[2] == "Client0:": #在坐标图中添加两个点,它们的X轴数值是相同的
listX.append(float(paraList[3]))
listY.append(float(paraList[5]) - float(paraList[3]))
listY1.append(float(paraList[4]) - float(paraList[3]))
file.close()
plt.plot(listX,listY,'bo-',listX,listY1,'ro')#画图
plt.title('tile')#设置所绘图像的标题
plt.xlabel('time in sec')#设置x轴名称
plt.ylabel('delays in ms'')#设置y轴名称
plt.show()
㈡ Python 日志按时间切分问题!
提供个思路,
win下和linux下的换行符不一样,所以处理文本结果就有差异。
㈢ python怎么使用切割获取网页内容
你可以用用现成的python模板:beautifulsoup。 或者最起码你得了解Python的正则,然后自己去用正则解析网页。
㈣ 日志文件太大,python怎么分割文件,多线程操作
python的多线程为伪多线程,多线程并不能提高文件IO的速度,在读取文件时使用直接读取 for line in open('文件名', 'r') 效率最高,因为此方式为直接读取,不像其它方式要把文件全部加载到内存再读取,所以效率最高。分割时文件时,提前计算好行数,把读取的每固定数量的行数存入新文件,直接读取完成,最后删除旧文件,即可实现文件分割。
示意代码:
line_count=0
index=0
fw=open('part'+str(index)+'.log','w')
forlineinopen('filename.log','r'):
fw.write(line)
line_count+=1
#假设每10000行写一个文件
ifline_count>10000:
fw.close()
index+=1
fw=open('part'+str(index)+'.log','w')
fw.close()
㈤ 如何用python分析网站日志
#coding:utf-8
#file: FileSplit.py
import os,os.path,time
def FileSplit(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
number = 100000 #每个小文件中保存100000条数据
dataLine = sFile.readline()
tempData = [] #缓存列表
fileNum = 1
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
for row in range(number):
tempData.append(dataLine) #将一行数据添加到列表中
dataLine = sFile.readline()
if not dataLine :
break
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tempData) #将列表保存到文件中
tFile.close()
tempData = [] #清空缓存列表
print(tFilename + " 创建于: " + str(time.ctime()))
fileNum += 1 #文件编号
sFile.close()
if __name__ == "__main__" :
FileSplit("access.log","access")
#coding:utf-8
#file: Map.py
import os,os.path,re
def Map(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
dataLine = sFile.readline()
tempData = {} #缓存列表
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
p_re = re.compile(r'(GET|POST)\s(.*?)\sHTTP/1.[01]',re.IGNORECASE) #用正则表达式解析数据
match = p_re.findall(dataLine)
if match:
visitUrl = match[0][1]
if visitUrl in tempData:
tempData[visitUrl] += 1
else:
tempData[visitUrl] = 1
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Map("access\\access.log1.txt","access")
Map("access\\access.log2.txt","access")
Map("access\\access.log3.txt","access")
#coding:utf-8
#file: Rece.py
import os,os.path,re
def Rece(sourceFolder, targetFile):
tempData = {} #缓存列表
p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正则表达式解析数据
for root,dirs,files in os.walk(sourceFolder):
for fil in files:
if fil.endswith('_map.txt'): #是rece文件
sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')
dataLine = sFile.readline()
while dataLine: #有数据
subdata = p_re.findall(dataLine) #用空格分割数据
#print(subdata[0][0]," ",subdata[0][1])
if subdata[0][0] in tempData:
tempData[subdata[0][0]] += int(subdata[0][1])
else:
tempData[subdata[0][0]] = int(subdata[0][1])
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Rece("access","access")
㈥ 求助:python 处理日志,用什么模块比较好
首先切割数据到小文件:
#coding:utf-8
#file: FileSplit.py
import os,os.path,time
def FileSplit(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
number = 100000 #每个小文件中保存100000条数据
dataLine = sFile.readline()
tempData = [] #缓存列表
fileNum = 1
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
for row in range(number):
tempData.append(dataLine) #将一行数据添加到列表中
dataLine = sFile.readline()
if not dataLine :
break
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tempData) #将列表保存到文件中
tFile.close()
tempData = [] #清空缓存列表
print(tFilename + " 创建于: " + str(time.ctime()))
fileNum += 1 #文件编号
sFile.close()
if __name__ == "__main__" :
FileSplit("access.log","access")
2. 对小文件分类汇总
#coding:utf-8
#file: Map.py
import os,os.path,re
def Map(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
dataLine = sFile.readline()
tempData = {} #缓存列表
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
p_re = re.compile(r'(GET|POST)\s(.*?)\sHTTP/1.[01]',re.IGNORECASE) #用正则表达式解析数据
match = p_re.findall(dataLine)
if match:
visitUrl = match[0][1]
if visitUrl in tempData:
tempData[visitUrl] += 1
else:
tempData[visitUrl] = 1
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Map("access\\access.log1.txt","access")
Map("access\\access.log2.txt","access")
Map("access\\access.log3.txt","access")
最后全部分类汇总得到一个文件:
#coding:utf-8
#file: Rece.py
import os,os.path,re
def Rece(sourceFolder, targetFile):
tempData = {} #缓存列表
p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正则表达式解析数据
for root,dirs,files in os.walk(sourceFolder):
for fil in files:
if fil.endswith('_map.txt'): #是rece文件
sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')
dataLine = sFile.readline()
while dataLine: #有数据
subdata = p_re.findall(dataLine) #用空格分割数据
#print(subdata[0][0]," ",subdata[0][1])
if subdata[0][0] in tempData:
tempData[subdata[0][0]] += int(subdata[0][1])
else:
tempData[subdata[0][0]] = int(subdata[0][1])
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Rece("access","access")
㈦ Python中的logger和handler到底是个什么鬼
最近的任务经常涉及到日志的记录,特意去又学了一遍logging的记录方法。跟java一样,python的日志记录也是比较繁琐的一件事,在写一条记录之前,要写好多东西。典型的日志记录的步骤是这样的:
创建logger
创建handler
定义formatter
给handler添加formatter
给logger添加handler
写成代码差不多就是酱婶的(这个是照别的网页抄的,参考附注):
1 import logging
2
3 # 1、创建一个logger
4 logger = logging.getLogger('mylogger')
5 logger.setLevel(logging.DEBUG)
6
7 # 2、创建一个handler,用于写入日志文件
8 fh = logging.FileHandler('test.log')
9 fh.setLevel(logging.DEBUG)
10
11 # 再创建一个handler,用于输出到控制台
12 ch = logging.StreamHandler()
13 ch.setLevel(logging.DEBUG)
14
15 # 3、定义handler的输出格式(formatter)
16 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
17
18 # 4、给handler添加formatter
19 fh.setFormatter(formatter)
20 ch.setFormatter(formatter)
21
22 # 5、给logger添加handler
23 logger.addHandler(fh)
24 logger.addHandler(ch)
之后才可以正式的开始记录日志。Java里面的java.util.Logging类差不多也是这样,代码还要更复杂一点。Golang的日志相对
写法简单一些,不过没有什么格式,系统记录一条时间,内容格式完全自己手画。第三方的日志库倒是没有接触过,像Java的Log4j,Golang的
log4go和seelog等等,不知道用起来会不会简单一点。我一直都记不住这些,因为不太理解logger和handler为什么要这样写。一直到这
次任务中出现的在我看来相当“诡异”的bug,才深入理解了一下。
我的任务是这样的,要做一个日志切割的工具,按天将日志分割开,即每天0点产生一个新日志,将旧日志改名。并且,将超过3个月的日志删除掉,以保证磁盘空间不会被log占满。程序要求可以切割多个目录中的不同日志,具体路径由json中配置。
这里用到了logging.handlers类中的TimedRotatingFileHandler方法,用以获得一个handler。大概的写法为:
1 logger = logging.getLogger() #获得logger
2 handler = logging.handlers.TimedRotatingFileHandler(logfile, 'S', 1, 0) #切割日志
3 handler.suffix = '%Y%m%d' #切割后的日志设置后缀
4 logger.addHandler(handler) #把logger添加上handler
5 logger.fatal(datetime.datetime.now().strftime('%Y-%m-%d')) #在新日志中写上当天的日期
这里我没有设置level和formatter。因为只是分割,对新日志没有什么影响。TimedRotatingFileHandler函数的方
法见附注,或查看python的源码,这个函数是python写的,可以找到定义。这里我使用的是每秒生成一个新的日志文件,之后用Crontab在每天
0点调度,然后用for循环处理json中的每一个日志文件。
但是奇怪的是,每次运行程序,第一个切割的日志生成一个分割后的文件,而后面的都生成两个新日志。百思不得其解。后检查代码觉得,可能是程序中设置
的时间太短了,每秒生成一个文件,有可能一秒钟处理不完,就生成了两个。虽然这个说法没有什么科学根据,但是还是把
TimedRotatingFileHandler中的第三个参数改成了60,即每60秒生成一个文件。完成,静静的等待crontab到时间。
㈧ python处理日志的包有哪些
#coding:utf-8
#file: FileSplit.py
import os,os.path,time
def FileSplit(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
number = 100000 #每个小文件中保存100000条数据
dataLine = sFile.readline()
tempData = [] #缓存列表
fileNum = 1
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
for row in range(number):
tempData.append(dataLine) #将一行数据添加到列表中
dataLine = sFile.readline()
if not dataLine :
break
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tempData) #将列表保存到文件中
tFile.close()
tempData = [] #清空缓存列表
print(tFilename + " 创建于: " + str(time.ctime()))
fileNum += 1 #文件编号
sFile.close()
if __name__ == "__main__" :
FileSplit("access.log","access")
#coding:utf-8
#file: Map.py
import os,os.path,re
def Map(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
dataLine = sFile.readline()
tempData = {} #缓存列表
if not os.path.isdir(targetFolder): #如果目标目录不存在,则创建
os.mkdir(targetFolder)
while dataLine: #有数据
p_re = re.compile(r'(GET|POST)\s(.*?)\sHTTP/1.[01]',re.IGNORECASE) #用正则表达式解析数据
match = p_re.findall(dataLine)
if match:
visitUrl = match[0][1]
if visitUrl in tempData:
tempData[visitUrl] += 1
else:
tempData[visitUrl] = 1
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Map("access\\access.log1.txt","access")
Map("access\\access.log2.txt","access")
Map("access\\access.log3.txt","access")
#coding:utf-8
#file: Rece.py
import os,os.path,re
def Rece(sourceFolder, targetFile):
tempData = {} #缓存列表
p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正则表达式解析数据
for root,dirs,files in os.walk(sourceFolder):
for fil in files:
if fil.endswith('_map.txt'): #是rece文件
sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')
dataLine = sFile.readline()
while dataLine: #有数据
subdata = p_re.findall(dataLine) #用空格分割数据
#print(subdata[0][0]," ",subdata[0][1])
if subdata[0][0] in tempData:
tempData[subdata[0][0]] += int(subdata[0][1])
else:
tempData[subdata[0][0]] = int(subdata[0][1])
dataLine = sFile.readline() #读入下一行数据
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")
tFile = open(tFilename, 'a+') #创建小文件
tFile.writelines(tList) #将列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Rece("access","access")
㈨ python 读取日志文件
#-*-coding:utf-8-*-
withopen('log.txt','r')asf:
foriinf:
ifdt.strftime(dt.now(),'%Y-%m-%d')ini:
#判断是否当天时间
if'ERROR'iniand'atcom.mytijian'ini:
#判断此行中是否含有'ERROR'及'atcom.mytijian'
if((dt.now()-dt.strptime(i.split(',')[0],'%Y-%m-%d%H:%M:%S')).seconds)<45*60:
#判断时间是为当前45分钟内
printi
㈩ 切割后的nginx日志怎么读取 python
兄弟,能说明白点不? linux下日志文件 vi、cat都可以读取啊,用python 直接open就行。