2017-05-08 103 views

回答

1

有什么办法可以保存到SQL数据库吗?

Azure Web App目前不提供此功能。您可以在以下站点发布功能请求。

How can we improve Azure Web Apps?

Web服务器日志使用W3C日志记录格式。如果我们选择将此日志保存到存储的选项。登录Azure的Blob服务的文件名格式都是这样的,

[ServerLogContainerName]>[WebAppName]>[Year]>[Month]>[Day]>[Hour]>[LogFileName].log 

Azure的Web应用程序将保存时间纪录群组。我们可以创建WebJob并使用TimeTrigger读取日志,解析日志文件并将数据每小时保存到SQL Server。以下代码供您参考。

// Runs immediately on startup, then every two hour 
public static void SaveLogsToSQLJob(
    [TimerTrigger("0 0 * * * *", RunOnStartup = true)] TimerInfo timerInfo) 
{ 
    // Retrieve storage account from connection string. 
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connection_string"); 

    // Create the blob client. 
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); 

    // Retrieve a reference to a container. 
    CloudBlobContainer container = blobClient.GetContainerReference("ServerLogContainerName"); 

    var blobs = container.GetDirectoryReference("YourWebAppName").GetDirectoryReference(DateTime.Now.Year.ToString()) 
     .GetDirectoryReference(DateTime.Now.Month.ToString()) 
     .GetDirectoryReference((DateTime.Now.Hour == 0 ? DateTime.Now.Day - 1 : DateTime.Now.Day).ToString()) 
     .GetDirectoryReference((DateTime.Now.Hour == 0 ? 23 : DateTime.Now.Hour - 1).ToString()).ListBlobs(); 

    foreach (CloudBlockBlob blob in blobs) 
    { 
     using (Stream stream = blob.OpenRead()) 
     { 
      using (StreamReader sr = new StreamReader(stream)) 
      { 
       string line = null; 
       while ((line = sr.ReadLine()) != null) 
       { 
        if (!line.StartsWith("#")) 
        { 
         string[] fields = line.Split(' '); 
         //Save these fields to database 
        } 
       } 
      } 
     } 

    } 
} 

根据日志文件,我们需要在SQL表中创建以下16列。

date time s-sitename cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status