Skip to content

Instantly share code, notes, and snippets.

@andrevdm
Created August 22, 2012 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrevdm/3428110 to your computer and use it in GitHub Desktop.
Save andrevdm/3428110 to your computer and use it in GitHub Desktop.
Q&D MongoDB logging
using System;
using System.Diagnostics;
using MongoDB.Driver;
namespace MongoDbLogging
{
class Program
{
private static bool g_logCalls;
static void Main( string[] args )
{
//g_logCalls = Convert.ToBoolean( ConfigurationManager.AppSettings["LogCalls"] ?? "false" );
g_logCalls = true;
var program = new Program();
program.DoSomeThing( "123", new SomeComplexParam { Param1 = "111" } );
}
public SomeResult DoSomeThing( string someSimpleParam, SomeComplexParam complexParam )
{
return Execute(
"DoSomeThing",
new { someSimpleParam, complexParam },
() =>
{
//Do stuff.
//So all methods wrapped with the Execute method
return new SomeResult { Value = 10 };
} );
}
private T Execute<T>( string method, object parameters, Func<T> action )
{
Exception exception = null;
T response = default( T );
TimeSpan? elapsed = null;
try
{
var timer = new Stopwatch();
timer.Start();
response = action();
timer.Stop();
elapsed = timer.Elapsed;
}
catch( Exception ex )
{
exception = ex;
}
if( g_logCalls )
{
string con = "mongodb://localhost:27017";
var server = MongoServer.Create( con );
MongoDatabase db = server["logging"];
MongoCollection coll = db["webServiceLog"];
coll.Insert( new
{
At = DateTime.Now,
Method = method,
Duration = elapsed,
Parameters = parameters,
Response = response,
Exception = exception != null ? exception.ToString() : null
} );
}
if( exception != null )
{
throw exception;
}
return response;
}
}
internal class SomeResult
{
public int Value { get; set; }
}
internal class SomeComplexParam
{
public string Param1 { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment