Created
August 22, 2012 18:20
-
-
Save andrevdm/3428110 to your computer and use it in GitHub Desktop.
Q&D MongoDB logging
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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