Creating ConsoleLogger directly astonishingly does

2019-09-19 08:58发布

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条回答
ゆ 、 Hurt°
2楼-- · 2019-09-19 09:17

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.

查看更多
登录 后发表回答