How-To: add geographical information to IIS log files with LINQ
LINQ in action: a real life problem, solved with a few lines of easy-to-read code. In my last post, I promised to provide a solution to enhance the information we can derive from IIS logs with the help of Log Parser. All you need is the free Geo-IP database (updated frequently) that can be found here plus the free C# API that is provided by these generous folks.
create a (less messy :-) ) little command line program that has a LINQ statement like this:
using System;
using System.Collections.Generic;
using System.Linq;
namespace CountryLookupProj
{
class SumColumns
{
static void Main(string[] args)
{
string[] lines = System.IO.File.ReadAllLines(args[0]);
int exam = int.Parse(args[1]);
AddSingleColumn(lines, exam - 1);
Console.WriteLine();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
static void AddSingleColumn(IEnumerable<string> strs, int examNum)
{
CountryLookup countryLookup =
new CountryLookup(@"C:\Stuff\GeoLiteCity\Geoip.dat");
var columnQuery =
from line in strs
let x = line.Split(';')
select countryLookup.lookupCountryName(x[examNum])
+ ";" + String.Join(";", x);
System.IO.File.WriteAllLines(@"c:\temp\output.log",
columnQuery.ToArray());
}
}
}
run it like this:
c:>\myprogram.exe "mylogfile.CSV" 1
the 1 is the (one-based) position of the ip-address column in your CSV-file.
thanks for the inspiration found here (MSDN)