Blog Stats
  • Posts - 79
  • Articles - 1
  • Comments - 29
  • Trackbacks - 191

 

Log Parser v2.1

Using Log Parser to Read Log Files
Log Parser COM Architecture
What to do with Log Parser?

Log Parser is a tool available from Microsoft that allows you to run SQL queries against log files and send the information to a SQL Database or other file formats. In this article I describe the capabilities of Log Parser and how you can use it as a set of COM interfaces from your application.

Using Log Parser to Read Log Files

Microsoft has a slick tool tucked away in the IIS 6.0 Resource Kit called the Log Parser 2.1. An earlier 2.0 version of the tool is also available for Windows 2000. Mike Gunderloy has a nice FAQ on how to use the Log Parser tool from the command line and an Unofficial Support Site.

Log Parser is a very slick way to extract and analyze the data in your IIS, NCSA and W3C Log files as well as the Windows Event Log, CSV files and file information from a directory. You can write queries on the data directly from the files using SQL.

Here’s a few example queries from the documentation.

The first runs against a W3C Extended Log File:

SELECT time, REVERSEDNS(c-ip), cs-uri-stem, cs-uri-query, sc-status FROM ex*.log TO MyTable WHERE (sc-status > 200 AND sc-status <> 404) OR time-taken > 30 ORDER BY time

A query against the Windows Event Log:

SELECT Message, COUNT(*) AS TotalCount FROM Application GROUP BY Message HAVING TotalCount > 2

A query that retrieves a list of large files on Drive D:

SELECT Path, QUANTIZE(Size, 1000000) AS Megs FROM D:\*.* WHERE Megs > 0 ORDER BY Megs DESC

Dan Bright has a write-up that lists the various input formats available for Log Parser.

Log Parser also has output targets. You can use the utility to query from, for example, the IIS log files and insert the results into a SQL Database. You can also accomplish things like splitting your log files into multiple files based on a field.

This query from the documentation will split the log files. One file will be created for each IP address occurring in the logs:

SELECT c-ip, date, time, cs-uri-stem, cs-uri-query FROM ex*.log TO exclient*.log

You can output to a SQL table, CSV files, XML files or text documents based on a template. There are a few others as well.

Log Parser COM Architecture

One of the cooler things about the Log Parser is that it is exposed via COM interfaces so that you can script the tool or call it from your application. I found this very useful a few weeks ago to create a batch process that downloads log files and imports them into a database, doing a little work on the data as it gets moved around.

I was able to reference the Log Parser type library in my .NET project and utilize it though the provided interfaces. Once you get use to creating SQL queries on your log data using the command line interface, using the COM interfaces is fairly easy:

  1. Set up a reference to the Log Parser component library in your VS.NET project.
  2. Create an Input Context compatible with the format of your input files.
  3. If you want the data outputted to another format, create an Output Context.
  4. Use the LogQueryClass interface to execute a query using the Input context and the optional Output Context.

To reference the Log Parser, look for the “MS Utility 1.0 Type Library – LogParser Interfaces collection” COM component in the Add Reference dialog.

Pick an Input Context that is appropriate for the format of the log files you want to query. My log files were in the IIS W3C format, so I used the COMIISW3CInputContextClass interface.

It’s useful to note that the Log Parser has support for an IIS format, W3C format and an IIS W3C format. There are differences between each. As far as I can tell, the difference between W3C and IIS W3C formats in Log Parser is the data types. The W3C format uses the string data type for each field whereas the IIS W3C format maps fields to appropriate integer, string and timestamp data types.

Create an instance of the Input Context class:

MSUtil.COMIISW3CInputContextClass inputContext =
         new MSUtil.COMIISW3CInputContextClassClass();

Choose the Output Context according to where you want to send the results of the query. I used the SQL Output Target. The SQL Output Target will send the results to a SQL table. If the table does not exist, this output target can create the table for you with the fields used in the query.

Create an instance of the Output Context class and set properties for the context:

MSUtil.COMSQLOutputContextClass outputContext = 
        new MSUtil.COMSQLOutputContextClassClass();
