I am working on code reconstruction recently. For the previous logging function, we need to pass the log message as well as come contextual information (like tracking ID, user ID, etc) on each function’s calling. So, the code is relatively ugly:

public class Foo {
	public void Bar(ILogContext context, string str, ObjA a) {
		...
		Logger.logInfo(context, "code is running here and working from something.");
		...
	}

	public void FooBar(ILogContext context, string testString){
		...
		Logger.logInfo(context, "code is running here and call Bar.");
		Bar(context, testString, new ObjA());
		...
	}
}

To avoid this, I try to find out something that can storage thread contextual information. And I found the ThreadStatic Attribute, where we can attribute a static field and the field will be unique for each thread.

public static class Logger{
	[ThreadStatic]
	private static ILogContext _context;

	public static bool InitializeThreadContext(ILogContext context) {
		if (_context != null) {
			if (_context == context) {
				LogVerbose("Logging context is initialized again!");
			} else {
				LogWarning("Logging context is trying to initialize for a new context! new context: {0}.", context);
				_context = context;
			}
			return false;
		}
		_context = context;
		return true;
	}

	...
}

public class Foo {
	public void Bar(string str, ObjA a) {
		...
		Logger.logInfo("code is running here and working from something.");
		...
	}

	public void FooBar(string testString){
		...
		Logger.logInfo("code is running here and call Bar.");
		Bar(context, testString, new ObjA());
		...
	}
}

After this, we just init to InitializeThreadContext once a thread start, and then we don’t need to pass the context object everywhere in our code.