|
From: Geoghegan, W. A (Willie) <wil...@in...> - 2010-10-01 21:47:40
|
Too long again. Part 1.
I have seen on the Common.Logging home page that Logging Context support
is planned for the next release. In the meantime, I have implemented a
logging context abstraction that is based, in part, on Castle's logging
context abstraction that they provide for log4net and NLog. At this
point I consider it somewhat experimental, but I think there are some ok
ideas here. I also did not modify any Common.Logging code. In a "real"
implementation, I would expect that context would be available from
LogManager (or maybe from ILog as was done in Castle). I think that
making it available from ILog could be misleading because it could be
read as "the logging context for THIS logger", which is not really true.
Anyway, with my code you can do something like to this to set the
context (LogContext is my static object that provides the entry point
into the logging context abstraction):
LogContext.GlobalProperties["number"] = 1234;
LogContext.ThreadProperties["id"] = System.Threading.Whatever.Id;
using (LogContext.ThreadStack.Push["outer level"])
{
DoSomeStuff();
using (LogContext.ThreadStack.Push["inner level")
{
DoSomeStuffFromInnerLevel();
}
}
Which logging context abstraction is in play is dictated by the current
LogManager.Adapter's implementation (or lack of same) of an interface,
IContextProvider. When one of the context operations (GlobalProperties,
ThreadProperties, ThreadStack) is access on LogContext, code like this
executes:
IContextProperties GlobalProperties
{
get
{
IAdapterContextProvider iacp = LogManager.Adapter as
IContextProvider;
if (iacp == null)
{
return NullContextProvider.GlobalProperties; //Does nothing, but
also does not fail.
}
else
{
return iacp.Context.GlobalProperties; //Global properties relevant
to the currently abstracted logger
}
}
}
To take advantage of LogContext, I have copied the NLog abstraction
provided by Common.Logging and added the IAdapterContextProvider
interface. Now, when I configure my NLog abstraction, LogContext finds
that LogManager.Adapter does support the interface, so the NLog context
values can be set. I have done something similar for log4net.
William A. Geoghegan
Software Scientist
Intergraph Corporation
Security, Government & Infrastructure (SG&I) Division
P.O. Box 6695, Huntsville, AL 35824-0695 USA
P 1.256.730.8371
wil...@in..., www.intergraph.com
|