patterncsharpMinor
Ambient Context
Viewed 0 times
contextambientstackoverflow
Problem
What do you think about this way to make logging available across the application without passing
Here is the
Where
Theoretically, per-request instance of
log object around? Let’s say we have something which allows us to write things this way:class Program
{
static void Main(string[] args)
{
using (new Log("c:\\a.txt"))
AsyncContext.Run(() => MainAsync());
}
static async Task MainAsync()
{
Log.Write("a1"); // Writes to a.txt
await Task.Delay(1000);
Log.Write("a2"); // Writes to a.txt
using (new Log("c:\\b.txt"))
await F();
Log.Write("a3"); // Writes to a.txt
}
static async Task F()
{
Log.Write("b1"); // Writes to b.txt
}
}Here is the
Log library code:class Log : Ambient
{
public static void Write(string line) =>
Current?.WriteCore(line);
public Log(string fileName)
{
FileName = fileName;
}
void WriteCore(string line) => File.AppendAllText(FileName, line);
string FileName { get; }
}Where
Ambient is defined as:class Ambient : IDisposable where T : Ambient
{
static readonly string Id = typeof(T).FullName;
protected static T Current
{
get { return (T)CallContext.LogicalGetData(Id); }
set { CallContext.LogicalSetData(Id, value); }
}
protected Ambient()
{
Previous = Current;
Current = (T)this;
}
public void Dispose() => Current = Previous;
T Previous { get; }
}Theoretically, per-request instance of
Log could come from IoC with all the dependencies injected while taking into account ASP.NET applications.Solution
In the example code you provided, you are just setting up where the logger is writing to, within a certain context. The reason you may consider passing around a logger object is when you need to have more complicated configuration for setting up a logger object.
It really depends on what you want. On one hand, having a static logger is nice. You don't have to worry about having to include a logger param everywhere in your code. Having to refactor your code when you have a bunch of static method calls is a huge cost if you decided to change later, to make configuration more flexible.
It really depends on what you want. On one hand, having a static logger is nice. You don't have to worry about having to include a logger param everywhere in your code. Having to refactor your code when you have a bunch of static method calls is a huge cost if you decided to change later, to make configuration more flexible.
Context
StackExchange Code Review Q#140694, answer score: 2
Revisions (0)
No revisions yet.