Docs Menu
Docs Home
/ /

Registro

A partir de la versión 2.18, el controlador .NET/C# utiliza el estándar API de registro de .NET. En esta guía, aprenderá a usar el controlador para configurar el registro de su aplicación.

Importante

Para utilizar esta función, debe agregar el paquete Microsoft.Extensions.Logging.Console a su proyecto.

Para especificar la configuración de registro para su aplicación, cree una nueva instancia de la LoggingSettings clase, luego asígnela a la propiedad LoggingSettings de su objeto MongoClientSettings.

El constructor LoggingSettings acepta los siguientes parámetros:

Propiedad
Descripción

LoggerFactory

The ILoggerFactory object that creates an ILogger. You can create an ILoggerFactory object by using the LoggerFactory.Create() method.

Data Type: ILoggerFactory
Default: null

MaxDocumentSize

Optional. The maximum number of characters for extended JSON documents in logged messages.

For example, when the driver logs the CommandStarted message, it truncates the Command field to the number of characters specified in this parameter.

Data Type: integer
Default: 1000

El siguiente ejemplo de código muestra cómo crear un MongoClient que registre todos los mensajes de depuración en la consola:

using var loggerFactory = LoggerFactory.Create(b =>
{
b.AddSimpleConsole();
b.SetMinimumLevel(LogLevel.Debug);
});
var settings = MongoClientSettings.FromConnectionString("<connection string>");
settings.LoggingSettings = new LoggingSettings(loggerFactory);
var client = new MongoClient(settings);

A cada mensaje generado por un clúster de MongoDB se le asigna una categoría. Esto permite especificar diferentes niveles de registro para distintos tipos de mensajes.

MongoDB utiliza las siguientes categorías para clasificar los mensajes:

Categoría
Descripción

MongoDB.Command

The progress of commands run against your cluster, represented by CommandStartedEvent, CommandSucceededEvent, and CommandFailedEvent

MongoDB.SDAM

Changes in the topology of the cluster, including ClusterAddedServerEvent, ClusterRemovedServerEvent, ServerHeartbeatStartedEvent, ClusterDescriptionChangedEvent, and ServerDescriptionChangedEvent

MongoDB.ServerSelection

The decisions that determine which server to send a particular command to

MongoDB.Connection

Changes in the cluster connection pool, including ConnectionPoolReadyEvent, ConnectionPoolClosedEvent, ConnectionCreatedEvent, and ConnectionCheckoutEvent

MongoDB.Internal.*

Prefix for all other .NET/C# Driver internal components

Tip

Puede especificar el nivel de detalle mínimo para todas las categorías de registro configurando la categoría Default.

Puede configurar el nivel de detalle del registro de cada categoría de mensaje mediante el mecanismo de registro estándar de .NET. El siguiente ejemplo de código muestra cómo configurar un MongoClient para registrar dos tipos de mensajes:

  • Todos los mensajes con nivel de registro Error o superior de todas las categorías

  • Todos los mensajes con nivel de registro Debug o superior de la categoría SDAM

En este ejemplo, la configuración se realiza en memoria. El código crea un Dictionary<string, string> donde la clave es "LogLevel:<category>" y el valor es el nivel mínimo de registro de mensajes en esa categoría. A continuación, el código añade el diccionario a un objeto ConfigurationBuilder y, posteriormente, el ConfigurationBuilder a un LoggerFactory.

var categoriesConfiguration = new Dictionary<string, string>
{
{ "LogLevel:Default", "Error" },
{ "LogLevel:MongoDB.SDAM", "Debug" }
};
var config = new ConfigurationBuilder()
.AddInMemoryCollection(categoriesConfiguration)
.Build();
using var loggerFactory = LoggerFactory.Create(b =>
{
b.AddConfiguration(config);
b.AddSimpleConsole();
});
var settings = MongoClientSettings.FromConnectionString("<connection string>");
settings.LoggingSettings = new LoggingSettings(loggerFactory);
var client = new MongoClient(settings);

Tip

Para obtener más información sobre la configuración del nivel de verbosidad de los registros, consulta la documentación de registros de Microsoft .NET.

Volver

Indexes

En esta página