问题
Can someone explain to me why this doesn't just work? This feels astonishing to me. If this is not a viable usage, I would say that this is a design smell. I should either be not permitted to do this by the API's design, or I would expect a useful error.
public static void Main(string[] args)
{
var l = new ConsoleLogger("test", (s, ll) => true, true);
l.WriteMessage(LogLevel.Critical, "test", 0, "hello world", null);
}
This implementation outputs literally nothing. Why? I don't feel like I should have to use the DependencyInjection and service location mechanisms.
回答1:
I guess it's because of the fire and forget (Task.Factory.StartNew
) implementation. See here. (In other words, the code doesn't wait for the message to be printed.)
If you do this:
var l = new ConsoleLogger("test", (s, ll) => true, true);
for (int i = 0; i < 10000; i++)
{
l.WriteMessage(LogLevel.Critical, "test", 0, "hello world", null);
}
it works fine and the messages are being printed.
If you need to do the console logging synchronously, I suggest you implement your own console logger where you await the logging operation.
来源:https://stackoverflow.com/questions/47424051/creating-consolelogger-directly-astonishingly-doesnt-work