outputContext.clearTable = false;
outputContext.createTable = true;
outputContext.database = "DBNAME";
outputContext.server = "SERVERNAME";
outputContext.username = "USERNAME";
outputContext.password = "PASSWORD";
outputContext.driver = "SQL Server";

Create a new instance of the LogQueryClass:

MSUtil.LogQueryClass logQuery = new MSUtil.LogQueryClassClass();

Now execute a batch query against the log files and output the results to the database:

String query = 
         "SELECT TO_TIMESTAMP(date, time) as dateTime, c-ip, cs-username, " + 
         "s-sitename, s-computername, s-ip, s-port, cs-method, cs-uri-stem, " +
         "cs-uri-query, sc-status, sc-win32-status, sc-bytes, cs-bytes, " + 
         "time-taken, cs-version, cs-host, cs(User-Agent), cs(Cookie), " +
         "cs(Referer) FROM C:\\Log\u005cu0020Files\\ex*.log TO Hits";
logQuery.ExecuteBatch(query, outputContext, inputContext);

UPDATE: The above line should read:

logQuery.ExecuteBatch(query, inputContext, outputContext);

If you don’t want to send the results to an output context, you can call the Execute method. This returns an ILogRecordset that you can iterate through and work with each result row.

What to do with Log Parser?

So what other things might you do with Log Parser? I can think of a few, but you can probably think of more.

  • Wrap the Log Parser in a DataReader class to easily read Event Logs or CSV files into a DataGrid.
  • Build a monitor application that queries the Event Log for critical events.
  • Build a query to summarize log files into an XML Document for display as a report on your Intranet.

Updates
01/13/2003 Roy Osherove says that the next version of LogParser will allow parsing of multiple line log files.
01/13/2003 Steve Makofsky will use LogParser to extract referrers for his blog. Good idea.
01/15/2003 Steve Makofsky shows another method for invoking the LogParser COM library.



		
		

Feedback

# re: Log Parser v2.1

Gravatar I have been looking for some VB.NET code to use with Log Parser.

1/23/2004 9:34 AM | Jim Ley

# re: Log Parser v2.1

Gravatar Dim inputContext As MSUtil.COMIISW3CInputContextClass
inputContext = New MSUtil.COMIISW3CInputContextClassClass()

Dim outputContext As MSUtil.COMSQLOutputContextClass
outputContext = New MSUtil.COMSQLOutputContextClassClass()

outputContext.clearTable = False
outputContext.createTable = True
outputContext.database = "DBNAME"
outputContext.server = "SERVERNAME"
outputContext.username = "USERNAME"
outputContext.password = "PASSWORD"
outputContext.driver = "SQL Server"

Dim query As String
query = "SELECT TO_TIMESTAMP(date, time) as dateTime, c-ip, cs-username, " & _
"s-sitename, s-computername, s-ip, s-port, cs-method, cs-uri-stem, " & _
"cs-uri-query, sc-status, sc-win32-status, sc-bytes, cs-bytes, " & _
"time-taken, cs-version, cs-host, cs(User-Agent), cs(Cookie), " & _
"cs(Referer) FROM C:\\Log\u005cu0020Files\\ex*.log TO Hits"
logQuery.ExecuteBatch(query, outputContext, inputContext)
1/23/2004 2:48 PM | Drew Robbins

# re: Log Parser v2.0

Gravatar Am having difficulty getting this to work in C#. Tried the two methods referred to in this blog:

MSUtil.COMEventLogInputContextClass ctxInput = new MSUtil.COMEventLogInputContextClassClass();

and

Type comLogQueryType = Type.GetTypeFromProgID("MSUtil.LogQuery", true);
object comLogQueryObject = Activator.CreateInstance(comLogQueryType);

Stepping through with the debugger, it comes to the line to create (input context / log query in examples above) and just sits there when you execute the line. Control doesn't come back to the debugger and there is no error.

I am using Log Parser V2.0.

Any ideas why it can't create MSUtil objects ?

Thanks 3/30/2004 4:42 PM | Rog

# re: Log Parser v2.1

Gravatar Very nice, much better than trying to work with the MSWC.IISLog object. Cheers. 4/17/2004 7:04 AM | Kevin Brown

# re: Log Parser v2.1

