3

Webサーバーのログアナライザー(Urchinなど)は、多くの場合、多数の「セッション」を表示します。セッションは、限られた継続的な時間セグメント内で個人が行った一連のページ訪問/クリックとして定義されます。IPアドレス、および多くの場合、ユーザーエージェントやOSなどの補足情報、および15分や30分などのセッションタイムアウトしきい値を使用して、これらのセグメントを識別しようとします。

特定のWebサイトおよびアプリケーションでは、ユーザーはCookieを使用してログインおよび/または追跡できます。これは、サーバーがセッションの開始時刻を正確に知ることができることを意味します。私はそれについて話しているのではなく、Webサーバーがセッションを追跡しないときにヒューリスティックにセッションを推測すること(「セッションの再構築」)について話している。

たとえばPythonでコードを記述して、上記の基準に基づいてセッションを再構築しようとすることはできますが、車輪の再発明はしたくありません。私は約400K行のサイズのログファイルを見ているので、スケーラブルなアルゴリズムを使用するように注意する必要があります。

ここでの私の目標は、ログファイルから一意のIPアドレスのリストを抽出し、IPアドレスごとに、そのログから推測されるセッションの数を取得することです。絶対的な精度と正確さは必要ありません...かなり良い見積もりは大丈夫です。

この説明に基づく:

次の2つの条件が有効な場合、新しいリクエストが既存のセッションに追加されます。


  • IPアドレスとユーザーエージェントは、セッションにすでに挿入されているリクエストと同じです。
  • リクエストは、最後に挿入されたリクエストから15分以内に実行されます。

理論的には、値がペアである辞書(ユーザーエージェントによってキー設定)の辞書(IPによってキー設定)を構築するPythonプログラムを作成するのは簡単です:(セッション数、最新セッションの最新の要求)。

ただし、パフォーマンスの調整に多くの時間を費やすリスクがある可能性があるため、既存の実装が利用可能な場合はそれを使用することをお勧めします。

参考までに、誰かがサンプル入力を求めないように、ログファイル(サニタイズ済み)の行を次に示します。

#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status 
2010-09-21 23:59:59 215.51.1.119 GET /graphics/foo.gif - 80 - 128.123.114.141 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.9.2)+Gecko/20100115+Firefox/3.6+(.NET+CLR+3.5.30729) http://www.mysite.org/blarg.htm 200 0 0
4

1 に答える 1

2

OK、他に答えがない場合は、これが私のPython実装です。私はPythonの専門家ではありません。改善のための提案を歓迎します。

#!/usr/bin/env python

"""Reconstruct sessions: Take a space-delimited web server access log
including IP addresses, timestamps, and User Agent,
and output a list of the IPs, and the number of inferred sessions for each."""

## Input looks like:
# Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status
# 2010-09-21 23:59:59 172.21.1.119 GET /graphics/foo.gif - 80 - 128.123.114.141 Mozilla/5.0+(Windows;+U;+Windows+NT+5.1;+en-US;+rv:1.9.2)+Gecko/20100115+Firefox/3.6+(.NET+CLR+3.5.30729) http://www.site.org//baz.htm 200 0 0

import datetime
import operator

infileName = "ex100922.log"
outfileName = "visitor-ips.csv"

ipDict = {}

def inputRecords():
    infile = open(infileName, "r")

    recordsRead = 0
    progressThreshold = 100
    sessionTimeout = datetime.timedelta(minutes=30)

    for line in infile:
        if (line[0] == '#'):
            continue
        else:
            recordsRead += 1

            fields = line.split()
            # print "line of %d records: %s\n" % (len(fields), line)
            if (recordsRead >= progressThreshold):
                print "Read %d records" % recordsRead
                progressThreshold *= 2

            # http://www.dblab.ntua.gr/persdl2007/papers/72.pdf
            #   "a new request is put in an existing session if two conditions are valid:
            #    * the IP address and the user-agent are the same of the requests already
            #      inserted in the session,
            #    * the request is done less than fifteen minutes after the last request inserted."

            theDate, theTime = fields[0], fields[1]
            newRequestTime = datetime.datetime.strptime(theDate + " " + theTime, "%Y-%m-%d %H:%M:%S")

            ipAddr, userAgent = fields[8], fields[9]

            if ipAddr not in ipDict:
                ipDict[ipAddr] = {userAgent: [1, newRequestTime]}
            else:
                if userAgent not in ipDict[ipAddr]:
                    ipDict[ipAddr][userAgent] = [1, newRequestTime]
                else:
                    ipdipaua = ipDict[ipAddr][userAgent]
                    if newRequestTime - ipdipaua[1] >= sessionTimeout:
                        ipdipaua[0] += 1
                    ipdipaua[1] = newRequestTime
    infile.close()
    return recordsRead

def outputSessions():
    outfile = open(outfileName, "w")
    outfile.write("#Fields: IPAddr Sessions\n")
    recordsWritten = len(ipDict)

    # ipDict[ip] is { userAgent1: [numSessions, lastTimeStamp], ... }
    for ip, val in ipDict.iteritems():
        # TODO: sum over on all keys' values  [(v, k) for (k, v) in d.iteritems()].
        totalSessions = reduce(operator.add, [v2[0] for v2 in val.itervalues()])
        outfile.write("%s\t%d\n" % (ip, totalSessions))

    outfile.close()
    return recordsWritten

recordsRead = inputRecords()

recordsWritten = outputSessions()

print "Finished session reconstruction: read %d records, wrote %d\n" % (recordsRead, recordsWritten)

更新:これは、342Kレコードの入力と処理、および21Kレコードの書き込みに39秒かかりました。それは私の目的には十分な速度です。どうやらその時間の3/4が費やされましたstrptime()

于 2010-09-23T08:59:24.090 に答える