英文:
Implement a message queue for logging in a .NET webapi
问题
我有一个.NET7服务器,其中有一些WebAPI,用NLog记录请求和响应到日志文件。在控制器中,我不想浪费时间记录日志,所以我将消息添加到ConcurrentQueue<LogText>
中,方法如下:
var logText = new LogText { deviceSerial = deviceSerial, message = message };
logTextsQueue.Enqueue(logText);
在Main.cs中,我添加了以下循环,有效地将日志写入磁盘:
_ = Task.Run(async () =>
{
while (true)
{
try
{
if (logTextsQueue.TryDequeue(out LogText result))
{
LogOut(result.deviceSerial, result.message);
}
}
catch (Exception ex)
{
LogManager.GetCurrentClassLogger().Error($"C3 Background thread error: {ex.Message}");
}
finally
{
}
}
});
这是一种消息队列的实现方式。看起来它运行正常,但您是否应该担心这个简单的实现中的一些问题呢?
谢谢
英文:
I have a .NET7 server, with a few webapi, that logs the request and responses to log files with NLog.
I don't want to waste time on the logging, so in the controllers I add the message to a
ConcurrentQueue<LogText> logTextsQueque
this way
var logText = new LogText { deviceSerial= deviceSerial, message = message };
logTextsQueque.Enqueue(logText);
and in the Main.cs I added this loop, that effectively writes the log to disk:
_ = Task.Run(async () =>
{
while (true)
{
try
{
if (logTextsQueque.TryDequeue(out LogText result))
{
LogOut(result.deviceSerial, result.message);
}
}
catch (Exception ex)
{
LogManager.GetCurrentClassLogger().Error($"C3 Background thread error: {ex.Message}");
}
finally
{
}
}
});
It's a sort of message queue. It seems to be working, but is there something I should be worried about with this simple implementation?
Thanks
答案1
得分: 0
NLog内置了一个名为AsyncWrapper的消息队列,可以在NLog.config
中轻松启用,使用<targets async="true">
:
默认情况下,它使用overflowAction="Discard"
来防止由于日志问题而导致应用程序失败。
AsyncWrapper确保NLog上下文会正确捕获${threadid}
并记录应用程序线程的线程ID(而不是处理消息队列的后台线程的线程ID)。
英文:
NLog has a builtin message-queue called AsyncWrapper, that can be easily enabled in NLog.config
using <targets async="true">
:
By default it uses overflowAction="Discard"
to prevent application failure because of logging issues.
The AsyncWrapper ensures that NLog Context will correctly capture ${threadid}
and will log the threadid of the application-thread (and not the background thread handling the message-queue).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论