Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
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, puedes aprender a utilizar el Controlador para configurar el registro de actividad de tu aplicación.

Importante

Para usar esta funcionalidad, debes agregar el paquete Microsoft.Extensions.Logging.Console a tu Proyecto.

Para especificar la configuración de registro para tu aplicación, crea una nueva instancia del LoggingSettings clase y luego asígnala a la propiedad LoggingSettings de tu 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

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

Puede configurar el nivel de verbosidad de los registros de cada categoría de mensajes utilizando 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 de registro mínimo de los mensajes en esa categoría. A continuación, el código añade el diccionario a un objeto ConfigurationBuilder, y luego añade 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

Time Series

En esta página