Gravatar When I use the code above I get the error:
CLogQueryClass: Error 80004002 : The specified Input Object does not implement an IComInputContext interface. Any ideas on why I would get this? I can't find any real documentation on this. Thanks 4/20/2004 4:57 PM | dustin

# re: Log Parser v2.1

Gravatar Rog, I have not tried using Log Parser v2.0. Dustin, are you using v2.0 or v2.1?
4/20/2004 6:25 PM | Drew Robbins

# re: Log Parser v2.1

Gravatar Referring to dustin's comment, I am having the same problem and I am using v2.1 4/22/2004 9:49 AM | bb

# re: Log Parser v2.1

Gravatar With reference to dustins message, the above Error (CLogQueryClass: Error 80004002 ) can be resolved by correcting the following code:

logQuery.ExecuteBatch(query, outputContext, inputContext);

to read:

logQuery.ExecuteBatch(query, inputContext, outputContext);

Hope this helps
Rekkie 5/7/2004 2:20 AM | Rekkie

# re: Log Parser v2.1

Gravatar Drewby,

Awesome, I've been playing with this for a few hours and got the command line version of MSUtil to work but couldn't figure out how to adjust the IIS log file name to be yesterday's date. I tried the suggestion in the FAQ but couldn't get it to work in the context of the SQLQuery.

I struggled with the com interface but couldn't get it to work. Your snippet worked perfectly! I just loaded it in and commented your comments, changed the output context values and wham!


Thanks

Lou 5/18/2004 6:06 AM | Lou Gallo

# getting the result in a string

Gravatar hi all,

Does someone know how to get the result of a query in a string but not in a file?

I need that because I want to make a real time application with log parser.I make the query with log parser and I refresh the operation every 5s.So to avoid opening and accessing file i need to get the query's result directly in a string or in a stream.

If someone has a solution, it would be very nice.

thanks.
Andriana 5/25/2004 6:02 AM | andriana

# RE: getting the result in a string

Gravatar Hi Adrina, about you question you need to use the DLL of LogParser, (MS Utility 1.0 Type Library like tell you this page avobe),to Make an object to execute the Query you want. The result is received in a Record Set and you can read the rows through it.

//example C#
//object MSUTIL (object logparser)
MSUtil.LogQueryClassClass Log = new MSUtil.LogQueryClassClass();
//object to configure the format of the sourse file log, this case is a CSV format.
MSUtil.COMCSVInputContextClass InputCSV = new MSUtil.COMCSVInputContextClassClass();

//record Set
MSUtil.ILogRecordset Record = null;
//to save the each row of the Record set
MSUtil.ILogRecord row = null;

string QUERY1 = "Select col1, col2, col3 from c:\file.log";
Record = Log.Execute(QUERY1,InputCSV);

while (!Record.atEnd() )
{
//print
string RowColumns = row.getValue(0) + row.getValue(1) + row.getValue(2);
//print the row
Console.WriteLine(RowColumns);
}
8/4/2004 1:43 PM | Asdrubal

# re: Log Parser v2.1

Gravatar What is the syntax for LastAccessTime using -i FS.

I'm trying to list files with LastAccessTime of before 01/01/2004.

Thanks

MR 9/7/2004 6:10 AM | mr

# re: Log Parser v2.1

Gravatar Bloody excellent info. Did just the trick as I was a little stuck with the Output context for SQL 9/7/2004 9:13 PM | Geno

# re: Log Parser v2.1

Gravatar To retrieve files whose LastAccessTime is <= 01/01/2004:

SELECT * FROM C:\*.* WHERE LastAccessTime <= TIMESTAMP('01/01/2004', 'MM/dd/yyyy')
9/14/2004 11:18 AM | Neurodancer

#  Log Parser v2.1

Gravatar Hi i am using 2.1 version and tring to parseing media log file but i can't able to parse Date and version from media log file can any one how can i do 9/21/2004 8:34 PM | Kunal

# re: Log Parser v2.1

Gravatar Could someone post a complete example of how to call the logparser.dll from asp.net (vb.net)?

I am trying to query and total (sc-bytes) and (cs-bytes) by month/day/year/whatever and display that information as a total on a webpage.

I assume logparser.dll must be in the bin directory.

