Overview
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.
Configurar registro
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 |
|---|---|
| The ILoggerFactory object that creates an ILogger. You can create
an ILoggerFactory object by using the LoggerFactory.Create() method.Data Type: ILoggerFactory Default: null |
| 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: integerDefault: 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);
Mensajes de registro por categoría
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 |
|---|---|
| The progress of commands run against your cluster, represented by
CommandStartedEvent, CommandSucceededEvent, and CommandFailedEvent |
| Changes in the topology of the cluster, including
ClusterAddedServerEvent, ClusterRemovedServerEvent,
ServerHeartbeatStartedEvent, ClusterDescriptionChangedEvent,
and ServerDescriptionChangedEvent |
| The decisions that determine which server to send a particular command to |
| Changes in the cluster connection pool, including ConnectionPoolReadyEvent,
ConnectionPoolClosedEvent, ConnectionCreatedEvent, and
ConnectionCheckoutEvent |
| 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.
Configurar la verbosidad del registro
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
Erroro superior de todas las categoríasTodos los mensajes con nivel de registro
Debugo 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.