利用 C# 去執行 Log Parser

來源:互聯網
上載者:User
通過 .NET Framework 的 COM  interop (COM 互動操作)特性,可以很方便地在 .NET 應用程式中使用 Log Parser,.NET Framework 的 COM  interop 是通過 Runtime Callable Wrappers (RCW) 來實現對 COM 的操作的,RCW 是 .NET 中的一個類。

編譯環境:VS2005 C#

首先在你建立的項目中添加引用:LogParser.dll,那麼出現在你解決方案的引用欄中:MSUtil。你可以在物件瀏覽器中查到此庫的各種類型介面。接下來要在你的cs檔案的開頭,引用你想調用的類型,例如:using LogQuery = MSUtil.LogQueryClassClass;using LogRecordSet = MSUtil.ILogRecordset;using LogRecord = MSUtil.ILogRecord;using W3CLogInputFormat = MSUtil.COMW3CInputContextClassClass;using CSVLogOutputFormat = MSUtil.COMCSVOutputContextClassClass;
舉個執行個體:用 Log Parser 和 C# 打造網站訪問統計分析系統,就是用 C# 調用 Log Parser,利用 Log Parser 去分析 IIS 的記錄檔。我們這裡的記錄檔是 W3C 格式的。

我們建立一個 .cs 檔案,引入:

using LogQuery = Interop.MSUtil.LogQueryClassClass;
using IISInputFormat = Interop.MSUtil.COMIISW3CInputContextClassClass;
using LogRecordSet = Interop.MSUtil.ILogRecordset;

類中關鍵代碼如下:

LogQuery oLogQuery = new LogQuery();
IISInputFormat oIISInputFormat = new IISInputFormat();
string query = @"SELECT COUNT(DISTINCT c-ip) AS hits
                 FROM 'C:\WINDOWS\system32\Logfiles\W3SVC1\ex070820.log'
                 WHERE cs-uri-stem like '%.asp'
                 AND sc-status=200";
LogRecordSet oRecordSet = oLogQuery.Execute(query, oIISInputFormat);
if (!oRecordSet.atEnd())
{
    hits = (int)oRecordSet.getRecord().getValue("hits");
}
oRecordSet.close();

看得出來跟使用資料庫沒有多大區別,查詢語句中 c-ip、cs-uri-stem、sc-status 等都是記錄檔的欄位,直接開啟記錄檔可以找到這些內容。

通過C#與LogParser的結合可以極大限度的發揮LogParsr的功能。讓它不僅僅局限與命令列的輸入。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.