Any help with this is greatly appreciated, thanking you all in advance. 9/22/2004 1:33 PM | Dave

# re: Log Parser v2.1

Gravatar Anyone have an idea how to use logparser in Delphi?
I'm having difficulty using the logparser.dll in Delphi, coz i didn't find any header files for logparser.dll..

My last chance is using the commandline logparser.exe, run it, change the format into csv, and parse it back..

Anyone have a better idea?

Oh, another question, if i'm using logparser in Windows XP to parse the Eventlog, i receive message such "access is denied" and "eventlog file is corrupted".. Well, I can open the eventlog file with event viewer... can't be corrupted. Is the EventLog format in windows XP is different that NT's ?? 9/22/2004 10:04 PM | Adhitya

# re: Log Parser v2.1

Gravatar my script doesn't error out. it creates an empty table. i can't get the data in. any ideas?

here is the code:

ASP.NET 1.1

Dim lg1 As MSUtil.LogQueryClass = New MSUtil.LogQueryClassClass

Dim s1 As String
s1 = "select * from C:\toJun28.log to testy"

Dim r1 As MSUtil.COMIISNCSAInputContextClass
r1 = New MSUtil.COMIISNCSAInputContextClassClass

Dim r2 As MSUtil.COMSQLOutputContextClass
r2 = New MSUtil.COMSQLOutputContextClassClass

r2.clearTable = True
r2.createTable = True
r2.database = "[db name inserted here]"
r2.server = "[server name inserted here]"
r2.driver = "SQL Server"

Dim r3 As MSUtil.LogQueryClass = New MSUtil.LogQueryClassClass

lg1.ExecuteBatch(s1, r1, r2) 11/8/2004 3:02 PM | haveing trouble with NCSA format

# re: Log Parser v2.1

Gravatar Can I use log parser in my application forloging error information?( create error log file) 11/20/2004 6:18 AM | Arun

# re: Log Parser v2.1

Gravatar hello sir.

i want to read data from log file using C#.net

please provide me solution.

please send ans to this id

shivakumar.sogi@wipro.com 12/8/2004 8:21 AM | shiva

# re: Log Parser v2.1

Gravatar Hi
Can anyone give me the code to use log parser in C++.
Mail me at manishj_78@yahoo.com. 1/12/2005 5:03 PM | Manish

# Log Parser v2.2 (VB.Net)

Gravatar
Example VB.NET version
Ref: http://blogs.msdn.com/mszcool/archive/2004/03/09/86762.aspx

PLEASE SOMEONE SUGGEST HOW I CAN CAST A LOG RECORDSET INTO A ADODB, I'M TRYING TO OPTIMISE IT - TO RETURN A DATASET RATHER THAN ITERATE OVER EACH ITEM! Maybe you can help shiva (l0l)

Function EVT(ByVal file As String) As DataSet

Dim strSql As String = "SELECT * FROM " & file 'C:\1A_Projects\VB\EventLogToText\application.evt

'Dim strSql2 As String = "SELECT time, cs-method, c-ip " & "FROM C:\windows\system32\logfiles\W3SVC1\ex040304.log"

'Create the log query class and execute the query
Dim log As MSUtil.ILogQuery = New MSUtil.LogQueryClassClass()
Try
Dim recSet As MSUtil.ILogRecordset = log.Execute(strSql)

' Dim DA As OleDbDataAdapter = New OleDbDataAdapter()
' Dim DS As DataSet = New DataSet()
' DA.Fill(DS, recSet, "File")
' Return DS

'Go through the results and write them to the screen
While Not recSet.atEnd()
Dim rec As MSUtil.ILogRecord =recSet.getRecord()
Debug.Write(String.Format("Found Record: {0} {1} {2}", rec.getValue(0), rec.getValue(1), rec.getValue(2)))
recSet.moveNext()
End While

Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function

postmaster@appointmentsbook.com 2/11/2005 8:37 PM | Jeremy

# log parser 2.2

Gravatar I want to analyze windows media log files. Specifically interested in number of hits for streaming media publish points and video on demand (VOD) hit count by name and date.

I need to run log parser against multiple log files on each of six windows media servers. Each server contains logs saved on a daily basis. Thoughts?

