Friday, 15 April 2011

c# - Identify log entries across a series of async operations -



c# - Identify log entries across a series of async operations -

i have seen in past people associating log entries on thread id; imperfect solution, 1 worked in many cases. having started doing async programming in c#, curious best way handle logging across multiple async operations. example:

async task<string> getsongnameasync(byte [] songbytes, authinfo auth) { log("received request user " + auth.user); if (!await authentication.haspremiumaccountasync(auth)) // more logging in here { homecoming "error: subscription not back upwards feature"; } song song = await songidentifier.identifyasync(songbytes); // more logging here if (song != null) { homecoming song.tostring() } homecoming new song() {name = "never gonna give up", artist = "rick astley", notes = "you got rick-rolled!"}; }

if there error in auth logic or song id logic, i'd associate error particular request, can query logging database , see somewhat-sequentially how request handled, , maybe why failed. start passing around guid or that, , include in message, seems cumbersome create every constructor , object expose value, when want @ async equivalent of 'thread local storage'.

you can utilize task.id ,and static task.currentid in similar way thread.id, doesn't play along async\await can see here. think best approach identify each request receive in unique way, either attaching requestid (or base of operations class), using provided infrastucture (in wcf operationcontext.current.incomingmessageheaders.messageid), or using exact tick (maybe thread id) when request received id.

btw nice solution if request handled across distributed system

regarding comment..

you can:

public static class magicalhelpper { private static conditionalweaktable<object, int> _registry = new conditionalweaktable<object, int>(); public void getid(object obj) { int result = _registry.getvalue(obj, ((object key)=> datetime.now.ticks + thread.currentthread.managedthreadid)); homecoming result; } }

this written without compiler...

now whenever want, can go magicalhelpper.getid(something) remember stick same request object...

this should compleatly thread safe, , not cause memory leak. conditionalweaktable documentation: http://msdn.microsoft.com/en-us/library/dd287757.aspx

c# logging asynchronous

No comments:

Post a Comment