gpt4 book ai didi

c# - MongoDB - 查看失败的命令

转载 作者:可可西里 更新时间:2023-11-01 10:36:24 34 4
gpt4 key购买 nike

失败的命令(插入、更新、删除等)是否被 Mongo DB 记录在任何地方?

我正在使用 C# 驱动程序,由于重复的唯一键(由索引强制执行),一些命令失败(例如插入),所以我想回顾一下插入了哪些文档。
我想在驱动程序序列化后查看失败的原始文档。

顺便说一下,据我所知,Mongo oplog 只包含成功的命令。

最佳答案

Are failed commands (inserts, updated, deletes etc.) logged anywhere by Mongo DB?

我不认为它们是,但也许我还没有努力找到它们。

但是,您可以像这样在 MongoClientSettings 上设置 ClusterConfigurator,将它们记录在应用程序中

           //Build the initial settings from the MongoConnectionString
MongoClientSettings settings = MongoClientSettings.FromConnectionString("MongoConnectionString");

//Subscribe on the following events
settings.ClusterConfigurator += cb =>
{
cb.Subscribe(delegate (CommandStartedEvent startedEvent) { Console.WriteLine($"Started: {startedEvent.Command} with OpId: {startedEvent.OperationId}"); });
cb.Subscribe(delegate (CommandSucceededEvent succeededEvent) { Console.WriteLine($"Succeeded OpId: {succeededEvent.OperationId}"); });
cb.Subscribe(delegate (CommandFailedEvent failedEvent) { Console.WriteLine($"Failed OpId: {failedEvent.OperationId}"); });
};

//Builld a MongoClient with the new Settings
var client = new MongoClient(settings);

此示例将仅写入正在执行的命令以及 OperationId 失败或成功的命令。

但从这里开始,您可以通过跟踪启动了哪个命令以及它运行的 OperationId 来扩展它。

有关完整示例,您可以查看 Gist (因为在这里发布的代码似乎太多了)。

可以这样称呼:

        var settings = MongoClientSettings.FromConnectionString("MongoConnectionString");
new MongoTracking().ConfigureTracking(settings);

var client = new MongoClient(settings);

郑重声明,这会在应用程序而不是数据库中进行日志记录。

关于c# - MongoDB - 查看失败的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56459230/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com