crayg@rocketmail.com 3/1/2005 7:00 PM | craig

# re: Log Parser v2.1

Gravatar All, there's a forum at www.logparser.com where you can ask questions directly to the developer! 3/8/2005 11:35 AM | Neurodancer

# re: Log Parser v2.1

Gravatar This looks perfect but I wondered if anyone had an example using classic asp? 5/11/2005 10:12 AM | Mick

# re: Log Parser v2.1

Gravatar how could i get the results back from the log query to a recordset? i want to query the secuirty log (which i have working), but i want to put the records into a vb.net recordset

thanks for your help! 3/13/2006 6:46 AM | Ed

# re: Log Parser v2.1

Gravatar Hi

I'm trying to list files but i get this Error

CLogQueryClass: Error 80070002: ExecuteBatch: error executing query: Cannot open : Cannot find any file matching "d:\log\W3SVC1\ex*.log" [ Das System kann die angegebene Datei nicht finden. ]

But the files are there!!

thanks for your help!
8/11/2006 1:34 AM | Mike

# re: Log Parser v2.1

Gravatar In regards to the code submited by Asdrubal, it was a great help, but was missing a couple of lines form the "While" loop:

MSUtil.COMIISW3CInputContextClass inputContext = new MSUtil.COMIISW3CInputContextClassClass();
MSUtil.LogQueryClass logQuery = new MSUtil.LogQueryClassClass();
string query="SELECT cs(Referer) as Referer,cs-uri-stem as To,COUNT(*) as Total from " + inPath +
" WHERE (sc-status=200) AND (Referer LIKE 'http:%') GROUP BY Referer,To ORDER BY Total DESC";
MSUtil.ILogRecordset logRecordset = null;
MSUtil.ILogRecord row = null;
logRecordset = logQuery.Execute(query, inputContext);

while (!logRecordset.atEnd())
{
row = logRecordset.getRecord();
string RowColumns = row.getValue(0).ToString();
//print the row
Console.WriteLine(RowColumns);
logRecordset.moveNext();

}
9/20/2006 3:27 PM | Shayne

# Log Parser v2.1

Gravatar i am getting trouble in giving the output context. I want to the output file to be in the text pad format not in SQL table so please suggest as which output context can be used. 12/11/2006 5:58 AM | Najeeb

# retrieve a list of log files from two web servers

Gravatar Hi All - I am trying to write a query that will query back a list of iis log files from two web server locations using log parser. Does anyone know the syntax to do that. I dont want to hard code the path to the location like C:\WINDOWS\system32\LogFiles\W3SVC1. I want the path to be dynamic since i have two web servers to query against. Any guidance will surely help. Thanks 6/26/2007 1:32 PM | LostKid

# re: Log Parser v2.1

Gravatar For parsing Windows Media logs, check out the Parsing Windows Media Services Log Files white paper (http://msdn2.microsoft.com/en-us/library/bb383537.aspx). 7/29/2007 11:41 PM | Chris

# re: Log Parser v2.1

Gravatar My log file si in txt format .it was created by using microsoft practise enterprise library for logging.I want retrive data from that log file by various conditions such as by time stamp,sevirity,message.plz help me 12/11/2007 12:46 AM | Sugukumar

# re: Log Parser v2.1

Gravatar thanks, super! 3/6/2008 9:32 AM | jan semorad

# re: Log Parser v2.1

Gravatar Can anyone post a sample for windows event log output to sql database? Thanks! 5/8/2008 12:24 AM | rodel

# re: Log Parser v2.1

Gravatar Using LogParser, can anybody help me to limit this to the past 30 days of backup files by using the date of the file?

** backup.sql begin **
SELECT DISTINCT server AS server, name AS name, start_time AS start_time
INTO c:\logs\Backup.html
FROM \\backup\BACKUP_*.xml
** backup.sql end **

** Command **
logparser file:c:\Backup.sql -i:xml -fMode:Tree -tpl:c:\BackupTpl.tpl -o:tpl
** Command **
5/29/2008 6:05 PM | Sean...

Post a comment





 

Please add 2 and 6 and type the answer here:

 

 

Copyright © Drew Robbins