眉標=IIS
副標=為IIS的健康把脈
大標=IIS Log管理與分析實務
作者=文/李明儒

=======程式=======

程式1 建立儲存Log記錄的資料表
CREATE TABLE [dbo].[IISLog] (
	[date] char(10) NULL,
	[time] char(8) NULL ,
	[c-ip] varchar(15) NULL ,
 	[cs-username] varchar(50) NULL,
	[s-ip] varchar(15) NULL,
	[s-port] int NULL,
	[cs-method] varchar(50) NULL ,
	[cs-uri-stem] varchar(255) NULL ,
	[cs-uri-query] varchar(2048) NULL ,
	[sc-status] int NULL ,
	[sc-bytes] int NULL ,
	[cs-bytes] int NULL,
	[time-taken] int NULL ,
	[cs(User-Agent)] varchar(255) NULL
	)

=======程式=======

=======程式=======

程式2 處理IIS Log檔Header列及時區調整的程式
static void prepLog(string fileName)
{
   DateTime st = DateTime.Now;
   Console.Write(fileName + "處理中...");
   if (!File.Exists(fileName))
   {
      Console.WriteLine(fileName + "不存在!");
      return;
   }
   StreamReader sr = new StreamReader(
    fileName, Encoding.GetEncoding("big5"));
   StreamWriter sw = new StreamWriter(
       fileName+".txt",false,
       Encoding.GetEncoding("big5"));
   string nextDate = "", curDate = "", newLine = "";
   while (sr.Peek() > -1)
   {
      string line = sr.ReadLine();
      if (!line.StartsWith("#"))
      {
         int h = int.Parse(line.Substring(11, 2));
         if (h >= 16) //Next Day
         {
            if (nextDate.Length == 0)
nextDate = DateTime.ParseExact(line.Substring(0,10),
"yyyy-MM-dd", null).AddDays(1).ToString("yyyy-MM-dd");
        h = h - 16;
newLine = nextDate + " " + h.ToString("00") +
line.Substring(13);
         }
         else
         {
            if (curDate.Length == 0) 
               curDate = line.Substring(0, 10);
         h = h + 8;
newLine = curDate + " " + h.ToString("00") +
line.Substring(13);
         }
         sw.WriteLine(newLine);
      }
   }
   sw.Close();
   sr.Close();
   TimeSpan duration=DateTime.Now-st;
   Console.WriteLine("耗時{0:#,###}ms",
duration.TotalMilliseconds);
}

static void Main(string[] args)
{
   if (args.Length!=1) 
   {
      Console.WriteLine("Syntax Example:
PrepLogTW ex060101.log or PrepLogTW ex0601*.log");
      return;
   }
   string fileNameArg=args[0];
   if (fileNameArg.IndexOf("*") > -1)
   {
      string path = ".";
      if (fileNameArg.IndexOf("\\") > -1)
      {
path = Path.GetDirectoryName(fileNameArg);
fileNameArg = Path.GetFileName(fileNameArg);
      }
      foreach (string logFile in Directory.GetFiles
(path, fileNameArg))
         prepLog(logFile);
      }
      else
         prepLog(fileNameArg);
}
=======程式=======