C#.net读取不同格式的IIS日志文件

来源:互联网 发布:caffe windows vs2015 编辑:程序博客网 时间:2024/06/10 06:28

如果有研究过IIS日志文件的朋友们,可能都知道,每个服务器,甚至每个域名的IIS日志格式可能都不同,这样刚开始接触的朋友就觉得很烦,特别是当我们要自己写IIS日志分析软件的时候更烦恼,因为如果一不小心设置错了,针对固定格式而写的读取文件就不能用了。特别是修改日志设置的时候,由于当日的文件中会存在两个不同的数据格式,读取非常麻烦,下面我把我解决这个烦恼问题的解决方案公开,希望对大家有帮助。

文件格式可能如下: 

#Fields: date time cs-method cs-uri-stem cs-uri-query cs-username c-ip cs-version cs(User-Agent) cs(Referer) sc-status sc-bytes 
2007-11-01 00:00:00 GET /book/product.aspx bookid=B10027740 - 66.249.73.134 HTTP/1.1 -  - 200 26124
#Fields: date time cs-uri-stem cs-uri-query cs-username c-ip cs-version cs(User-Agent) cs(Referer) sc-status 
2007-11-01 00:00:00  /book/product.aspx bookid=B10027740 - 66.249.73.134 HTTP/1.1 - - 200

#Fields代表格式符,对应到下一个#Fields之前全部使用这种格式读取

也就是说 第2行使用第1行的格式,第4行使用第2行的格式,我们尝试读取第四行中的/book/product.aspx,注意1、3行定义了cs-uri-stem为这个数据的格式 ,比较1、3行,1行比3行多了cs-method 也就是Form中对应的GET/POST

由于顺序可能不同,出现的先后也可能不同,所以建立一个索引类,对应信息类的字段。代码如下

/// <summary>
    
/// 信息类
    
/// </summary>

    public class LogInfo
    
{
        
private string _url;

        
public string Url
        
{
            
get return _url; }
            
set { _url = value; }
        }

    }


    
/// <summary>
    
/// 缩引类
    
/// </summary>

    public static class ReadIndex
    
{
        
private static int _urlIndex = -1;

        
public static int UrlIndex
        
{
            
get return _urlIndex; }
            
set { _urlIndex = value; }
        }


        
public static void Reset()
        
{
            _urlIndex 
= -1;
        }

    }

UrlIndex对应的就是Url的索引ID号

使用索引读取数据的代码如下

 StreamReader Reader = new StreamReader();
            
while (Reader.Peek() != -1)
            
{
                
string tmp = Reader.ReadLine(); 
                 
string[] strArray = tmp.Split(' ');
                
if (strArray[0]== "#Fields")        //是否需要重新设置读取格式
                {
                    ReadIndex.Reset();
                   
                    
for (int iCount = 0; iCount < strArray.Length; iCount++)
                    
{
                        
if (strArray[iCount] == "cs-uri-stem") ReadIndex.UrlIndex = iCount + 1;         //得到索引ID,为什么加1 自己想想!!
                    }

                    
continue;
                }

                LogInfo log 
= new LogInfo();
                log.Url 
= strArray[ReadIndex.UrlIndex]; //根据索引ID得到数据
            }

就这样,我们利用一个索引类的帮助,解决了对不同格式IIS日志的读取,希望本篇文章对自己想做网站访问分析的朋友有所帮助

原创粉丝点击