2022年 11月 16日

python分析日志

需求1:分析日志每天的的访问量

日志格式:
95.143.192.110 – – [15/Dec/2019:10:22:00 +0800] “GET /post/nihao/ HTTP/1.1” 304 0 “https://www.ssgeek.com/” “Mozilla/5.0 “

dict = {}
with open('log2.txt','r') as f:
  for line in f.readlines():
    time = line.split()[3][1:12]
    if time not in list(dict.keys()):
      dict[time] = 1
    else:
      dict[time] += 1


for key,values in dict.items():
  print("{} : {}".format(key,values))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

需求2:分析指定用户每分钟内访问量

日志格式:
23:56:17 Amy

dest_time="12:10"
dest_name="Amy"
n=0
with open('log.txt','r') as f:
  for line in f.readlines():
    if len(line) >= 10:
      time = line.split()[0]
      name = line.split()[1]
      #print("{},{}".format(name,name.find("ac")))      
      if dest_time == time[0:5] and name == dest_name:
        n = n + 1
print(" jack vist time in one minute  is : {} ".format(n))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12