diff --git a/src/MongoDB.Bson/BsonExtensionMethods.cs b/src/MongoDB.Bson/BsonExtensionMethods.cs index bda37baf3a1..32844fdaa21 100644 --- a/src/MongoDB.Bson/BsonExtensionMethods.cs +++ b/src/MongoDB.Bson/BsonExtensionMethods.cs @@ -181,7 +181,7 @@ public static BsonDocument ToBsonDocument( /// The object. /// The JsonWriter settings. /// The serializer. - /// The serializastion context configurator. + /// The serialization context configurator. /// The serialization args. /// /// A JSON string. diff --git a/src/MongoDB.Driver.Core/Core/Clusters/SingleServerCluster.cs b/src/MongoDB.Driver.Core/Core/Clusters/SingleServerCluster.cs index 58f06d73260..c7d6503c832 100644 --- a/src/MongoDB.Driver.Core/Core/Clusters/SingleServerCluster.cs +++ b/src/MongoDB.Driver.Core/Core/Clusters/SingleServerCluster.cs @@ -59,12 +59,12 @@ protected override void Dispose(bool disposing) if (_server != null) { - _clusterEventsLogger.LogAndPublish(new ClusterRemovingServerEvent(_server.ServerId, "Cluster is closing.")); + _clusterEventsLogger.LogAndPublish(new ClusterRemovingServerEvent(_server.ServerId, "Removing server.")); _server.DescriptionChanged -= ServerDescriptionChanged; _server.Dispose(); - _clusterEventsLogger.LogAndPublish(new ClusterRemovedServerEvent(_server.ServerId, "Cluster is closing.", stopwatch.Elapsed)); + _clusterEventsLogger.LogAndPublish(new ClusterRemovedServerEvent(_server.ServerId, "Server removed.", stopwatch.Elapsed)); } stopwatch.Stop(); } diff --git a/src/MongoDB.Driver.Core/Core/Configuration/ClusterBuilder.cs b/src/MongoDB.Driver.Core/Core/Configuration/ClusterBuilder.cs index 1c12daa438d..a0453d17503 100644 --- a/src/MongoDB.Driver.Core/Core/Configuration/ClusterBuilder.cs +++ b/src/MongoDB.Driver.Core/Core/Configuration/ClusterBuilder.cs @@ -17,7 +17,6 @@ using System.Diagnostics; using System.IO; using System.Threading; -using Microsoft.Extensions.Logging; using MongoDB.Driver.Core.Authentication; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.ConnectionPools; @@ -43,7 +42,7 @@ public class ClusterBuilder private ClusterSettings _clusterSettings; private ConnectionPoolSettings _connectionPoolSettings; private ConnectionSettings _connectionSettings; - private ILoggerFactory _loggerFactory; + private LoggingSettings _loggingSettings; #pragma warning disable CS0618 // Type or member is obsolete private SdamLoggingSettings _sdamLoggingSettings; #pragma warning restore CS0618 // Type or member is obsolete @@ -121,16 +120,16 @@ public ClusterBuilder ConfigureConnectionPool(Func - /// Configures the logging factory. + /// Configures the logging settings. /// - /// The logging factory configurator delegate. + /// The logging settings configurator delegate. /// A reconfigured cluster builder. [CLSCompliant(false)] - public ClusterBuilder ConfigureLoggingFactory(Func configurator) + public ClusterBuilder ConfigureLoggingSettings(Func configurator) { Ensure.IsNotNull(configurator, nameof(configurator)); - _loggerFactory = configurator(_loggerFactory).DecorateCategories(); + _loggingSettings = configurator(_loggingSettings); return this; } @@ -139,7 +138,7 @@ public ClusterBuilder ConfigureLoggingFactory(Func /// The SDAM logging settings configurator delegate. /// A reconfigured cluster builder. - [Obsolete("Use ConfigureLoggingFactory instead.")] + [Obsolete("Use ConfigureLoggingSettings instead.")] public ClusterBuilder ConfigureSdamLogging(Func configurator) { _sdamLoggingSettings = configurator(_sdamLoggingSettings); @@ -241,7 +240,7 @@ private IClusterFactory CreateClusterFactory() _clusterSettings, serverFactory, _eventAggregator, - _loggerFactory); + _loggingSettings?.ToInternalLoggingFactory()); } private IConnectionPoolFactory CreateConnectionPoolFactory() @@ -253,7 +252,7 @@ private IConnectionPoolFactory CreateConnectionPoolFactory() streamFactory, _eventAggregator, _clusterSettings.ServerApi, - _loggerFactory); + _loggingSettings.ToInternalLoggingFactory()); var connectionPoolSettings = _connectionPoolSettings.WithInternal(isPausable: !_connectionSettings.LoadBalanced); @@ -261,7 +260,7 @@ private IConnectionPoolFactory CreateConnectionPoolFactory() connectionPoolSettings, connectionFactory, _eventAggregator, - _loggerFactory); + _loggingSettings.ToInternalLoggingFactory()); } private ServerFactory CreateServerFactory() @@ -284,7 +283,7 @@ private ServerFactory CreateServerFactory() serverMonitorFactory, _eventAggregator, _clusterSettings.ServerApi, - _loggerFactory); + _loggingSettings.ToInternalLoggingFactory()); } private IServerMonitorFactory CreateServerMonitorFactory() @@ -326,7 +325,7 @@ private IServerMonitorFactory CreateServerMonitorFactory() serverMonitorConnectionFactory, _eventAggregator, _clusterSettings.ServerApi, - _loggerFactory); + _loggingSettings.ToInternalLoggingFactory()); } private IStreamFactory CreateTcpStreamFactory(TcpStreamSettings tcpStreamSettings) diff --git a/src/MongoDB.Driver.Core/Core/Configuration/LoggingSettings.cs b/src/MongoDB.Driver.Core/Core/Configuration/LoggingSettings.cs new file mode 100644 index 00000000000..791f9dfd524 --- /dev/null +++ b/src/MongoDB.Driver.Core/Core/Configuration/LoggingSettings.cs @@ -0,0 +1,101 @@ +/* Copyright 2010-present MongoDB Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +using System; +using Microsoft.Extensions.Logging; + +namespace MongoDB.Driver.Core.Configuration +{ + /// + /// Represents the settings for logging. + /// + public sealed class LoggingSettings : IEquatable + { + /// + /// Gets the logger factory. + /// + [CLSCompliant(false)] + public ILoggerFactory LoggerFactory { get; } + + /// + /// Gets the maximum document size in chars + /// + public int MaxDocumentSize { get; } + + // constructors + /// + /// Initializes a new instance of the class. + /// + /// The logger factory. + /// The maximum document size in chars. + [CLSCompliant(false)] + public LoggingSettings( + ILoggerFactory loggerFactory = default, + Optional maxDocumentSize = default) + { + LoggerFactory = loggerFactory; + MaxDocumentSize = maxDocumentSize.WithDefault(MongoInternalDefaults.Logging.MaxDocumentSize); + } + + // public operators + /// + /// Determines whether two instances are equal. + /// + /// The LHS. + /// The RHS. + /// + /// true if the left hand side is equal to the right hand side; otherwise, false. + /// + public static bool operator ==(LoggingSettings lhs, LoggingSettings rhs) + { + return object.Equals(lhs, rhs); // handles lhs == null correctly + } + + /// + /// Determines whether two instances are not equal. + /// + /// The LHS. + /// The RHS. + /// + /// true if the left hand side is not equal to the right hand side; otherwise, false. + /// + public static bool operator !=(LoggingSettings lhs, LoggingSettings rhs) + { + return !(lhs == rhs); + } + + // public methods + /// + /// Determines whether the specified is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public bool Equals(LoggingSettings rhs) + { + return + rhs != null && + LoggerFactory == rhs.LoggerFactory && + MaxDocumentSize == rhs.MaxDocumentSize; + } + + /// + public override bool Equals(object obj) => Equals(obj as LoggingSettings); + + /// + public override int GetHashCode() => base.GetHashCode(); + } +} diff --git a/src/MongoDB.Driver.Core/Core/ConnectionPools/ExclusiveConnectionPool.cs b/src/MongoDB.Driver.Core/Core/ConnectionPools/ExclusiveConnectionPool.cs index 2b5794d4d0b..287a2f52b95 100644 --- a/src/MongoDB.Driver.Core/Core/ConnectionPools/ExclusiveConnectionPool.cs +++ b/src/MongoDB.Driver.Core/Core/ConnectionPools/ExclusiveConnectionPool.cs @@ -17,7 +17,6 @@ using System.Net; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using MongoDB.Bson; using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Connections; @@ -54,18 +53,16 @@ public ExclusiveConnectionPool( EndPoint endPoint, ConnectionPoolSettings settings, IConnectionFactory connectionFactory, - IEventSubscriber eventSubscriber, IConnectionExceptionHandler connectionExceptionHandler, - ILogger logger) + EventsLogger eventsLogger) { _serverId = Ensure.IsNotNull(serverId, nameof(serverId)); _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint)); _settings = Ensure.IsNotNull(settings, nameof(settings)); _connectionFactory = Ensure.IsNotNull(connectionFactory, nameof(connectionFactory)); _connectionExceptionHandler = Ensure.IsNotNull(connectionExceptionHandler, nameof(connectionExceptionHandler)); - Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber)); - _eventsLogger = logger.ToEventsLogger(eventSubscriber); + _eventsLogger = Ensure.IsNotNull(eventsLogger, nameof(eventsLogger)); _maintenanceHelper = new MaintenanceHelper(this, _settings.MaintenanceInterval); _poolState = new PoolState(EndPointHelper.ToString(_endPoint)); diff --git a/src/MongoDB.Driver.Core/Core/ConnectionPools/ExclusiveConnectionPoolFactory.cs b/src/MongoDB.Driver.Core/Core/ConnectionPools/ExclusiveConnectionPoolFactory.cs index f3d14768154..5be48f5d398 100644 --- a/src/MongoDB.Driver.Core/Core/ConnectionPools/ExclusiveConnectionPoolFactory.cs +++ b/src/MongoDB.Driver.Core/Core/ConnectionPools/ExclusiveConnectionPoolFactory.cs @@ -45,7 +45,7 @@ public IConnectionPool CreateConnectionPool(ServerId serverId, EndPoint endPoint Ensure.IsNotNull(serverId, nameof(serverId)); Ensure.IsNotNull(endPoint, nameof(endPoint)); - return new ExclusiveConnectionPool(serverId, endPoint, _settings, _connectionFactory, _eventSubscriber, connectionExceptionHandler, _loggerFactory?.CreateLogger()); + return new ExclusiveConnectionPool(serverId, endPoint, _settings, _connectionFactory, connectionExceptionHandler, _loggerFactory.CreateEventsLogger(_eventSubscriber)); } } } diff --git a/src/MongoDB.Driver.Core/Core/Connections/BinaryConnection.cs b/src/MongoDB.Driver.Core/Core/Connections/BinaryConnection.cs index 18a04b19cd8..14332f075fe 100644 --- a/src/MongoDB.Driver.Core/Core/Connections/BinaryConnection.cs +++ b/src/MongoDB.Driver.Core/Core/Connections/BinaryConnection.cs @@ -137,6 +137,8 @@ public ConnectionSettings Settings get { return _settings; } } + private bool IsInitializing => _state.Value == State.Initializing; + // methods private void ConnectionFailed(Exception exception) { @@ -153,7 +155,7 @@ private void ConnectionFailed(Exception exception) { _failedEventHasBeenRaised = true; _eventsLogger.LogAndPublish(new ConnectionFailedEvent(_connectionId, exception)); - _commandEventHelper.ConnectionFailed(_connectionId, _description?.ServiceId, exception); + _commandEventHelper.ConnectionFailed(_connectionId, _description?.ServiceId, exception, IsInitializing); } } @@ -920,7 +922,7 @@ public void FailedReceivingMessage(Exception exception) { if (_connection._commandEventHelper.ShouldCallErrorReceiving) { - _connection._commandEventHelper.ErrorReceiving(_responseTo, _connection._connectionId, _connection.Description?.ServiceId, exception); + _connection._commandEventHelper.ErrorReceiving(_responseTo, _connection._connectionId, _connection.Description?.ServiceId, exception, _connection.IsInitializing); } _connection._eventsLogger.LogAndPublish(new ConnectionReceivingMessageFailedEvent(_connection.ConnectionId, _responseTo, exception, EventContext.OperationId)); @@ -930,7 +932,7 @@ public void ReceivedMessage(IByteBuffer buffer, ResponseMessage message) { if (_connection._commandEventHelper.ShouldCallAfterReceiving) { - _connection._commandEventHelper.AfterReceiving(message, buffer, _connection._connectionId, _connection.Description?.ServiceId, _messageEncoderSettings); + _connection._commandEventHelper.AfterReceiving(message, buffer, _connection._connectionId, _connection.Description?.ServiceId, _messageEncoderSettings, _connection.IsInitializing); } _connection._eventsLogger.LogAndPublish(new ConnectionReceivedMessageEvent(_connection.ConnectionId, _responseTo, buffer.Length, _networkDuration, _deserializationDuration, EventContext.OperationId)); @@ -1017,7 +1019,7 @@ public void FailedSendingMessages(Exception ex) { if (_connection._commandEventHelper.ShouldCallErrorSending) { - _connection._commandEventHelper.ErrorSending(_messages, _connection._connectionId, _connection._description?.ServiceId, ex); + _connection._commandEventHelper.ErrorSending(_messages, _connection._connectionId, _connection._description?.ServiceId, ex, _connection.IsInitializing); } _connection._eventsLogger.LogAndPublish(new ConnectionSendingMessagesFailedEvent(_connection.ConnectionId, _requestIds.Value, ex, EventContext.OperationId)); @@ -1027,7 +1029,7 @@ public void SendingMessages(IByteBuffer buffer) { if (_connection._commandEventHelper.ShouldCallBeforeSending) { - _connection._commandEventHelper.BeforeSending(_messages, _connection.ConnectionId, _connection.Description?.ServiceId, buffer, _messageEncoderSettings, _commandStopwatch); + _connection._commandEventHelper.BeforeSending(_messages, _connection.ConnectionId, _connection.Description?.ServiceId, buffer, _messageEncoderSettings, _commandStopwatch, _connection.IsInitializing); } _networkStopwatch = Stopwatch.StartNew(); @@ -1040,7 +1042,7 @@ public void SentMessages(int bufferLength) if (_connection._commandEventHelper.ShouldCallAfterSending) { - _connection._commandEventHelper.AfterSending(_messages, _connection._connectionId, _connection.Description?.ServiceId); + _connection._commandEventHelper.AfterSending(_messages, _connection._connectionId, _connection.Description?.ServiceId, _connection.IsInitializing); } _connection._eventsLogger.LogAndPublish(new ConnectionSentMessagesEvent(_connection.ConnectionId, _requestIds.Value, bufferLength, networkDuration, _serializationDuration, EventContext.OperationId)); diff --git a/src/MongoDB.Driver.Core/Core/Connections/CommandEventHelper.cs b/src/MongoDB.Driver.Core/Core/Connections/CommandEventHelper.cs index 2093ba52b81..7c4d02336e2 100644 --- a/src/MongoDB.Driver.Core/Core/Connections/CommandEventHelper.cs +++ b/src/MongoDB.Driver.Core/Core/Connections/CommandEventHelper.cs @@ -88,7 +88,8 @@ public void BeforeSending( ObjectId? serviceId, IByteBuffer buffer, MessageEncoderSettings encoderSettings, - Stopwatch stopwatch) + Stopwatch stopwatch, + bool skipLogging) { using (var stream = new ByteBufferStream(buffer, ownsBuffer: false)) { @@ -96,12 +97,12 @@ public void BeforeSending( while (messageQueue.Count > 0) { - ProcessRequestMessages(messageQueue, connectionId, serviceId, stream, encoderSettings, stopwatch); + ProcessRequestMessages(messageQueue, connectionId, serviceId, stream, encoderSettings, stopwatch, skipLogging); } } } - public void AfterSending(IEnumerable messages, ConnectionId connectionId, ObjectId? serviceId) + public void AfterSending(IEnumerable messages, ConnectionId connectionId, ObjectId? serviceId, bool skipLogging) { foreach (var message in messages) { @@ -120,14 +121,15 @@ public void AfterSending(IEnumerable messages, ConnectionId conn message.RequestId, connectionId, serviceId, - state.Stopwatch.Elapsed)); + state.Stopwatch.Elapsed), + skipLogging); } _state.TryRemove(message.RequestId, out state); } } } - public void ErrorSending(IEnumerable messages, ConnectionId connectionId, ObjectId? serviceId, Exception exception) + public void ErrorSending(IEnumerable messages, ConnectionId connectionId, ObjectId? serviceId, Exception exception, bool skipLogging) { foreach (var message in messages) { @@ -142,12 +144,13 @@ public void ErrorSending(IEnumerable messages, ConnectionId conn message.RequestId, connectionId, serviceId, - state.Stopwatch.Elapsed)); + state.Stopwatch.Elapsed), + skipLogging); } } } - public void AfterReceiving(ResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, ObjectId? serviceId, MessageEncoderSettings encoderSettings) + public void AfterReceiving(ResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, ObjectId? serviceId, MessageEncoderSettings encoderSettings, bool skipLogging) { CommandState state; if (!_state.TryRemove(message.ResponseTo, out state)) @@ -158,15 +161,15 @@ public void AfterReceiving(ResponseMessage message, IByteBuffer buffer, Connecti if (message is CommandResponseMessage) { - ProcessCommandResponseMessage(state, (CommandResponseMessage)message, buffer, connectionId, serviceId, encoderSettings); + ProcessCommandResponseMessage(state, (CommandResponseMessage)message, buffer, connectionId, serviceId, encoderSettings, skipLogging); } else { - ProcessReplyMessage(state, message, buffer, connectionId, encoderSettings); + ProcessReplyMessage(state, message, buffer, connectionId, encoderSettings, skipLogging); } } - public void ErrorReceiving(int responseTo, ConnectionId connectionId, ObjectId? serviceId, Exception exception) + public void ErrorReceiving(int responseTo, ConnectionId connectionId, ObjectId? serviceId, Exception exception, bool skipLogging) { CommandState state; if (!_state.TryRemove(responseTo, out state)) @@ -184,10 +187,11 @@ public void ErrorReceiving(int responseTo, ConnectionId connectionId, ObjectId? responseTo, connectionId, serviceId, - state.Stopwatch.Elapsed)); + state.Stopwatch.Elapsed), + skipLogging); } - public void ConnectionFailed(ConnectionId connectionId, ObjectId? serviceId, Exception exception) + public void ConnectionFailed(ConnectionId connectionId, ObjectId? serviceId, Exception exception, bool skipLogging) { if (!_shouldTrackFailed) { @@ -208,28 +212,29 @@ public void ConnectionFailed(ConnectionId connectionId, ObjectId? serviceId, Exc requestId, connectionId, serviceId, - state.Stopwatch.Elapsed)); + state.Stopwatch.Elapsed), + skipLogging); } } } - private void ProcessRequestMessages(Queue messageQueue, ConnectionId connectionId, ObjectId? serviceId, Stream stream, MessageEncoderSettings encoderSettings, Stopwatch stopwatch) + private void ProcessRequestMessages(Queue messageQueue, ConnectionId connectionId, ObjectId? serviceId, Stream stream, MessageEncoderSettings encoderSettings, Stopwatch stopwatch, bool skipLogging) { var message = messageQueue.Dequeue(); switch (message.MessageType) { case MongoDBMessageType.Command: - ProcessCommandRequestMessage((CommandRequestMessage)message, messageQueue, connectionId, serviceId, new CommandMessageBinaryEncoder(stream, encoderSettings), stopwatch); + ProcessCommandRequestMessage((CommandRequestMessage)message, messageQueue, connectionId, serviceId, new CommandMessageBinaryEncoder(stream, encoderSettings), stopwatch, skipLogging); break; case MongoDBMessageType.Query: - ProcessQueryMessage((QueryMessage)message, connectionId, new QueryMessageBinaryEncoder(stream, encoderSettings), stopwatch); + ProcessQueryMessage((QueryMessage)message, connectionId, new QueryMessageBinaryEncoder(stream, encoderSettings), stopwatch, skipLogging); break; default: throw new MongoInternalException("Invalid message type."); } } - private void ProcessCommandRequestMessage(CommandRequestMessage originalMessage, Queue messageQueue, ConnectionId connectionId, ObjectId? serviceId, CommandMessageBinaryEncoder encoder, Stopwatch stopwatch) + private void ProcessCommandRequestMessage(CommandRequestMessage originalMessage, Queue messageQueue, ConnectionId connectionId, ObjectId? serviceId, CommandMessageBinaryEncoder encoder, Stopwatch stopwatch, bool skipLogging) { var requestId = originalMessage.RequestId; var operationId = EventContext.OperationId; @@ -266,7 +271,8 @@ private void ProcessCommandRequestMessage(CommandRequestMessage originalMessage, operationId, requestId, connectionId, - serviceId)); + serviceId), + skipLogging); if (_shouldTrackState) { @@ -283,7 +289,7 @@ private void ProcessCommandRequestMessage(CommandRequestMessage originalMessage, } } - private void ProcessCommandResponseMessage(CommandState state, CommandResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, ObjectId? serviceId, MessageEncoderSettings encoderSettings) + private void ProcessCommandResponseMessage(CommandState state, CommandResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, ObjectId? serviceId, MessageEncoderSettings encoderSettings, bool skipLogging) { var wrappedMessage = message.WrappedMessage; var type0Section = wrappedMessage.Sections.OfType>().Single(); @@ -311,7 +317,8 @@ private void ProcessCommandResponseMessage(CommandState state, CommandResponseMe message.ResponseTo, connectionId, serviceId, - state.Stopwatch.Elapsed)); + state.Stopwatch.Elapsed), + skipLogging); } else { @@ -328,12 +335,13 @@ private void ProcessCommandResponseMessage(CommandState state, CommandResponseMe message.ResponseTo, connectionId, serviceId, - state.Stopwatch.Elapsed)); + state.Stopwatch.Elapsed), + skipLogging); } } } - private void ProcessQueryMessage(QueryMessage originalMessage, ConnectionId connectionId, QueryMessageBinaryEncoder encoder, Stopwatch stopwatch) + private void ProcessQueryMessage(QueryMessage originalMessage, ConnectionId connectionId, QueryMessageBinaryEncoder encoder, Stopwatch stopwatch, bool skipLogging) { var requestId = originalMessage.RequestId; var operationId = EventContext.OperationId; @@ -373,7 +381,8 @@ private void ProcessQueryMessage(QueryMessage originalMessage, ConnectionId conn decodedMessage.CollectionNamespace.DatabaseNamespace, operationId, requestId, - connectionId)); + connectionId), + skipLogging); if (_shouldTrackState) { @@ -403,7 +412,7 @@ private void ProcessQueryMessage(QueryMessage originalMessage, ConnectionId conn } } - private void ProcessReplyMessage(CommandState state, ResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, MessageEncoderSettings encoderSettings) + private void ProcessReplyMessage(CommandState state, ResponseMessage message, IByteBuffer buffer, ConnectionId connectionId, MessageEncoderSettings encoderSettings, bool skipLogging) { state.Stopwatch.Stop(); bool disposeOfDocuments = false; @@ -445,7 +454,8 @@ private void ProcessReplyMessage(CommandState state, ResponseMessage message, IB state.OperationId, replyMessage.ResponseTo, connectionId, - state.Stopwatch.Elapsed)); + state.Stopwatch.Elapsed), + skipLogging); } } else @@ -453,10 +463,10 @@ private void ProcessReplyMessage(CommandState state, ResponseMessage message, IB switch (state.ExpectedResponseType) { case ExpectedResponseType.Command: - ProcessCommandReplyMessage(state, replyMessage, connectionId); + ProcessCommandReplyMessage(state, replyMessage, connectionId, skipLogging); break; case ExpectedResponseType.Query: - ProcessQueryReplyMessage(state, replyMessage, connectionId); + ProcessQueryReplyMessage(state, replyMessage, connectionId, skipLogging); break; } } @@ -470,7 +480,7 @@ private void ProcessReplyMessage(CommandState state, ResponseMessage message, IB } } - private void ProcessCommandReplyMessage(CommandState state, ReplyMessage replyMessage, ConnectionId connectionId) + private void ProcessCommandReplyMessage(CommandState state, ReplyMessage replyMessage, ConnectionId connectionId, bool skipLogging) { BsonDocument reply = replyMessage.Documents[0]; BsonValue ok; @@ -500,7 +510,8 @@ private void ProcessCommandReplyMessage(CommandState state, ReplyMessage replyMessage, ConnectionId connectionId) + private void ProcessQueryReplyMessage(CommandState state, ReplyMessage replyMessage, ConnectionId connectionId, bool skipLogging) { if (_shouldTrackSucceeded) { @@ -546,7 +558,8 @@ private void ProcessQueryReplyMessage(CommandState state, ReplyMessage where T : LogCategories.EventCategory { private readonly EventsPublisher _eventsPublisher; private readonly ILogger _logger; + private readonly EventsLogsFormattingOptions _eventsLogsFormattingOptions; - public EventsLogger(IEventSubscriber eventSubscriber, ILogger logger) + public static EventsLogger Empty { get; } = new EventsLogger(null, null); + + public EventsLogger(IEventSubscriber eventSubscriber, ILogger logger, EventsLogsFormattingOptions eventsLogsFormattingOptions = null) { _logger = logger; _eventsPublisher = eventSubscriber != null ? new EventsPublisher(eventSubscriber) : null; + _eventsLogsFormattingOptions = eventsLogsFormattingOptions ?? new EventsLogsFormattingOptions(0); } public ILogger Logger => _logger; @@ -39,19 +43,22 @@ public bool IsEventTracked() where TEvent : struct, IEvent => private LogLevel GetEventVerbosity() where TEvent : struct, IEvent => StructuredLogsTemplates.GetTemplateProvider(new TEvent().Type).LogLevel; - public void LogAndPublish(TEvent @event) where TEvent : struct, IEvent - => LogAndPublish(null, @event); + public void LogAndPublish(TEvent @event, bool skipLogging = false) where TEvent : struct, IEvent + => LogAndPublish(null, @event, skipLogging); - public void LogAndPublish(Exception exception, TEvent @event) where TEvent : struct, IEvent + public void LogAndPublish(Exception exception, TEvent @event, bool skipLogging = false) where TEvent : struct, IEvent { - var eventTemplateProvider = StructuredLogsTemplates.GetTemplateProvider(@event.Type); - - if (_logger?.IsEnabled(eventTemplateProvider.LogLevel) == true) + if (!skipLogging) { - var @params = eventTemplateProvider.GetParams(@event); - var template = eventTemplateProvider.GetTemplate(@event); + var eventTemplateProvider = StructuredLogsTemplates.GetTemplateProvider(@event.Type); + + if (_logger?.IsEnabled(eventTemplateProvider.LogLevel) == true) + { + var @params = eventTemplateProvider.GetParams(@event, _eventsLogsFormattingOptions); + var template = eventTemplateProvider.GetTemplate(@event); - Log(eventTemplateProvider.LogLevel, template, exception, @params); + Log(eventTemplateProvider.LogLevel, template, exception, @params); + } } _eventsPublisher?.Publish(@event); @@ -63,7 +70,7 @@ public void LogAndPublish(TEvent @event, TArg arg) where TEvent : if (_logger?.IsEnabled(eventTemplateProvider.LogLevel) == true) { - var @params = eventTemplateProvider.GetParams(@event, arg); + var @params = eventTemplateProvider.GetParams(@event, _eventsLogsFormattingOptions, arg); var template = eventTemplateProvider.GetTemplate(@event); Log(eventTemplateProvider.LogLevel, template, exception: null, @params); diff --git a/src/MongoDB.Driver.Core/Core/Logging/EventsLogsFormattingOptions.cs b/src/MongoDB.Driver.Core/Core/Logging/EventsLogsFormattingOptions.cs new file mode 100644 index 00000000000..cf79ddedd56 --- /dev/null +++ b/src/MongoDB.Driver.Core/Core/Logging/EventsLogsFormattingOptions.cs @@ -0,0 +1,29 @@ +/* Copyright 2010-present MongoDB Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +using MongoDB.Driver.Core.Misc; + +namespace MongoDB.Driver.Core.Logging +{ + internal sealed class EventsLogsFormattingOptions + { + public int MaxDocumentSize { get; } + + public EventsLogsFormattingOptions(int maxCommandDocumentSize) + { + MaxDocumentSize = Ensure.IsGreaterThanOrEqualToZero(maxCommandDocumentSize, nameof(maxCommandDocumentSize)); + } + } +} diff --git a/src/MongoDB.Driver.Core/Core/Logging/LoggerExtentions.cs b/src/MongoDB.Driver.Core/Core/Logging/LoggerExtentions.cs index df793971350..d38b1a48287 100644 --- a/src/MongoDB.Driver.Core/Core/Logging/LoggerExtentions.cs +++ b/src/MongoDB.Driver.Core/Core/Logging/LoggerExtentions.cs @@ -27,6 +27,10 @@ public static EventsLogger ToEventsLogger(this ILogger logger, IEventSu where T : LogCategories.EventCategory => new EventsLogger(eventSubscriber, logger); + public static EventsLogger ToEventsLogger(this IEventSubscriber eventSubscriber) + where T : LogCategories.EventCategory => + new EventsLogger(eventSubscriber, null); + public static void LogDebug(this ILogger logger, ClusterId clusterId, string message) { if (logger.IsEnabled(LogLevel.Debug)) diff --git a/src/MongoDB.Driver.Core/Core/Logging/LoggerFactoryCategoryDecorator.cs b/src/MongoDB.Driver.Core/Core/Logging/LoggerFactoryCategoryDecorator.cs index 6e0cfeea1e6..33e88f56732 100644 --- a/src/MongoDB.Driver.Core/Core/Logging/LoggerFactoryCategoryDecorator.cs +++ b/src/MongoDB.Driver.Core/Core/Logging/LoggerFactoryCategoryDecorator.cs @@ -14,6 +14,7 @@ */ using Microsoft.Extensions.Logging; +using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver.Core.Logging @@ -21,12 +22,16 @@ namespace MongoDB.Driver.Core.Logging internal sealed class LoggerFactoryCategoryDecorator : ILoggerFactory { private readonly ILoggerFactory _loggerFactory; + private readonly LoggingSettings _loggingSettings; - public LoggerFactoryCategoryDecorator(ILoggerFactory loggerFactory) + public LoggerFactoryCategoryDecorator(ILoggerFactory loggerFactory, LoggingSettings loggingSettings) { _loggerFactory = Ensure.IsNotNull(loggerFactory, nameof(loggerFactory)); + _loggingSettings = Ensure.IsNotNull(loggingSettings, nameof(loggingSettings)); } + public LoggingSettings LoggingSettings => _loggingSettings; + public void AddProvider(ILoggerProvider provider) => _loggerFactory.AddProvider(provider); public ILogger CreateLogger(string categoryName) => diff --git a/src/MongoDB.Driver.Core/Core/Logging/LoggerFactoryExtentions.cs b/src/MongoDB.Driver.Core/Core/Logging/LoggerFactoryExtentions.cs index f1b0f9421b2..57fd00539a3 100644 --- a/src/MongoDB.Driver.Core/Core/Logging/LoggerFactoryExtentions.cs +++ b/src/MongoDB.Driver.Core/Core/Logging/LoggerFactoryExtentions.cs @@ -20,16 +20,13 @@ namespace MongoDB.Driver.Core.Logging { internal static class LoggerFactoryExtentions { - public static ILoggerFactory DecorateCategories(this ILoggerFactory loggerFactory) => - loggerFactory switch - { - LoggerFactoryCategoryDecorator => loggerFactory, - _ when loggerFactory != null => new LoggerFactoryCategoryDecorator(loggerFactory), - _ => null - }; - public static EventsLogger CreateEventsLogger(this ILoggerFactory loggerFactory, IEventSubscriber eventSubscriber) - where T : LogCategories.EventCategory => - new EventsLogger(eventSubscriber, loggerFactory?.CreateLogger()); + where T : LogCategories.EventCategory + { + var loggingSettings = (loggerFactory as LoggerFactoryCategoryDecorator)?.LoggingSettings; + var eventLogFormattingOptions = loggingSettings != null ? new EventsLogsFormattingOptions(loggingSettings.MaxDocumentSize) : null; + + return new EventsLogger(eventSubscriber, loggerFactory?.CreateLogger(), eventLogFormattingOptions); + } } } diff --git a/src/MongoDB.Driver.Core/Core/Logging/LoggingSettingsExtentions.cs b/src/MongoDB.Driver.Core/Core/Logging/LoggingSettingsExtentions.cs new file mode 100644 index 00000000000..1dcc3fafee3 --- /dev/null +++ b/src/MongoDB.Driver.Core/Core/Logging/LoggingSettingsExtentions.cs @@ -0,0 +1,37 @@ +/* Copyright 2010-present MongoDB Inc. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +using Microsoft.Extensions.Logging; +using MongoDB.Driver.Core.Configuration; + +namespace MongoDB.Driver.Core.Logging +{ + internal static class LoggingSettingsExtentions + { + public static ILoggerFactory ToInternalLoggingFactory(this LoggingSettings loggingSettings) => + loggingSettings?.LoggerFactory switch + { + _ when loggingSettings?.LoggerFactory != null => new LoggerFactoryCategoryDecorator(loggingSettings.LoggerFactory, loggingSettings), + _ => null + }; + + public static ILogger CreateLogger(this LoggingSettings loggingSettings) => + loggingSettings?.LoggerFactory switch + { + _ when loggingSettings?.LoggerFactory != null => new LoggerFactoryCategoryDecorator(loggingSettings.LoggerFactory, loggingSettings).CreateLogger(), + _ => null + }; + } +} diff --git a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplates.cs b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplates.cs index f05929b8cf0..163f0cc4624 100644 --- a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplates.cs +++ b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplates.cs @@ -136,20 +136,20 @@ public static object[] GetParamsOmitNull(ConnectionId connectionId, object arg1, return new object[] { connectionId.ServerId.ClusterId.Value, connectionId.LocalValue, host, port, arg1, arg2, arg3, arg4, arg5, arg6, arg7, ommitableParam }; } - private static void AddTemplateProvider(LogLevel logLevel, string template, Func extractor) where TEvent : struct, IEvent => + private static void AddTemplateProvider(LogLevel logLevel, string template, Func extractor) where TEvent : struct, IEvent => AddTemplateProvider(new LogsTemplateProvider( logLevel, new[] { template }, extractor)); - private static void AddTemplateProvider(LogLevel logLevel, string[] templates, Func extractor, Func templateExtractor) where TEvent : struct, IEvent => + private static void AddTemplateProvider(LogLevel logLevel, string[] templates, Func extractor, Func templateExtractor) where TEvent : struct, IEvent => AddTemplateProvider(new LogsTemplateProvider( logLevel, templates, extractor, templateExtractor)); - private static void AddTemplate(LogLevel logLevel, string template, Func extractor) where TEvent : struct, IEvent => + private static void AddTemplate(LogLevel logLevel, string template, Func extractor) where TEvent : struct, IEvent => AddTemplateProvider(new LogsTemplateProvider( logLevel, new[] { template }, @@ -161,7 +161,7 @@ private static void AddTemplateProvider(LogsTemplateProvider templatePro if (__eventsTemplates[index] != null) { - throw new InvalidOperationException($"Template already registered for {typeof(TEvent)} event"); + throw new InvalidOperationException($"Template already registered for {typeof(TEvent)} event."); } __eventsTemplates[index] = templateProvider; @@ -191,11 +191,11 @@ public LogsTemplateProvider(LogLevel logLevel, string[] templates, Delegate para public string GetTemplate(TEvent @event) where TEvent : struct, IEvent => TemplateExtractor != null ? ((Func)TemplateExtractor)(@event, this) : Templates.First(); - public object[] GetParams(TEvent @event) where TEvent : struct, IEvent => - (ParametersExtractor as Func)(@event); + public object[] GetParams(TEvent @event, EventsLogsFormattingOptions eventsLogsFormattingOptions) where TEvent : struct, IEvent => + (ParametersExtractor as Func)(@event, eventsLogsFormattingOptions); - public object[] GetParams(TEvent @event, TArg arg) where TEvent : struct, IEvent => - (ParametersExtractor as Func)(@event, arg); + public object[] GetParams(TEvent @event, EventsLogsFormattingOptions eventsLogsFormattingOptions, TArg arg) where TEvent : struct, IEvent => + (ParametersExtractor as Func)(@event, eventsLogsFormattingOptions, arg); } } } diff --git a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCluster.cs b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCluster.cs index 7d177308f3f..385e13d51ba 100644 --- a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCluster.cs +++ b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCluster.cs @@ -33,62 +33,62 @@ private static void AddClusterTemplates() AddTemplateProvider( LogLevel.Debug, ClusterCommonParams(), - e => GetParams(e.ClusterId, "Description changed")); + (e, _) => GetParams(e.ClusterId, "Description changed")); AddTemplateProvider( LogLevel.Debug, ClusterCommonParams(), - e => GetParams(e.ClusterId, "Selecting server")); + (e, _) => GetParams(e.ClusterId, "Selecting server")); AddTemplateProvider( LogLevel.Debug, ClusterCommonParams(), - e => GetParams(e.ClusterId, "Selected server")); + (e, _) => GetParams(e.ClusterId, "Selected server")); AddTemplateProvider( LogLevel.Debug, ClusterCommonParams(), - e => GetParams(e.ClusterId, "Selecting server failed")); + (e, _) => GetParams(e.ClusterId, "Selecting server failed")); AddTemplateProvider( LogLevel.Debug, ClusterCommonParams(), - e => GetParams(e.ClusterId, "Cluster closing")); + (e, _) => GetParams(e.ClusterId, "Cluster closing")); AddTemplateProvider( LogLevel.Debug, ClusterCommonParams(), - e => GetParams(e.ClusterId, "Cluster closed")); + (e, _) => GetParams(e.ClusterId, "Cluster closed")); AddTemplateProvider( LogLevel.Debug, ClusterCommonParams(), - e => GetParams(e.ClusterId, "Cluster opening")); + (e, _) => GetParams(e.ClusterId, "Cluster opening")); AddTemplateProvider( LogLevel.Debug, ClusterCommonParams(), - e => GetParams(e.ClusterId, "Cluster opened")); + (e, _) => GetParams(e.ClusterId, "Cluster opened")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ClusterId, e.EndPoint, "Adding server")); + (e, _) => GetParams(e.ClusterId, e.EndPoint, "Adding server")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Added server")); + (e, _) => GetParams(e.ServerId, "Added server")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Removing server")); + (e, _) => GetParams(e.ServerId, "Removing server")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Removed server")); + (e, _) => GetParams(e.ServerId, "Removed server")); } } } diff --git a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCmap.cs b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCmap.cs index 535f3586f55..f3849d855a7 100644 --- a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCmap.cs +++ b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCmap.cs @@ -36,47 +36,47 @@ private static void AddCmapTemplates() AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Connection adding")); + (e, _) => GetParams(e.ServerId, "Connection adding")); AddTemplateProvider( - LogLevel.Debug, - ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Connection checking in")); + LogLevel.Debug, + ConnectionCommonParams(), + (e, _) => GetParams(e.ConnectionId, "Connection checking in")); AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Connection checked in")); + (e, _) => GetParams(e.ConnectionId, "Connection checked in")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Connection checkout started")); + (e, _) => GetParams(e.ServerId, "Connection checkout started")); AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Connection checked out")); + (e, _) => GetParams(e.ConnectionId, "Connection checked out")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(Reason), - e => GetParams(e.ServerId, "Connection checkout failed", e.Reason)); + (e, _) => GetParams(e.ServerId, "Connection checkout failed", e.Reason)); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Connection removing")); + (e, _) => GetParams(e.ServerId, "Connection removing")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Connection removed")); + (e, _) => GetParams(e.ServerId, "Connection removed")); AddTemplate( LogLevel.Debug, CmapCommonParams(MaxIdleTimeMS, WaitQueueTimeoutMS, MinPoolSize, MaxPoolSize, MaxConnecting), - (e, s) => GetParams( + (e, _, s) => GetParams( e.ServerId, "Connection pool opening", s.MaxIdleTime.TotalMilliseconds, @@ -88,7 +88,7 @@ private static void AddCmapTemplates() AddTemplate( LogLevel.Debug, CmapCommonParams(MaxIdleTimeMS, WaitQueueTimeoutMS, MinPoolSize, MaxPoolSize, MaxConnecting), - (e, s) => GetParams( + (e, _, s) => GetParams( e.ServerId, "Connection pool created", s.MaxIdleTime.TotalMilliseconds, @@ -100,27 +100,27 @@ private static void AddCmapTemplates() AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Connection pool ready")); + (e, _) => GetParams(e.ServerId, "Connection pool ready")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(ServiceId), - e => GetParams(e.ServerId, "Connection pool clearing", e.ServiceId)); + (e, _) => GetParams(e.ServerId, "Connection pool clearing", e.ServiceId)); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(ServiceId), - e => GetParams(e.ServerId, "Connection pool cleared", e.ServiceId)); + (e, _) => GetParams(e.ServerId, "Connection pool cleared", e.ServiceId)); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Connection pool closing")); + (e, _) => GetParams(e.ServerId, "Connection pool closing")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Connection pool closed")); + (e, _) => GetParams(e.ServerId, "Connection pool closed")); } } } diff --git a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCommand.cs b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCommand.cs index 0fe014f4e66..62fd6dabdde 100644 --- a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCommand.cs +++ b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesCommand.cs @@ -13,8 +13,10 @@ * limitations under the License. */ +using System; using System.Linq; using Microsoft.Extensions.Logging; +using MongoDB.Bson; using MongoDB.Driver.Core.Events; namespace MongoDB.Driver.Core.Logging @@ -45,7 +47,7 @@ private static void AddCommandTemplates() AddTemplateProvider( LogLevel.Debug, CommandCommonParams(DatabaseName, Command), - e => GetParamsOmitNull( + (e, o) => GetParamsOmitNull( e.ConnectionId, e.ConnectionId.ServerValue, e.RequestId, @@ -53,14 +55,14 @@ private static void AddCommandTemplates() "Command started", e.CommandName, e.DatabaseNamespace.DatabaseName, - e.Command?.ToString(), + CommandDocumentToString(e.Command, o), ommitableParam: e.ServiceId), (e, s) => e.ServiceId == null ? s.Templates[0] : s.Templates[1]); AddTemplateProvider( LogLevel.Debug, CommandCommonParams(DurationMS, Reply), - e => GetParamsOmitNull( + (e, o) => GetParamsOmitNull( e.ConnectionId, e.ConnectionId.ServerValue, e.RequestId, @@ -68,14 +70,14 @@ private static void AddCommandTemplates() "Command succeeded", e.CommandName, e.Duration.TotalMilliseconds, - e.Reply?.ToString(), + CommandDocumentToString(e.Reply, o), ommitableParam: e.ServiceId), (e, s) => e.ServiceId == null ? s.Templates[0] : s.Templates[1]); AddTemplateProvider( LogLevel.Debug, CommandCommonParams(DurationMS, Failure), - e => GetParamsOmitNull( + (e, o) => GetParamsOmitNull( e.ConnectionId, e.ConnectionId.ServerValue, e.RequestId, @@ -83,9 +85,44 @@ private static void AddCommandTemplates() "Command failed", e.CommandName, e.Duration.TotalMilliseconds, - e.Failure?.ToString(), + FormatCommandException(e.Failure, o), ommitableParam: e.ServiceId), (e, s) => e.ServiceId == null ? s.Templates[0] : s.Templates[1]); } + + private static string CommandDocumentToString(BsonDocument document, EventsLogsFormattingOptions eventsLogsFormattingOptions) + { + if (document == null) + { + return null; + } + + return TruncateIfNeeded(document.ToString(), eventsLogsFormattingOptions.MaxDocumentSize); + } + + private static string FormatCommandException(Exception exception, EventsLogsFormattingOptions eventsLogsFormattingOptions) + { + if (exception == null) + { + return null; + } + + var serverResult = (exception as MongoCommandException)?.Result; + var result = exception.ToString(); + + if (serverResult != null) + { + result = $"{exception} server reply: {result}"; + } + else + { + result = exception.ToString(); + } + + return TruncateIfNeeded(result, eventsLogsFormattingOptions.MaxDocumentSize); + } + + private static string TruncateIfNeeded(string str, int length) => + str.Length > length ? str.Substring(0, length) + "..." : str; } } diff --git a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesConnection.cs b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesConnection.cs index 09f4d4ac2f5..34e6a418824 100644 --- a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesConnection.cs +++ b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesConnection.cs @@ -36,72 +36,72 @@ private static void AddConnectionTemplates() AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Connection added")); + (e, _) => GetParams(e.ConnectionId, "Connection added")); AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Connection ready")); + (e, _) => GetParams(e.ConnectionId, "Connection ready")); AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Connection added")); + (e, _) => GetParams(e.ConnectionId, "Connection added")); AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(Reason), - e => GetParams(e.ConnectionId, "Connection opening failed", e.Exception?.ToString())); + (e, _) => GetParams(e.ConnectionId, "Connection opening failed", e.Exception?.ToString())); AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Connection created")); + (e, _) => GetParams(e.ConnectionId, "Connection created")); AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(Reason), - e => GetParams(e.ConnectionId, "Connection failed", e.Exception?.ToString())); + (e, _) => GetParams(e.ConnectionId, "Connection failed", e.Exception?.ToString())); AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(Reason), - e => GetParams(e.ConnectionId, "Connection closing", "Unknown")); + (e, _) => GetParams(e.ConnectionId, "Connection closing", "Unknown")); AddTemplateProvider( LogLevel.Debug, ConnectionCommonParams(Reason), - e => GetParams(e.ConnectionId, "Connection closed", "Unknown")); + (e, _) => GetParams(e.ConnectionId, "Connection closed", "Unknown")); AddTemplateProvider( LogLevel.Trace, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Received")); + (e, _) => GetParams(e.ConnectionId, "Received")); AddTemplateProvider( LogLevel.Trace, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Receiving")); + (e, _) => GetParams(e.ConnectionId, "Receiving")); AddTemplateProvider( LogLevel.Trace, ConnectionCommonParams(Reason), - e => GetParams(e.ConnectionId, "Receiving failed", e.Exception?.ToString())); + (e, _) => GetParams(e.ConnectionId, "Receiving failed", e.Exception?.ToString())); AddTemplateProvider( LogLevel.Trace, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Sending")); + (e, _) => GetParams(e.ConnectionId, "Sending")); AddTemplateProvider( LogLevel.Trace, ConnectionCommonParams(Reason), - e => GetParams(e.ConnectionId, "Sending failed", e.Exception?.ToString())); + (e, _) => GetParams(e.ConnectionId, "Sending failed", e.Exception?.ToString())); AddTemplateProvider( LogLevel.Trace, ConnectionCommonParams(), - e => GetParams(e.ConnectionId, "Sent")); + (e, _) => GetParams(e.ConnectionId, "Sent")); } } } diff --git a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesSdam.cs b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesSdam.cs index 68799d61c8d..68f3f1c3b04 100644 --- a/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesSdam.cs +++ b/src/MongoDB.Driver.Core/Core/Logging/StructuredLogsTemplatesSdam.cs @@ -36,47 +36,47 @@ private static void AddSdamTemplates() AddTemplateProvider( LogLevel.Debug, SdamCommonParams(), - e => GetParams(e.ConnectionId, "Heartbeat started")); + (e, _) => GetParams(e.ConnectionId, "Heartbeat started")); AddTemplateProvider( LogLevel.Debug, SdamCommonParams(), - e => GetParams(e.ConnectionId, "Heartbeat succeeded")); + (e, _) => GetParams(e.ConnectionId, "Heartbeat succeeded")); AddTemplateProvider( LogLevel.Debug, SdamCommonParams(), - e => GetParams(e.ConnectionId, "Heartbeat failed")); + (e, _) => GetParams(e.ConnectionId, "Heartbeat failed")); AddTemplateProvider( LogLevel.Debug, Concat(new[] { Message }), - e => new[] { e.Message }); + (e, _) => new[] { e.Message }); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Server opening")); + (e, _) => GetParams(e.ServerId, "Server opening")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Server opened")); + (e, _) => GetParams(e.ServerId, "Server opened")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Server closing")); + (e, _) => GetParams(e.ServerId, "Server closing")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(), - e => GetParams(e.ServerId, "Server closed")); + (e, _) => GetParams(e.ServerId, "Server closed")); AddTemplateProvider( LogLevel.Debug, CmapCommonParams(Description), - e => GetParams(e.ServerId, "Description changed", e.NewDescription)); + (e, _) => GetParams(e.ServerId, "Description changed", e.NewDescription)); } } } diff --git a/src/MongoDB.Driver.Core/Core/Servers/DefaultServer.cs b/src/MongoDB.Driver.Core/Core/Servers/DefaultServer.cs index f7aa6c37a18..d6456260142 100644 --- a/src/MongoDB.Driver.Core/Core/Servers/DefaultServer.cs +++ b/src/MongoDB.Driver.Core/Core/Servers/DefaultServer.cs @@ -25,7 +25,6 @@ using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.ConnectionPools; using MongoDB.Driver.Core.Connections; -using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.Misc; @@ -60,9 +59,8 @@ public DefaultServer( EndPoint endPoint, IConnectionPoolFactory connectionPoolFactory, IServerMonitorFactory monitorFactory, - IEventSubscriber eventSubscriber, ServerApi serverApi, - ILogger logger) + EventsLogger eventsLogger) : base( clusterId, clusterClock, @@ -72,9 +70,8 @@ public DefaultServer( settings, endPoint, connectionPoolFactory, - eventSubscriber, serverApi, - logger) + eventsLogger) { _monitor = Ensure.IsNotNull(monitorFactory, nameof(monitorFactory)).Create(ServerId, endPoint); _baseDescription = _currentDescription = new ServerDescription(ServerId, endPoint, reasonChanged: "ServerInitialDescription", heartbeatInterval: settings.HeartbeatInterval); diff --git a/src/MongoDB.Driver.Core/Core/Servers/LoadBalancedServer.cs b/src/MongoDB.Driver.Core/Core/Servers/LoadBalancedServer.cs index e1ba284b3ff..18a7d8927c3 100644 --- a/src/MongoDB.Driver.Core/Core/Servers/LoadBalancedServer.cs +++ b/src/MongoDB.Driver.Core/Core/Servers/LoadBalancedServer.cs @@ -38,9 +38,8 @@ public LoadBalancedServer( ServerSettings serverSettings, EndPoint endPoint, IConnectionPoolFactory connectionPoolFactory, - IEventSubscriber eventSubscriber, ServerApi serverApi, - ILogger logger) + EventsLogger eventsLogger) : base( clusterId, clusterClock, @@ -52,9 +51,8 @@ public LoadBalancedServer( serverSettings, endPoint, connectionPoolFactory, - eventSubscriber, serverApi, - logger) + eventsLogger) { _baseDescription = _currentDescription = new ServerDescription(ServerId, endPoint, reasonChanged: "ServerInitialDescription"); } diff --git a/src/MongoDB.Driver.Core/Core/Servers/Server.cs b/src/MongoDB.Driver.Core/Core/Servers/Server.cs index a0062c4e408..95094d6c26d 100644 --- a/src/MongoDB.Driver.Core/Core/Servers/Server.cs +++ b/src/MongoDB.Driver.Core/Core/Servers/Server.cs @@ -19,7 +19,6 @@ using System.Net; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; @@ -71,9 +70,8 @@ public Server( ServerSettings settings, EndPoint endPoint, IConnectionPoolFactory connectionPoolFactory, - IEventSubscriber eventSubscriber, ServerApi serverApi, - ILogger logger) + EventsLogger eventsLogger) { ClusterConnectionModeHelper.EnsureConnectionModeValuesAreValid(clusterConnectionMode, connectionModeSwitch, directConnection); @@ -83,7 +81,6 @@ public Server( _directConnection = directConnection; _settings = Ensure.IsNotNull(settings, nameof(settings)); _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint)); - Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber)); _serverId = new ServerId(clusterId, endPoint); _connectionPool = Ensure.IsNotNull(connectionPoolFactory, nameof(connectionPoolFactory)).CreateConnectionPool(_serverId, endPoint, this); @@ -91,7 +88,7 @@ public Server( _serverApi = serverApi; _outstandingOperationsCount = 0; - _eventsLogger = logger.ToEventsLogger(eventSubscriber); + _eventsLogger = Ensure.IsNotNull(eventsLogger, nameof(eventsLogger)); } // events diff --git a/src/MongoDB.Driver.Core/Core/Servers/ServerFactory.cs b/src/MongoDB.Driver.Core/Core/Servers/ServerFactory.cs index 0db720f4944..29070faa210 100644 --- a/src/MongoDB.Driver.Core/Core/Servers/ServerFactory.cs +++ b/src/MongoDB.Driver.Core/Core/Servers/ServerFactory.cs @@ -78,9 +78,8 @@ public IClusterableServer CreateServer(ClusterType clusterType, ClusterId cluste _settings, endPoint, _connectionPoolFactory, - _eventSubscriber, _serverApi, - _loggerFactory?.CreateLogger()), + _loggerFactory.CreateEventsLogger(_eventSubscriber)), _ => new DefaultServer( @@ -93,9 +92,8 @@ public IClusterableServer CreateServer(ClusterType clusterType, ClusterId cluste endPoint, _connectionPoolFactory, _serverMonitorFactory, - _eventSubscriber, _serverApi, - _loggerFactory?.CreateLogger()) + _loggerFactory.CreateEventsLogger(_eventSubscriber)) }; } } diff --git a/src/MongoDB.Driver.Core/MongoInternalDefaults.cs b/src/MongoDB.Driver.Core/MongoInternalDefaults.cs index 43e69374426..2ae113b5cca 100644 --- a/src/MongoDB.Driver.Core/MongoInternalDefaults.cs +++ b/src/MongoDB.Driver.Core/MongoInternalDefaults.cs @@ -17,6 +17,11 @@ namespace MongoDB.Driver { internal static class MongoInternalDefaults { + public static class Logging + { + public const int MaxDocumentSize = 1000; + } + public static class ConnectionPool { public const int MaxConnecting = 2; diff --git a/src/MongoDB.Driver.Legacy/MongoServerSettings.cs b/src/MongoDB.Driver.Legacy/MongoServerSettings.cs index b4394791e07..71c4e9bdd43 100644 --- a/src/MongoDB.Driver.Legacy/MongoServerSettings.cs +++ b/src/MongoDB.Driver.Legacy/MongoServerSettings.cs @@ -1209,7 +1209,7 @@ internal ClusterKey ToClusterKey() _ipv6, loadBalanced: false, // not supported for legacy, so turn it off _localThreshold, - loggerFactory: null, + loggingSettings: null, maxConnecting: MongoInternalDefaults.ConnectionPool.MaxConnecting, _maxConnectionIdleTime, _maxConnectionLifeTime, diff --git a/src/MongoDB.Driver/ClusterKey.cs b/src/MongoDB.Driver/ClusterKey.cs index 48ce367036b..7decd94f8ea 100644 --- a/src/MongoDB.Driver/ClusterKey.cs +++ b/src/MongoDB.Driver/ClusterKey.cs @@ -44,7 +44,7 @@ internal class ClusterKey private readonly bool _ipv6; private readonly bool _loadBalanced; private readonly TimeSpan _localThreshold; - private readonly ILoggerFactory _loggerFactory; + private readonly LoggingSettings _loggingSettings; private readonly int _maxConnecting; private readonly TimeSpan _maxConnectionIdleTime; private readonly TimeSpan _maxConnectionLifeTime; @@ -84,7 +84,7 @@ public ClusterKey( bool ipv6, bool loadBalanced, TimeSpan localThreshold, - ILoggerFactory loggerFactory, + LoggingSettings loggingSettings, int maxConnecting, TimeSpan maxConnectionIdleTime, TimeSpan maxConnectionLifeTime, @@ -122,7 +122,7 @@ public ClusterKey( _ipv6 = ipv6; _loadBalanced = loadBalanced; _localThreshold = localThreshold; - _loggerFactory = loggerFactory; + _loggingSettings = loggingSettings; _maxConnecting = maxConnecting; _maxConnectionIdleTime = maxConnectionIdleTime; _maxConnectionLifeTime = maxConnectionLifeTime; @@ -186,7 +186,7 @@ public bool? DirectConnection public bool IPv6 { get { return _ipv6; } } public bool LoadBalanced => _loadBalanced; public TimeSpan LocalThreshold { get { return _localThreshold; } } - public ILoggerFactory LoggerFactory { get { return _loggerFactory; } } + public LoggingSettings LoggingSettings { get { return _loggingSettings; } } public int MaxConnecting{ get { return _maxConnecting; } } public TimeSpan MaxConnectionIdleTime { get { return _maxConnectionIdleTime; } } public TimeSpan MaxConnectionLifeTime { get { return _maxConnectionLifeTime; } } @@ -241,7 +241,7 @@ public override bool Equals(object obj) _ipv6 == rhs._ipv6 && _loadBalanced == rhs._loadBalanced && _localThreshold == rhs._localThreshold && - _loggerFactory == rhs._loggerFactory && + _loggingSettings == rhs._loggingSettings && _maxConnecting == rhs._maxConnecting && _maxConnectionIdleTime == rhs._maxConnectionIdleTime && _maxConnectionLifeTime == rhs._maxConnectionLifeTime && diff --git a/src/MongoDB.Driver/ClusterRegistry.cs b/src/MongoDB.Driver/ClusterRegistry.cs index 409fec34dd1..b947f067828 100644 --- a/src/MongoDB.Driver/ClusterRegistry.cs +++ b/src/MongoDB.Driver/ClusterRegistry.cs @@ -62,7 +62,7 @@ private ICluster CreateCluster(ClusterKey clusterKey) .ConfigureConnection(settings => ConfigureConnection(settings, clusterKey)) .ConfigureTcp(settings => ConfigureTcp(settings, clusterKey)) .ConfigureSdamLogging(settings => ConfigureSdamLogging(settings, clusterKey)) - .ConfigureLoggingFactory(_ => clusterKey.LoggerFactory); + .ConfigureLoggingSettings(_ => clusterKey.LoggingSettings); #pragma warning restore CS0618 // Type or member is obsolete if (clusterKey.UseTls) diff --git a/src/MongoDB.Driver/MongoClientSettings.cs b/src/MongoDB.Driver/MongoClientSettings.cs index c1fefb57674..1cc583f7f4e 100644 --- a/src/MongoDB.Driver/MongoClientSettings.cs +++ b/src/MongoDB.Driver/MongoClientSettings.cs @@ -18,11 +18,9 @@ using System.Collections.ObjectModel; using System.Linq; using System.Text; -using Microsoft.Extensions.Logging; using MongoDB.Bson; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; -using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Encryption; using MongoDB.Driver.Linq; @@ -55,7 +53,7 @@ public class MongoClientSettings : IEquatable, IInheritable private LinqProvider _linqProvider; private bool _loadBalanced; private TimeSpan _localThreshold; - private ILoggerFactory _loggerFactory; + private LoggingSettings _loggingSettings; private int _maxConnecting; private TimeSpan _maxConnectionIdleTime; private TimeSpan _maxConnectionLifeTime; @@ -452,16 +450,15 @@ public TimeSpan LocalThreshold } /// - /// Gets or sets the logger factory + /// Gets or sets the logging settings /// - [CLSCompliant(false)] - public ILoggerFactory LoggerFactory + public LoggingSettings LoggingSettings { - get { return _loggerFactory; } + get { return _loggingSettings; } set { if (_isFrozen) { throw new InvalidOperationException("MongoClientSettings is frozen."); } - _loggerFactory = value.DecorateCategories(); + _loggingSettings = value; } } @@ -1020,7 +1017,7 @@ public MongoClientSettings Clone() clone._linqProvider = _linqProvider; clone._loadBalanced = _loadBalanced; clone._localThreshold = _localThreshold; - clone._loggerFactory = _loggerFactory; + clone._loggingSettings = _loggingSettings; clone._maxConnecting = _maxConnecting; clone._maxConnectionIdleTime = _maxConnectionIdleTime; clone._maxConnectionLifeTime = _maxConnectionLifeTime; @@ -1089,7 +1086,7 @@ public override bool Equals(object obj) _linqProvider == rhs._linqProvider && _loadBalanced == rhs._loadBalanced && _localThreshold == rhs._localThreshold && - object.ReferenceEquals(_loggerFactory, rhs._loggerFactory) && + _loggingSettings == rhs._loggingSettings && _maxConnecting == rhs._maxConnecting && _maxConnectionIdleTime == rhs._maxConnectionIdleTime && _maxConnectionLifeTime == rhs._maxConnectionLifeTime && @@ -1311,7 +1308,7 @@ internal ClusterKey ToClusterKey() _ipv6, _loadBalanced, _localThreshold, - _loggerFactory, + _loggingSettings, _maxConnecting, _maxConnectionIdleTime, _maxConnectionLifeTime, diff --git a/tests/MongoDB.Driver.Core.TestHelpers/Logging/ILoggingService.cs b/tests/MongoDB.Driver.Core.TestHelpers/Logging/ILoggingService.cs index 62cfbf4f6c4..7be0301efb9 100644 --- a/tests/MongoDB.Driver.Core.TestHelpers/Logging/ILoggingService.cs +++ b/tests/MongoDB.Driver.Core.TestHelpers/Logging/ILoggingService.cs @@ -13,13 +13,13 @@ * limitations under the License. */ -using Microsoft.Extensions.Logging; +using MongoDB.Driver.Core.Configuration; namespace MongoDB.Driver.Core.TestHelpers.Logging { public interface ILoggingService { - public ILoggerFactory LoggerFactory { get; } + public LoggingSettings LoggingSettings { get; } public LogEntry[] Logs { get; } } } diff --git a/tests/MongoDB.Driver.Core.TestHelpers/Logging/LogEntry.cs b/tests/MongoDB.Driver.Core.TestHelpers/Logging/LogEntry.cs index fdef0dc4ef3..5f1fae09002 100644 --- a/tests/MongoDB.Driver.Core.TestHelpers/Logging/LogEntry.cs +++ b/tests/MongoDB.Driver.Core.TestHelpers/Logging/LogEntry.cs @@ -54,6 +54,9 @@ public LogEntry(LogLevel logLevel, public object GetParameter(string key) => State.FirstOrDefault(s => s.Key == key).Value; + public T GetParameter(string key) where T : class => + GetParameter(key) as T; + public override string ToString() => $"{Timestamp.ToString("hh:mm:ss.FFFFFFF")}_{LogLevel}<{Category}> {FormattedMessage}"; } diff --git a/tests/MongoDB.Driver.Core.TestHelpers/Logging/LoggableTestClass.cs b/tests/MongoDB.Driver.Core.TestHelpers/Logging/LoggableTestClass.cs index 8068c3d0a66..9e2b6dbc75a 100644 --- a/tests/MongoDB.Driver.Core.TestHelpers/Logging/LoggableTestClass.cs +++ b/tests/MongoDB.Driver.Core.TestHelpers/Logging/LoggableTestClass.cs @@ -18,6 +18,8 @@ using System.Linq; using Microsoft.Diagnostics.Runtime; using Microsoft.Extensions.Logging; +using MongoDB.Driver.Core.Configuration; +using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.Misc; using Xunit.Abstractions; @@ -40,7 +42,8 @@ public LoggableTestClass(ITestOutputHelper output, bool includeAllCategories = f Accumulator = new XUnitOutputAccumulator(logCategoriesToExclude); MinLogLevel = LogLevel.Warning; - LoggerFactory = new XUnitLoggerFactory(Accumulator).DecorateCategories(); + LoggingSettings = new LoggingSettings(new XUnitLoggerFactory(Accumulator), 10000); // Spec test require larger truncation default + LoggerFactory = LoggingSettings.ToInternalLoggingFactory(); Logger = LoggerFactory.CreateLogger(); } @@ -51,9 +54,12 @@ public LoggableTestClass(ITestOutputHelper output, bool includeAllCategories = f protected LogLevel MinLogLevel { get; set; } public ILoggerFactory LoggerFactory { get; } + public LoggingSettings LoggingSettings { get; } public LogEntry[] Logs => Accumulator.Logs; protected ILogger CreateLogger() => LoggerFactory.CreateLogger(); + private protected EventsLogger CreateEventsLogger(IEventSubscriber eventSubscriber) where TCategory : LogCategories.EventCategory => + LoggerFactory.CreateEventsLogger(eventSubscriber); protected virtual void DisposeInternal() { } diff --git a/tests/MongoDB.Driver.Core.TestHelpers/Logging/NullLoggingService.cs b/tests/MongoDB.Driver.Core.TestHelpers/Logging/NullLoggingService.cs index 7309b5caa13..9f171ab857b 100644 --- a/tests/MongoDB.Driver.Core.TestHelpers/Logging/NullLoggingService.cs +++ b/tests/MongoDB.Driver.Core.TestHelpers/Logging/NullLoggingService.cs @@ -13,8 +13,8 @@ * limitations under the License. */ -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; +using MongoDB.Driver.Core.Configuration; namespace MongoDB.Driver.Core.TestHelpers.Logging { @@ -24,7 +24,7 @@ public sealed class NullLoggingService : ILoggingService private NullLoggingService() { } - public ILoggerFactory LoggerFactory { get; } = NullLoggerFactory.Instance; + public LoggingSettings LoggingSettings { get; } = new LoggingSettings(NullLoggerFactory.Instance); public LogEntry[] Logs { get; } = new LogEntry[0]; } } diff --git a/tests/MongoDB.Driver.Core.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs index 9a637686810..3a8d37a9e33 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs @@ -46,6 +46,7 @@ public class ExclusiveConnectionPoolTests : LoggableTestClass private Mock _mockConnectionExceptionHandler; private DnsEndPoint _endPoint; private EventCapturer _capturedEvents; + private EventsLogger _eventsLoggger; private ServerId _serverId; private ConnectionPoolSettings _settings; private ExclusiveConnectionPool _subject; @@ -56,6 +57,7 @@ public ExclusiveConnectionPoolTests(ITestOutputHelper output) : base(output) _mockConnectionExceptionHandler = new Mock(); _endPoint = new DnsEndPoint("localhost", 27017); _capturedEvents = new EventCapturer(); + _eventsLoggger = _capturedEvents.ToEventsLogger(); _serverId = new ServerId(new ClusterId(), _endPoint); _mockConnectionFactory.Setup(f => f.ConnectionSettings).Returns(() => new ConnectionSettings()); @@ -78,7 +80,7 @@ public ExclusiveConnectionPoolTests(ITestOutputHelper output) : base(output) [Fact] public void Constructor_should_throw_when_serverId_is_null() { - Action act = () => new ExclusiveConnectionPool(null, _endPoint, _settings, _mockConnectionFactory.Object, _capturedEvents, _mockConnectionExceptionHandler.Object, null); + Action act = () => new ExclusiveConnectionPool(null, _endPoint, _settings, _mockConnectionFactory.Object, _mockConnectionExceptionHandler.Object, _eventsLoggger); act.ShouldThrow(); } @@ -86,7 +88,7 @@ public void Constructor_should_throw_when_serverId_is_null() [Fact] public void Constructor_should_throw_when_endPoint_is_null() { - Action act = () => new ExclusiveConnectionPool(_serverId, null, _settings, _mockConnectionFactory.Object, _capturedEvents, _mockConnectionExceptionHandler.Object, null); + Action act = () => new ExclusiveConnectionPool(_serverId, null, _settings, _mockConnectionFactory.Object, _mockConnectionExceptionHandler.Object, _eventsLoggger); act.ShouldThrow(); } @@ -94,7 +96,7 @@ public void Constructor_should_throw_when_endPoint_is_null() [Fact] public void Constructor_should_throw_when_settings_is_null() { - Action act = () => new ExclusiveConnectionPool(_serverId, _endPoint, null, _mockConnectionFactory.Object, _capturedEvents, _mockConnectionExceptionHandler.Object, null); + Action act = () => new ExclusiveConnectionPool(_serverId, _endPoint, null, _mockConnectionFactory.Object, _mockConnectionExceptionHandler.Object, _eventsLoggger); act.ShouldThrow(); } @@ -102,15 +104,15 @@ public void Constructor_should_throw_when_settings_is_null() [Fact] public void Constructor_should_throw_when_connectionFactory_is_null() { - Action act = () => new ExclusiveConnectionPool(_serverId, _endPoint, _settings, null, _capturedEvents, _mockConnectionExceptionHandler.Object, null); + Action act = () => new ExclusiveConnectionPool(_serverId, _endPoint, _settings, null, _mockConnectionExceptionHandler.Object, _eventsLoggger); act.ShouldThrow(); } [Fact] - public void Constructor_should_throw_when_eventSubscriber_is_null() + public void Constructor_should_throw_when_eventLogger_is_null() { - Action act = () => new ExclusiveConnectionPool(_serverId, _endPoint, _settings, _mockConnectionFactory.Object, null, _mockConnectionExceptionHandler.Object, null); + Action act = () => new ExclusiveConnectionPool(_serverId, _endPoint, _settings, _mockConnectionFactory.Object, _mockConnectionExceptionHandler.Object, null); act.ShouldThrow(); } @@ -207,7 +209,7 @@ public void AcquireConnection_should_iterate_over_all_dormant_connections() [Fact] public void Constructor_should_throw_when_exceptionHandler_is_null() { - Action act = () => new ExclusiveConnectionPool(_serverId, _endPoint, _settings, _mockConnectionFactory.Object, _capturedEvents, null, null); + Action act = () => new ExclusiveConnectionPool(_serverId, _endPoint, _settings, _mockConnectionFactory.Object, null, _eventsLoggger); act.ShouldThrow(); } @@ -1705,9 +1707,8 @@ private ExclusiveConnectionPool CreateSubject( _endPoint, connectionPoolSettings ?? _settings, connectionFactory ?? _mockConnectionFactory.Object, - eventCapturer ?? _capturedEvents, connectionExceptionHandler ?? _mockConnectionExceptionHandler.Object, - CreateLogger()); + (eventCapturer ?? _capturedEvents).ToEventsLogger()); } private void InitializeAndWait(ExclusiveConnectionPool pool = null, ConnectionPoolSettings poolSettings = null) diff --git a/tests/MongoDB.Driver.Core.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs index 80ec3a99485..6d4c6d3db49 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs @@ -27,6 +27,7 @@ using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Helpers; +using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.Servers; using Moq; using Xunit; @@ -224,9 +225,8 @@ private ExclusiveConnectionPool CreatePool( __endPoint, new ConnectionPoolSettings(maintenanceInterval: maintenanceInterval.GetValueOrDefault(defaultValue: __dummyInterval), minConnections: minPoolSize), mockConnectionFactory.Object, - eventCapturer ?? Mock.Of(), Mock.Of(), - null); + eventCapturer.ToEventsLogger()); exclusiveConnectionPool.Initialize(); exclusiveConnectionPool.SetReady(); // MaintenanceHelper is started diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Helpers/MockClusterableServerFactory.cs b/tests/MongoDB.Driver.Core.Tests/Core/Helpers/MockClusterableServerFactory.cs index 09d53e4cf2d..d461ad57c18 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Helpers/MockClusterableServerFactory.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Helpers/MockClusterableServerFactory.cs @@ -129,9 +129,8 @@ IClusterableServer CreateServer(ClusterType clusterType, IConnectionPoolFactory new ServerSettings(), endPoint, connectionPoolFactory, - _eventSubscriber, serverApi: null, - _loggerFactory.CreateLogger()); + _loggerFactory.CreateEventsLogger(_eventSubscriber)); default: return new DefaultServer( clusterId, @@ -145,9 +144,8 @@ IClusterableServer CreateServer(ClusterType clusterType, IConnectionPoolFactory endPoint, connectionPoolFactory, serverMonitorFactory, - _eventSubscriber, serverApi: null, - _loggerFactory.CreateLogger()); + _loggerFactory.CreateEventsLogger(_eventSubscriber)); } } } diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Logging/LoggerFactoryCategoryDecoratorTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Logging/LoggerFactoryCategoryDecoratorTests.cs index 1985feadd5c..96a8f1712cd 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Logging/LoggerFactoryCategoryDecoratorTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Logging/LoggerFactoryCategoryDecoratorTests.cs @@ -14,6 +14,7 @@ */ using Microsoft.Extensions.Logging; +using MongoDB.Driver.Core.Configuration; using Moq; using Xunit; @@ -42,7 +43,8 @@ public class LoggerFactoryCategoryDecoratorTests internal void DecorateCategories_should_return_correct_category(string providedCategory, string expectedCatergory) { var underlyingFactory = new Mock(); - var decoratedFactory = underlyingFactory.Object.DecorateCategories(); + var loggingSettings = new LoggingSettings(underlyingFactory.Object); + var decoratedFactory = loggingSettings.ToInternalLoggingFactory(); decoratedFactory.CreateLogger(providedCategory); underlyingFactory.Verify(f => f.CreateLogger(expectedCatergory), Times.Once); diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Servers/LoadBalancedServerTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Servers/LoadBalancedServerTests.cs index f4e857978b4..42fe4479de5 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Servers/LoadBalancedServerTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Servers/LoadBalancedServerTests.cs @@ -32,6 +32,7 @@ using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.TestHelpers; using MongoDB.Driver.Core.TestHelpers.Logging; +using MongoDB.Driver.Specifications.connection_monitoring_and_pooling; using Moq; using Xunit; using Xunit.Abstractions; @@ -47,6 +48,7 @@ public class LoadBalancedTests : LoggableTestClass private Mock _mockConnectionPoolFactory; private EndPoint _endPoint; private EventCapturer _capturedEvents; + private EventsLogger _eventsLoggger; private ServerApi _serverApi; private ServerSettings _settings; private LoadBalancedServer _subject; @@ -68,10 +70,11 @@ public LoadBalancedTests(ITestOutputHelper output) : base(output) .Returns(_mockConnectionPool.Object); _capturedEvents = new EventCapturer(); + _eventsLoggger = _capturedEvents.ToEventsLogger(); _serverApi = new ServerApi(ServerApiVersion.V1, true, true); _settings = new ServerSettings(heartbeatInterval: Timeout.InfiniteTimeSpan); - _subject = new LoadBalancedServer(_clusterId, _clusterClock, _settings, _endPoint, _mockConnectionPoolFactory.Object, _capturedEvents, _serverApi, CreateLogger()); + _subject = new LoadBalancedServer(_clusterId, _clusterClock, _settings, _endPoint, _mockConnectionPoolFactory.Object, _serverApi, _eventsLoggger); _connectionId = new ConnectionId(_subject.ServerId); } @@ -100,13 +103,13 @@ public void ChannelFork_should_not_affect_operations_count([Values(false, true)] [Fact] public void Constructor_should_not_throw_when_serverApi_is_null() { - _ = new LoadBalancedServer(_clusterId, _clusterClock, _settings, _endPoint, _mockConnectionPoolFactory.Object, _capturedEvents, serverApi: null, null); + _ = new LoadBalancedServer(_clusterId, _clusterClock, _settings, _endPoint, _mockConnectionPoolFactory.Object, serverApi: null, _capturedEvents.ToEventsLogger()); } [Fact] public void Constructor_should_throw_when_settings_is_null() { - var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, _clusterClock, serverSettings: null, _endPoint, _mockConnectionPoolFactory.Object, _capturedEvents, _serverApi, null)); + var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, _clusterClock, serverSettings: null, _endPoint, _mockConnectionPoolFactory.Object, _serverApi, _eventsLoggger)); exception.Should().BeOfType(); } @@ -114,7 +117,7 @@ public void Constructor_should_throw_when_settings_is_null() [Fact] public void Constructor_should_throw_when_clusterId_is_null() { - var exception = Record.Exception(() => new LoadBalancedServer(clusterId: null, _clusterClock, serverSettings: _settings, _endPoint, _mockConnectionPoolFactory.Object, _capturedEvents, _serverApi, null)); + var exception = Record.Exception(() => new LoadBalancedServer(clusterId: null, _clusterClock, serverSettings: _settings, _endPoint, _mockConnectionPoolFactory.Object, _serverApi, _eventsLoggger)); exception.Should().BeOfType(); } @@ -122,7 +125,7 @@ public void Constructor_should_throw_when_clusterId_is_null() [Fact] public void Constructor_should_throw_when_clusterClock_is_null() { - var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, clusterClock: null, serverSettings: _settings, _endPoint, _mockConnectionPoolFactory.Object, _capturedEvents, _serverApi, null)); + var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, clusterClock: null, serverSettings: _settings, _endPoint, _mockConnectionPoolFactory.Object, _serverApi, _eventsLoggger)); exception.Should().BeOfType(); } @@ -130,7 +133,7 @@ public void Constructor_should_throw_when_clusterClock_is_null() [Fact] public void Constructor_should_throw_when_endPoint_is_null() { - var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, _clusterClock, serverSettings: _settings, endPoint: null, _mockConnectionPoolFactory.Object, _capturedEvents, _serverApi, null)); + var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, _clusterClock, serverSettings: _settings, endPoint: null, _mockConnectionPoolFactory.Object, _serverApi, _eventsLoggger)); exception.Should().BeOfType(); } @@ -138,15 +141,15 @@ public void Constructor_should_throw_when_endPoint_is_null() [Fact] public void Constructor_should_throw_when_connectionPoolFactory_is_null() { - var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, _clusterClock, serverSettings: _settings, _endPoint, connectionPoolFactory: null, _capturedEvents, _serverApi, null)); + var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, _clusterClock, serverSettings: _settings, _endPoint, connectionPoolFactory: null, _serverApi, _eventsLoggger)); exception.Should().BeOfType(); } [Fact] - public void Constructor_should_throw_when_eventSubscriber_is_null() + public void Constructor_should_throw_when_eventsLogger_is_null() { - var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, _clusterClock, serverSettings: _settings, _endPoint, _mockConnectionPoolFactory.Object, eventSubscriber: null, _serverApi, null)); + var exception = Record.Exception(() => new LoadBalancedServer(_clusterId, _clusterClock, serverSettings: _settings, _endPoint, _mockConnectionPoolFactory.Object, _serverApi, eventsLogger: null)); exception.Should().BeOfType(); } @@ -199,9 +202,8 @@ public void GetChannel_should_clear_connection_pool_when_opening_connection_thro _settings, _endPoint, mockConnectionPoolFactory.Object, - _capturedEvents, _serverApi, - CreateLogger()); + _eventsLoggger); server.Initialize(); var exception = Record.Exception(() => @@ -343,21 +345,23 @@ public void GetChannel_should_not_update_topology_and_clear_connection_pool_on_M var openConnectionException = new MongoConnectionException(connectionId, "Oops", new IOException("Cry", innerMostException)); var mockConnection = new Mock(); + mockConnection.Setup(c => c.ConnectionId).Returns(connectionId); mockConnection.Setup(c => c.Open(It.IsAny())).Throws(openConnectionException); mockConnection.Setup(c => c.OpenAsync(It.IsAny())).ThrowsAsync(openConnectionException); var connectionFactory = new Mock(); connectionFactory.Setup(cf => cf.CreateConnection(serverId, _endPoint)).Returns(mockConnection.Object); + connectionFactory.Setup(cf => cf.ConnectionSettings).Returns(new ConnectionSettings()); var connectionPoolSettings = new ConnectionPoolSettings(); - var connectionPool = new ExclusiveConnectionPool(serverId, _endPoint, connectionPoolSettings, connectionFactory.Object, new EventAggregator(), mockConnectionExceptionHandler.Object, null); + var connectionPool = new ExclusiveConnectionPool(serverId, _endPoint, connectionPoolSettings, connectionFactory.Object, mockConnectionExceptionHandler.Object, CreateLogger().ToEventsLogger(null)); var mockConnectionPoolFactory = new Mock(); mockConnectionPoolFactory .Setup(f => f.CreateConnectionPool(It.IsAny(), _endPoint, It.IsAny())) .Returns(connectionPool); - var subject = new LoadBalancedServer(_clusterId, _clusterClock, _settings, _endPoint, mockConnectionPoolFactory.Object, _capturedEvents, _serverApi, CreateLogger()); + var subject = new LoadBalancedServer(_clusterId, _clusterClock, _settings, _endPoint, mockConnectionPoolFactory.Object, _serverApi, _eventsLoggger); subject.Initialize(); IChannelHandle channel = null; @@ -470,9 +474,8 @@ private Server SetupServer(bool exceptionOnConnectionOpen, bool exceptionOnConne _settings, _endPoint, mockConnectionPoolFactory.Object, - _capturedEvents, _serverApi, - CreateLogger()); + _eventsLoggger); server.Initialize(); return server; diff --git a/tests/MongoDB.Driver.Core.Tests/Core/Servers/ServerTests.cs b/tests/MongoDB.Driver.Core.Tests/Core/Servers/ServerTests.cs index 7d33b4853c6..f64599b1750 100644 --- a/tests/MongoDB.Driver.Core.Tests/Core/Servers/ServerTests.cs +++ b/tests/MongoDB.Driver.Core.Tests/Core/Servers/ServerTests.cs @@ -60,6 +60,7 @@ public class ServerTests : LoggableTestClass private Mock _mockConnectionPoolFactory; private EndPoint _endPoint; private EventCapturer _capturedEvents; + private EventsLogger _eventsLoggger; private Mock _mockServerMonitor; private Mock _mockServerMonitorFactory; private ServerApi _serverApi; @@ -91,10 +92,11 @@ public ServerTests(ITestOutputHelper output) : base(output) _mockServerMonitorFactory.Setup(f => f.Create(It.IsAny(), _endPoint)).Returns(_mockServerMonitor.Object); _capturedEvents = new EventCapturer(); + _eventsLoggger = CreateLogger().ToEventsLogger(_capturedEvents); _serverApi = new ServerApi(ServerApiVersion.V1, true, true); _settings = new ServerSettings(heartbeatInterval: Timeout.InfiniteTimeSpan); - _subject = new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _capturedEvents, _serverApi, CreateLogger()); + _subject = new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _serverApi, _eventsLoggger); _connectionId = new ConnectionId(_subject.ServerId); } @@ -128,7 +130,7 @@ public void ChannelFork_should_not_affect_operations_count([Values(false, true)] [Fact] public void Constructor_should_not_throw_when_serverApi_is_null() { - Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _capturedEvents, null, null); + Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, null, _eventsLoggger); act.ShouldNotThrow(); } @@ -136,7 +138,7 @@ public void Constructor_should_not_throw_when_serverApi_is_null() [Fact] public void Constructor_should_throw_when_settings_is_null() { - Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, null, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _capturedEvents, _serverApi, null); + Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, null, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _serverApi, _eventsLoggger); act.ShouldThrow(); } @@ -144,7 +146,7 @@ public void Constructor_should_throw_when_settings_is_null() [Fact] public void Constructor_should_throw_when_clusterId_is_null() { - Action act = () => new DefaultServer(null, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _capturedEvents, _serverApi, null); + Action act = () => new DefaultServer(null, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _serverApi, _eventsLoggger); act.ShouldThrow(); } @@ -152,7 +154,7 @@ public void Constructor_should_throw_when_clusterId_is_null() [Fact] public void Constructor_should_throw_when_clusterClock_is_null() { - Action act = () => new DefaultServer(_clusterId, null, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _capturedEvents, _serverApi, null); + Action act = () => new DefaultServer(_clusterId, null, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _serverApi, _eventsLoggger); act.ShouldThrow(); } @@ -160,7 +162,7 @@ public void Constructor_should_throw_when_clusterClock_is_null() [Fact] public void Constructor_should_throw_when_endPoint_is_null() { - Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, null, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _capturedEvents, _serverApi, null); + Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, null, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _serverApi, _eventsLoggger); act.ShouldThrow(); } @@ -168,7 +170,7 @@ public void Constructor_should_throw_when_endPoint_is_null() [Fact] public void Constructor_should_throw_when_connectionPoolFactory_is_null() { - Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, null, _mockServerMonitorFactory.Object, _capturedEvents, _serverApi, null); + Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, null, _mockServerMonitorFactory.Object, _serverApi, _eventsLoggger); act.ShouldThrow(); } @@ -176,15 +178,15 @@ public void Constructor_should_throw_when_connectionPoolFactory_is_null() [Fact] public void Constructor_should_throw_when_serverMonitorFactory_is_null() { - Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, null, _capturedEvents, _serverApi, null); + Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, null, _serverApi, _eventsLoggger); act.ShouldThrow(); } [Fact] - public void Constructor_should_throw_when_eventSubscriber_is_null() + public void Constructor_should_throw_when_eventsLogger_is_null() { - Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, null, _serverApi, null); + Action act = () => new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, _mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, _serverApi, null); act.ShouldThrow(); } @@ -229,9 +231,8 @@ public void GetChannel_should_clear_connection_pool_when_opening_connection_thro _endPoint, mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, - _capturedEvents, _serverApi, - CreateLogger()); + _eventsLoggger); var exceptionToThrow = new MongoAuthenticationException(connectionId, "Invalid login."); mockConnectionPool @@ -387,6 +388,7 @@ public void GetChannel_should_update_topology_and_clear_connection_pool_on_netwo var openConnectionException = new MongoConnectionException(connectionId, "Oops", new IOException("Cry", innerMostException)); var mockConnection = new Mock(); + mockConnection.Setup(c => c.ConnectionId).Returns(connectionId); mockConnection.Setup(c => c.Open(It.IsAny())).Throws(openConnectionException); mockConnection.Setup(c => c.OpenAsync(It.IsAny())).ThrowsAsync(openConnectionException); @@ -396,7 +398,7 @@ public void GetChannel_should_update_topology_and_clear_connection_pool_on_netwo var mockExceptionHandler = new Mock(); var connectionPoolSettings = new ConnectionPoolSettings(); - var connectionPool = new ExclusiveConnectionPool(serverId, _endPoint, connectionPoolSettings, connectionFactory.Object, new EventAggregator(), mockExceptionHandler.Object, null); + var connectionPool = new ExclusiveConnectionPool(serverId, _endPoint, connectionPoolSettings, connectionFactory.Object, mockExceptionHandler.Object, CreateLogger().ToEventsLogger(null)); var mockConnectionPoolFactory = new Mock(); mockConnectionPoolFactory @@ -409,7 +411,7 @@ public void GetChannel_should_update_topology_and_clear_connection_pool_on_netwo var mockServerMonitorFactory = new Mock(); mockServerMonitorFactory.Setup(f => f.Create(It.IsAny(), _endPoint)).Returns(mockServerMonitor.Object); - var subject = new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, mockConnectionPoolFactory.Object, mockServerMonitorFactory.Object, _capturedEvents, _serverApi, CreateLogger()); + var subject = new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, mockConnectionPoolFactory.Object, mockServerMonitorFactory.Object, _serverApi, _eventsLoggger); connectionPool._connectionExceptionHandler(subject); subject.Initialize(); connectionPool.SetReady(); @@ -469,7 +471,7 @@ public void HandleChannelException_should_update_topology_as_expected_on_network mockServerMonitor.SetupGet(m => m.Lock).Returns(new object()); var mockServerMonitorFactory = new Mock(); mockServerMonitorFactory.Setup(f => f.Create(It.IsAny(), _endPoint)).Returns(mockServerMonitor.Object); - var subject = new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, mockConnectionPoolFactory.Object, mockServerMonitorFactory.Object, _capturedEvents, _serverApi, CreateLogger()); + var subject = new DefaultServer(_clusterId, _clusterClock, _clusterConnectionMode, _connectionModeSwitch, _directConnection, _settings, _endPoint, mockConnectionPoolFactory.Object, mockServerMonitorFactory.Object, _serverApi, _eventsLoggger); subject.Initialize(); var heartbeatDescription = mockMonitorServerInitialDescription.With(reasonChanged: "Heartbeat", type: ServerType.Standalone); mockServerMonitor.Setup(m => m.Description).Returns(heartbeatDescription); @@ -885,9 +887,8 @@ private Server SetupServer(bool exceptionOnConnectionOpen, bool exceptionOnConne _endPoint, mockConnectionPoolFactory.Object, _mockServerMonitorFactory.Object, - _capturedEvents, _serverApi, - CreateLogger()); + _eventsLoggger); server.Initialize(); return server; diff --git a/tests/MongoDB.Driver.Core.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs b/tests/MongoDB.Driver.Core.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs index e0b8372aa67..4b356d8acc6 100644 --- a/tests/MongoDB.Driver.Core.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs +++ b/tests/MongoDB.Driver.Core.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs @@ -34,6 +34,7 @@ using MongoDB.Driver.Core.Connections; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Helpers; +using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; using MongoDB.Driver.Core.TestHelpers; @@ -650,9 +651,8 @@ private void ResetConnectionId() endPoint, connectionPoolSettings, connectionFactory.Object, - eventCapturer, connectionExceptionHandler.Object, - logger: null); + eventCapturer.ToEventsLogger()); connectionPool.Initialize(); } @@ -757,9 +757,8 @@ private IConnectionPool SetupConnectionPoolMock(BsonDocument test, IEventSubscri endPoint, connectionPoolSettings, connectionFactory.Object, - eventSubscriber, exceptionHandler.Object, - null); + eventSubscriber.ToEventsLogger()); return connectionPool; } diff --git a/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs b/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs index 70e104ca7f6..e94932082c0 100644 --- a/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs +++ b/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs @@ -21,6 +21,7 @@ using MongoDB.Driver.Core; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Configuration; +using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.Servers; using MongoDB.Driver.Linq; using MongoDB.Driver.TestHelpers; @@ -124,14 +125,14 @@ public static IEnumerable CreateDirectClientsToHostsInConnectionSt return CreateDirectClientsToServersInClientSettings(MongoClientSettings.FromConnectionString(connectionString.ToString())); } - public static DisposableMongoClient CreateDisposableClient(ILoggerFactory loggerFactory = null) + public static DisposableMongoClient CreateDisposableClient(LoggingSettings loggingSettings = null) { - return CreateDisposableClient((MongoClientSettings s) => { }, loggerFactory); + return CreateDisposableClient((MongoClientSettings s) => { }, loggingSettings); } - public static DisposableMongoClient CreateDisposableClient(Action clusterConfigurator, ILoggerFactory loggerFactory = null) + public static DisposableMongoClient CreateDisposableClient(Action clusterConfigurator, LoggingSettings loggingSettings = null) { - return CreateDisposableClient((MongoClientSettings s) => s.ClusterConfigurator = clusterConfigurator, loggerFactory); + return CreateDisposableClient((MongoClientSettings s) => s.ClusterConfigurator = clusterConfigurator, loggingSettings); } public static MongoClient CreateClient( @@ -157,31 +158,32 @@ public static MongoClient CreateClient( public static DisposableMongoClient CreateDisposableClient( Action clientSettingsConfigurator, - ILoggerFactory loggerFactory, + LoggingSettings loggingSettings, bool useMultipleShardRouters = false) { Action compositeClientSettingsConfigurator = s => { EnsureUniqueCluster(s); - s.LoggerFactory = loggerFactory; + s.LoggingSettings = loggingSettings; clientSettingsConfigurator?.Invoke(s); }; var client = CreateClient(compositeClientSettingsConfigurator, useMultipleShardRouters); - return new DisposableMongoClient(client, loggerFactory?.CreateLogger()); + return new DisposableMongoClient(client, loggingSettings.ToInternalLoggingFactory()?.CreateLogger()); } - public static DisposableMongoClient CreateDisposableClient(EventCapturer capturer, ILoggerFactory loggerFactory = null) + public static DisposableMongoClient CreateDisposableClient(EventCapturer capturer, LoggingSettings loggingSettings = null) { - return CreateDisposableClient((ClusterBuilder c) => c.Subscribe(capturer), loggerFactory); + return CreateDisposableClient((ClusterBuilder c) => c.Subscribe(capturer), loggingSettings); } public static DisposableMongoClient CreateDisposableClient(MongoClientSettings settings) { EnsureUniqueCluster(settings); - return new DisposableMongoClient(new MongoClient(settings), settings.LoggerFactory?.CreateLogger()); + + return new DisposableMongoClient(new MongoClient(settings), settings.LoggingSettings.ToInternalLoggingFactory()?.CreateLogger()); } private static MongoClient CreateLinq3Client() diff --git a/tests/MongoDB.Driver.Tests/ClusterKeyTests.cs b/tests/MongoDB.Driver.Tests/ClusterKeyTests.cs index 8736d9861bc..c89db0ede76 100644 --- a/tests/MongoDB.Driver.Tests/ClusterKeyTests.cs +++ b/tests/MongoDB.Driver.Tests/ClusterKeyTests.cs @@ -18,7 +18,6 @@ using System.Linq; using System.Security.Authentication; using FluentAssertions; -using Microsoft.Extensions.Logging; using MongoDB.Bson; using MongoDB.Bson.TestHelpers.XunitExtensions; using MongoDB.Driver.Core.Clusters; @@ -205,7 +204,7 @@ private ClusterKey CreateSubject(string notEqualFieldName = null) var kmsProviders = new Dictionary>(); var loadBalanced = true; var localThreshold = TimeSpan.FromMilliseconds(20); - ILoggerFactory loggerFactory = null; + var loggingSettings = new LoggingSettings(); var maxConnecting = 3; var maxConnectionIdleTime = TimeSpan.FromSeconds(2); var maxConnectionLifeTime = TimeSpan.FromSeconds(3); @@ -307,7 +306,7 @@ private ClusterKey CreateSubject(string notEqualFieldName = null) ipv6, loadBalanced, localThreshold, - loggerFactory, + loggingSettings, maxConnecting, maxConnectionIdleTime, maxConnectionLifeTime, @@ -356,7 +355,7 @@ internal ClusterKey CreateSubjectWith( var kmsProviders = kmsProvidersValue ?? new Dictionary>(); var loadBalanced = true; var localThreshold = TimeSpan.FromMilliseconds(20); - ILoggerFactory loggerFactory = null; + var loggingSettings = new LoggingSettings(); var maxConnecting = 3; var maxConnectionIdleTime = TimeSpan.FromSeconds(2); var maxConnectionLifeTime = TimeSpan.FromSeconds(3); @@ -398,7 +397,7 @@ internal ClusterKey CreateSubjectWith( ipv6, loadBalanced, localThreshold, - loggerFactory, + loggingSettings, maxConnecting, maxConnectionIdleTime, maxConnectionLifeTime, diff --git a/tests/MongoDB.Driver.Tests/ClusterRegistryTests.cs b/tests/MongoDB.Driver.Tests/ClusterRegistryTests.cs index 9f562af65cd..ae95e543cf0 100644 --- a/tests/MongoDB.Driver.Tests/ClusterRegistryTests.cs +++ b/tests/MongoDB.Driver.Tests/ClusterRegistryTests.cs @@ -96,7 +96,7 @@ public void GetOrCreateCluster_should_return_a_cluster_with_the_correct_settings ipv6: true, loadBalanced: false, localThreshold: TimeSpan.FromSeconds(4), - loggerFactory: null, + loggingSettings: null, maxConnecting: 3, maxConnectionIdleTime: TimeSpan.FromSeconds(5), maxConnectionLifeTime: TimeSpan.FromSeconds(6), diff --git a/tests/MongoDB.Driver.Tests/ClusterTests.cs b/tests/MongoDB.Driver.Tests/ClusterTests.cs index af80888629a..2ea15f99abd 100644 --- a/tests/MongoDB.Driver.Tests/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/ClusterTests.cs @@ -176,7 +176,7 @@ private DisposableMongoClient CreateDisposableClient(EventCapturer eventCapturer settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); settings.LocalThreshold = TimeSpan.FromMilliseconds(1000); }, - LoggerFactory, + LoggingSettings, true); var timeOut = TimeSpan.FromSeconds(60); bool AllServersConnected() => client.Cluster.Description.Servers.All(s => s.State == ServerState.Connected); diff --git a/tests/MongoDB.Driver.Tests/CustomServerSelectorTests.cs b/tests/MongoDB.Driver.Tests/CustomServerSelectorTests.cs index 47c7e9c2f33..1ab4420cbc1 100644 --- a/tests/MongoDB.Driver.Tests/CustomServerSelectorTests.cs +++ b/tests/MongoDB.Driver.Tests/CustomServerSelectorTests.cs @@ -48,7 +48,7 @@ public void Should_call_custom_server_selector() c.ConfigureCluster(s => s.With(postServerSelector: customServerSelector)); c.Subscribe(eventCapturer); }, - LoggerFactory)) + LoggingSettings)) { var collection = client .GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName) diff --git a/tests/MongoDB.Driver.Tests/LoggingTests.cs b/tests/MongoDB.Driver.Tests/LoggingTests.cs index c2f092a69b0..23aa04f5887 100644 --- a/tests/MongoDB.Driver.Tests/LoggingTests.cs +++ b/tests/MongoDB.Driver.Tests/LoggingTests.cs @@ -17,8 +17,11 @@ using System.Linq; using FluentAssertions; using Microsoft.Extensions.Logging; +using MongoDB.Bson; +using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.TestHelpers.Logging; +using MongoDB.Driver.Linq; using MongoDB.Driver.TestHelpers; using Xunit; using Xunit.Abstractions; @@ -34,7 +37,7 @@ public LoggingTests(ITestOutputHelper output) : base(output, includeAllCategorie [Fact] public void MongoClient_should_log() { - using (var client = DriverTestConfiguration.CreateDisposableClient(LoggerFactory)) + using (var client = DriverTestConfiguration.CreateDisposableClient(LoggingSettings)) { client.ListDatabases(new ListDatabasesOptions()); } @@ -81,7 +84,7 @@ public void MongoClient_should_log() [Fact] public void MongoClient_should_not_throw_when_factory_is_null() { - using (var client = DriverTestConfiguration.CreateDisposableClient(loggerFactory: null)) + using (var client = DriverTestConfiguration.CreateDisposableClient(loggingSettings: null)) { client.ListDatabases(new ListDatabasesOptions()); } @@ -89,6 +92,76 @@ public void MongoClient_should_not_throw_when_factory_is_null() Logs.Any().Should().BeFalse(); } + [Theory] + [InlineData(null)] + [InlineData(100)] + public void Prose_tests_truncation_limit_1(int? maxDocumentSize) + { + var expectedMaxSize = (maxDocumentSize ?? 1000) + 3; // 3 to account for '...' + const string collectionName = "proseLogTests"; + + var documents = Enumerable.Range(0, 100).Select(_ => new BsonDocument() { { "x", "y" } }).ToArray(); + + var loggingSettings = maxDocumentSize == null + ? new LoggingSettings(LoggerFactory) + : new LoggingSettings(LoggerFactory, maxDocumentSize.Value); + using (var client = DriverTestConfiguration.CreateDisposableClient(loggingSettings)) + { + + var db = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName); + + try + { + var collection = db.GetCollection(collectionName); + collection.InsertMany(documents); + _ = collection.Find(FilterDefinition.Empty).ToList(); + } + finally + { + db.DropCollection(collectionName); + } + } + + var commandCategory = LogCategoryHelper.GetCategoryName(); + var commands = Logs.Where(l => l.Category == commandCategory).ToArray(); + + GetCommandParameter(commands, "insert", "Command started", StructuredLogsTemplates.Command) + .Length.Should().Be(expectedMaxSize); + GetCommandParameter(commands, "insert", "Command succeeded", StructuredLogsTemplates.Reply) + .Length.Should().BeLessOrEqualTo(expectedMaxSize); + GetCommandParameter(commands, "find", "Command succeeded", StructuredLogsTemplates.Reply) + .Length.Should().Be(expectedMaxSize); + } + + [Fact] + public void Prose_tests_truncation_limit_2() + { + const int truncationSize = 5; + const int maxDocumentSize = truncationSize + 3; // 3 to account for '...' + var loggingSettings = new LoggingSettings(LoggerFactory, truncationSize); + using (var client = DriverTestConfiguration.CreateDisposableClient(loggingSettings)) + { + var db = client.GetDatabase(DriverTestConfiguration.DatabaseNamespace.DatabaseName); + + try + { + db.RunCommand(new BsonDocument() { { "hello", "true" } }); + db.RunCommand(new BsonDocument() { { "notARealCommand", "true" } }); + } + catch (MongoCommandException) { } + } + + var commandCategory = LogCategoryHelper.GetCategoryName(); + var commands = Logs.Where(l => l.Category == commandCategory).ToArray(); + + GetCommandParameter(commands, "hello", "Command started", StructuredLogsTemplates.Command) + .Length.Should().Be(maxDocumentSize); + GetCommandParameter(commands, "hello", "Command succeeded", StructuredLogsTemplates.Reply) + .Length.Should().Be(maxDocumentSize); + GetCommandParameter(commands, "notARealCommand", "Command failed", StructuredLogsTemplates.Failure) + .Length.Should().Be(maxDocumentSize); + } + private void AssertLogs((LogLevel logLevel, string categorySubString, string messageSubString)[] expectedLogs, LogEntry[] actualLogs) { var actualLogIndex = 0; @@ -107,5 +180,14 @@ bool Match(LogEntry logEntry) => logEntry.FormattedMessage?.Contains(messageSubString) == true; } } + + private string GetCommandParameter(LogEntry[] commandLogs, string commandName, string message, string parameter) + { + var command = commandLogs.Single(c => + c.GetParameter(StructuredLogsTemplates.CommandName) == commandName && + c.GetParameter(StructuredLogsTemplates.Message) == message); + + return command.GetParameter(parameter); + } } } diff --git a/tests/MongoDB.Driver.Tests/MongoClientSettingsTests.cs b/tests/MongoDB.Driver.Tests/MongoClientSettingsTests.cs index 84472381bec..0bbe6d3180e 100644 --- a/tests/MongoDB.Driver.Tests/MongoClientSettingsTests.cs +++ b/tests/MongoDB.Driver.Tests/MongoClientSettingsTests.cs @@ -25,7 +25,6 @@ using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Compression; using MongoDB.Driver.Core.Configuration; -using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.TestHelpers.XunitExtensions; using Moq; using Xunit; @@ -936,21 +935,20 @@ public void TestLocalThreshold() } [Fact] - public void TestLoggerFactory() + public void TestLoggingSettings() { var settings = new MongoClientSettings(); - Assert.Equal(null, settings.LoggerFactory); + Assert.Equal(null, settings.LoggingSettings); - settings.LoggerFactory = null; - Assert.Equal(null, settings.LoggerFactory); + settings.LoggingSettings = null; + Assert.Equal(null, settings.LoggingSettings); var loggerFactory = new Mock(); - settings.LoggerFactory = loggerFactory.Object; - Assert.IsType(settings.LoggerFactory); + settings.LoggingSettings = new LoggingSettings(loggerFactory.Object); + Assert.Equal(loggerFactory.Object, settings.LoggingSettings.LoggerFactory); settings.Freeze(); - Assert.IsType(settings.LoggerFactory); - Assert.Throws(() => { settings.LoggerFactory = loggerFactory.Object; }); + Assert.Throws(() => { settings.LoggingSettings = new LoggingSettings(loggerFactory.Object); }); } [Fact] @@ -1437,7 +1435,7 @@ public void ToClusterKey_should_copy_relevant_values() HeartbeatTimeout = TimeSpan.FromSeconds(8), IPv6 = true, LocalThreshold = TimeSpan.FromMilliseconds(20), - LoggerFactory = new Mock().Object, + LoggingSettings = new LoggingSettings(), MaxConnecting = 3, MaxConnectionIdleTime = TimeSpan.FromSeconds(2), MaxConnectionLifeTime = TimeSpan.FromSeconds(3), @@ -1486,7 +1484,7 @@ public void ToClusterKey_should_copy_relevant_values() result.HeartbeatTimeout.Should().Be(subject.HeartbeatTimeout); result.IPv6.Should().Be(subject.IPv6); result.LocalThreshold.Should().Be(subject.LocalThreshold); - result.LoggerFactory.Should().Be(subject.LoggerFactory); + result.LoggingSettings.Should().Be(subject.LoggingSettings); result.MaxConnecting.Should().Be(subject.MaxConnecting); result.MaxConnectionIdleTime.Should().Be(subject.MaxConnectionIdleTime); result.MaxConnectionLifeTime.Should().Be(subject.MaxConnectionLifeTime); diff --git a/tests/MongoDB.Driver.Tests/OcspIntegrationTests.cs b/tests/MongoDB.Driver.Tests/OcspIntegrationTests.cs index ee800e887b2..e39c552a37e 100644 --- a/tests/MongoDB.Driver.Tests/OcspIntegrationTests.cs +++ b/tests/MongoDB.Driver.Tests/OcspIntegrationTests.cs @@ -111,7 +111,7 @@ private DisposableMongoClient CreateDisposableMongoClient(bool tlsInsecure) settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5 * 2); // must be > 5s // settings.SdamLogFilename = @"C:\temp\sdam" + $"{tlsInsecure}.log"; - settings.LoggerFactory = LoggerFactory; + settings.LoggingSettings = LoggingSettings; return new DisposableMongoClient(new MongoClient(settings), CreateLogger()); } diff --git a/tests/MongoDB.Driver.Tests/PinnedShardRouterTests.cs b/tests/MongoDB.Driver.Tests/PinnedShardRouterTests.cs index be7b8588578..696f0953274 100644 --- a/tests/MongoDB.Driver.Tests/PinnedShardRouterTests.cs +++ b/tests/MongoDB.Driver.Tests/PinnedShardRouterTests.cs @@ -186,7 +186,7 @@ private DisposableMongoClient CreateDisposableClient(EventCapturer eventCapturer settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); settings.LocalThreshold = TimeSpan.FromMilliseconds(1000); }, - LoggerFactory, + LoggingSettings, useMultipleShardRouters); var timeOut = TimeSpan.FromSeconds(60); bool AllServersConnected() => client.Cluster.Description.Servers.All(s => s.State == ServerState.Connected); diff --git a/tests/MongoDB.Driver.Tests/ReadPreferenceOnStandaloneTests.cs b/tests/MongoDB.Driver.Tests/ReadPreferenceOnStandaloneTests.cs index 7fbf5235162..5b6ec286fc1 100644 --- a/tests/MongoDB.Driver.Tests/ReadPreferenceOnStandaloneTests.cs +++ b/tests/MongoDB.Driver.Tests/ReadPreferenceOnStandaloneTests.cs @@ -79,7 +79,7 @@ private DisposableMongoClient CreateDisposableClient(EventCapturer eventCapturer settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); settings.ReadPreference = readPreference; }, - LoggerFactory); + LoggingSettings); } } } diff --git a/tests/MongoDB.Driver.Tests/RetryableWritesTests.cs b/tests/MongoDB.Driver.Tests/RetryableWritesTests.cs index 03a71da3573..e087c9ad28a 100644 --- a/tests/MongoDB.Driver.Tests/RetryableWritesTests.cs +++ b/tests/MongoDB.Driver.Tests/RetryableWritesTests.cs @@ -262,7 +262,7 @@ private DisposableMongoClient GetClient(Action clusterConfigurat clientSettings.ClusterConfigurator = clusterConfigurator; clientSettings.RetryWrites = retryWrites; }, - LoggerFactory); + LoggingSettings); } private DisposableMongoClient GetClient(EventCapturer capturer) diff --git a/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs b/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs index 6f2ec54f150..0f960caa2ee 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs @@ -501,7 +501,7 @@ protected DisposableMongoClient CreateDisposableClient(BsonDocument test, EventC settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); } }, - LoggerFactory, + LoggingSettings, useMultipleShardRouters); } diff --git a/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs index 940d14bc9fb..89b9d38e1f5 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs @@ -33,6 +33,7 @@ using MongoDB.Driver.Core; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; +using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Operations; @@ -2188,7 +2189,7 @@ private MongoClientSettings CreateMongoClientSettings( mongoClientSettings.AutoEncryptionOptions = autoEncryptionOptions; } - mongoClientSettings.LoggerFactory = LoggerFactory; + mongoClientSettings.LoggingSettings = LoggingSettings; return mongoClientSettings; } diff --git a/tests/MongoDB.Driver.Tests/Specifications/command-logging-and-monitoring/CommandLoggingUnifiedTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/command-logging-and-monitoring/CommandLoggingUnifiedTestRunner.cs index de889e9a58d..518f961558a 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/command-logging-and-monitoring/CommandLoggingUnifiedTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/command-logging-and-monitoring/CommandLoggingUnifiedTestRunner.cs @@ -48,6 +48,7 @@ protected override IEnumerable CreateTestCases(BsonDocument { foreach (var testCase in base.CreateTestCases(document)) { + // .NET driver has a fallback logic to get a server connectionId based on an additional getLastError call which is not expected by the spec. if (testCase.Name.Contains("pre-42-server-connection-id")) { continue; diff --git a/tests/MongoDB.Driver.Tests/Specifications/crud/CrudTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/crud/CrudTestRunner.cs index 6241dd61e8d..4913cb7275b 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/crud/CrudTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/crud/CrudTestRunner.cs @@ -145,7 +145,7 @@ private DisposableMongoClient CreateDisposableClient(EventCapturer eventCapturer c.ConfigureServer(ss => ss.With(heartbeatInterval: Timeout.InfiniteTimeSpan)); }; }, - LoggerFactory); + LoggingSettings); } private void ExecuteOperation(IMongoClient client, IMongoDatabase database, IMongoCollection collection, BsonDocument operation, BsonDocument outcome, bool async) diff --git a/tests/MongoDB.Driver.Tests/Specifications/crud/prose-tests/CrudProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/crud/prose-tests/CrudProseTests.cs index 98261fb04db..7f936e6bd4c 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/crud/prose-tests/CrudProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/crud/prose-tests/CrudProseTests.cs @@ -167,7 +167,7 @@ private DisposableMongoClient CreateDisposableClient(EventCapturer eventCapturer settings.HeartbeatInterval = TimeSpan.FromMilliseconds(5); settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); }, - LoggerFactory); + LoggingSettings); } } } diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsTestRunner.cs index 48c524ed85b..b5bf8d6574b 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsTestRunner.cs @@ -216,7 +216,7 @@ private DisposableMongoClient CreateDisposableClient(BsonDocument test, EventCap ConfigureClientSettings(settings, test); settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); }, - LoggerFactory); + LoggingSettings); } private void ConfigureClientSettings(MongoClientSettings settings, BsonDocument test) diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/RetryableWriteTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/RetryableWriteTestRunner.cs index cdbf7f6403b..b74c0f1fa68 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/RetryableWriteTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/RetryableWriteTestRunner.cs @@ -138,7 +138,7 @@ private DisposableMongoClient CreateDisposableClient(BsonDocument test, bool use settings.HeartbeatInterval = TimeSpan.FromMilliseconds(5); // the default value for spec tests ParseClientOptions(settings, clientOptions); }, - LoggerFactory, + LoggingSettings, useMultipleShardRouters); } diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/CommandConstructionTests.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/CommandConstructionTests.cs index 023aa7646c0..d399f7cbb84 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/CommandConstructionTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/CommandConstructionTests.cs @@ -444,7 +444,7 @@ private DisposableMongoClient CreateDisposableClient(EventCapturer eventCapturer settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); settings.RetryWrites = true; }, - LoggerFactory); + LoggingSettings); } private EventCapturer CreateEventCapturer() diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/MMapV1Tests.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/MMapV1Tests.cs index 6a5f9ac849d..e20d27c4166 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/MMapV1Tests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/MMapV1Tests.cs @@ -66,7 +66,7 @@ public void Write_operation_should_throw_when_retry_writes_is_true_and_storage_e // private methods private DisposableMongoClient CreateDisposableMongoClient() { - return DriverTestConfiguration.CreateDisposableClient(s => s.RetryWrites = true, LoggerFactory); + return DriverTestConfiguration.CreateDisposableClient(s => s.RetryWrites = true, LoggingSettings); } } } diff --git a/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/prose-tests/ServerDiscoveryProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/prose-tests/ServerDiscoveryProseTests.cs index 582435792f0..14b61086e63 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/prose-tests/ServerDiscoveryProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/prose-tests/ServerDiscoveryProseTests.cs @@ -21,6 +21,7 @@ using MongoDB.Bson; using MongoDB.Bson.TestHelpers.XunitExtensions; using MongoDB.Driver.Core.Clusters; +using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; using MongoDB.Driver.Core.TestHelpers.Logging; @@ -66,7 +67,7 @@ public void Topology_secondary_discovery_with_directConnection_false_should_work var dnsEndpoint = (DnsEndPoint)secondary.EndPoint; var replicaSetName = secondary.ReplicaSetConfig.Name; var settings = MongoClientSettings.FromConnectionString(CreateConnectionString(dnsEndpoint, directConnection, replicaSetName)); - settings.LoggerFactory = LoggerFactory; + settings.LoggingSettings = LoggingSettings; using (var client = new DisposableMongoClient(new MongoClient(settings), CreateLogger())) { diff --git a/tests/MongoDB.Driver.Tests/Specifications/sessions/SessionsProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/sessions/SessionsProseTests.cs index f3600f3fa08..de6da82636f 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/sessions/SessionsProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/sessions/SessionsProseTests.cs @@ -68,7 +68,7 @@ public async Task Ensure_server_session_are_allocated_only_on_connection_checkou settings.MaxConnectionPoolSize = 1; settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); }, - LoggerFactory); + LoggingSettings); var database = client.GetDatabase("test"); @@ -202,7 +202,7 @@ public async Task Ensure_server_session_are_allocated_only_on_connection_checkou settings.MaxConnectionPoolSize = 1; settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); }, - LoggerFactory); + LoggingSettings); var database = client.GetDatabase("test"); database.DropCollection("inventory"); diff --git a/tests/MongoDB.Driver.Tests/Specifications/transactions/TransactionTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/transactions/TransactionTestRunner.cs index d85dc5a2491..3dfc44078a0 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/transactions/TransactionTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/transactions/TransactionTestRunner.cs @@ -262,7 +262,7 @@ private DisposableMongoClient CreateDisposableClient(BsonDocument test, EventCap ConfigureClientSettings(settings, test); settings.ClusterConfigurator = c => c.Subscribe(eventCapturer); }, - LoggerFactory, + LoggingSettings, useMultipleShardRouters); } diff --git a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/Matchers/UnifiedLogMatcher.cs b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/Matchers/UnifiedLogMatcher.cs index ab81ed5334d..96c7f13ab15 100644 --- a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/Matchers/UnifiedLogMatcher.cs +++ b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/Matchers/UnifiedLogMatcher.cs @@ -16,9 +16,7 @@ using System.Collections.Generic; using System.Linq; using FluentAssertions; -using Microsoft.Extensions.Logging; using MongoDB.Bson; -using MongoDB.Driver.Core.Logging; using MongoDB.Driver.Core.TestHelpers.Logging; namespace MongoDB.Driver.Tests.UnifiedTestOperations.Matchers @@ -34,52 +32,22 @@ public UnifiedLogMatcher(UnifiedValueMatcher valueMatcher) public void AssertLogsMatch(LogEntry[] actualLogs, BsonArray expectedLogs) { - actualLogs.Length.Should().BeGreaterOrEqualTo(expectedLogs.Count); + actualLogs.Length.Should().Be(expectedLogs.Count); - var actualLogIndex = 0; for (int i = 0; i < expectedLogs.Count; i++) { var expectedLogDocument = expectedLogs[i].AsBsonDocument; + var actualLog = actualLogs[i]; + var expectedCategory = UnifiedLogHelper.ParseCategory(expectedLogDocument["component"].AsString); var expectedLogLevel = UnifiedLogHelper.ParseLogLevel(expectedLogDocument["level"].AsString); - var matchFound = false; - for (; actualLogIndex < actualLogs.Length && !matchFound; actualLogIndex++) - { - var logEntry = actualLogs[actualLogIndex]; - - if (PreMatchLog(logEntry, expectedLogDocument, expectedCategory, expectedLogLevel)) - { - var logDataDocument = new BsonDocument(logEntry.State.Select(ToBsonElement)); - - try - { - _valueMatcher.AssertValuesMatch(logDataDocument, expectedLogDocument["data"]); - matchFound = true; - } - catch { } - } - } - - matchFound.Should().BeTrue("Log message not found {0}", expectedLogDocument); - } - } - - private static bool PreMatchLog(LogEntry actualLog, BsonDocument expectedLog, string expectedCategory, LogLevel expectedLogLevel) - { - if (actualLog.LogLevel != expectedLogLevel || - actualLog.Category != expectedCategory) - { - return false; - } + actualLog.Category.Should().Be(expectedCategory); + actualLog.LogLevel.Should().Be(expectedLogLevel); - if (expectedCategory == LogCategoryHelper.GetCategoryName() && - actualLog.GetParameter(StructuredLogsTemplates.CommandName)?.ToString() != expectedLog["data"]["commandName"].AsString) - { - return false; + var actualLogDocument = new BsonDocument(actualLog.State.Select(ToBsonElement)); + _valueMatcher.AssertValuesMatch(actualLogDocument, expectedLogDocument["data"]); } - - return true; } private static BsonElement ToBsonElement(KeyValuePair pair) => diff --git a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedCreateEntitiesOperation.cs b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedCreateEntitiesOperation.cs index 9137b4303db..671a8f3685b 100644 --- a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedCreateEntitiesOperation.cs +++ b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedCreateEntitiesOperation.cs @@ -35,7 +35,7 @@ public OperationResult Execute(CancellationToken cancellationToken) { try { - var newEntityMap = new UnifiedEntityMapBuilder(null, _entityMap.LoggerFactory).Build(_entitiesArray); + var newEntityMap = new UnifiedEntityMapBuilder(null, _entityMap.LoggingSettings).Build(_entitiesArray); _entityMap.AddEntities(newEntityMap); return OperationResult.Empty(); diff --git a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedEntityMap.cs b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedEntityMap.cs index f307052b9ce..2cef67bfa2e 100644 --- a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedEntityMap.cs +++ b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedEntityMap.cs @@ -20,6 +20,7 @@ using Microsoft.Extensions.Logging; using MongoDB.Bson; using MongoDB.Driver.Core; +using MongoDB.Driver.Core.Configuration; using MongoDB.Driver.Core.Events; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.TestHelpers.XunitExtensions; @@ -50,7 +51,7 @@ public sealed class UnifiedEntityMap : IDisposable private readonly Dictionary _sessions; private readonly Dictionary _sessionIds; private readonly Dictionary _successCounts; - private readonly ILoggerFactory _loggerFactory; + private readonly LoggingSettings _loggingSettings; // public constructors public UnifiedEntityMap( @@ -70,7 +71,7 @@ public UnifiedEntityMap( Dictionary sessions, Dictionary sessionIds, Dictionary successCounts, - ILoggerFactory loggerFactory) + LoggingSettings loggingSettings) { _buckets = buckets; _changeStreams = changeStreams; @@ -88,7 +89,7 @@ public UnifiedEntityMap( _sessions = sessions; _sessionIds = sessionIds; _successCounts = successCounts; - _loggerFactory = loggerFactory; + _loggingSettings = loggingSettings; } // public properties @@ -164,12 +165,12 @@ public Dictionary IterationCounts } } - public ILoggerFactory LoggerFactory + public LoggingSettings LoggingSettings { get { ThrowIfDisposed(); - return _loggerFactory; + return _loggingSettings; } } @@ -305,12 +306,12 @@ public void AddEntities(UnifiedEntityMap unifiedEntityMap) public class UnifiedEntityMapBuilder { private readonly Dictionary _eventFormatters; - private readonly ILoggerFactory _loggerFactory; + private readonly LoggingSettings _loggingSettings; - public UnifiedEntityMapBuilder(Dictionary eventFormatters, ILoggerFactory loggerFactory) + public UnifiedEntityMapBuilder(Dictionary eventFormatters, LoggingSettings loggingSettings) { _eventFormatters = eventFormatters ?? new(); - _loggerFactory = loggerFactory; + _loggingSettings = loggingSettings; } public UnifiedEntityMap Build(BsonArray entitiesArray) @@ -409,7 +410,7 @@ public UnifiedEntityMap Build(BsonArray entitiesArray) sessions, sessionIds, successCounts, - _loggerFactory); + _loggingSettings); void EnsureIsNotHandled(Dictionary dictionary, string key) { @@ -645,7 +646,7 @@ private IGridFSBucket CreateBucket(BsonDocument entity, Dictionary(); + _logger = loggingService.LoggingSettings.CreateLogger(); } // public properties @@ -117,7 +118,7 @@ public void Run( KillOpenTransactions(DriverTestConfiguration.Client); - _entityMap = new UnifiedEntityMapBuilder(_eventFormatters, _loggingService.LoggerFactory).Build(entities); + _entityMap = new UnifiedEntityMapBuilder(_eventFormatters, _loggingService.LoggingSettings).Build(entities); if (initialData != null) { diff --git a/tests/SmokeTests/MongoDB.Driver.SmokeTests.Sdk/LoggingTests.cs b/tests/SmokeTests/MongoDB.Driver.SmokeTests.Sdk/LoggingTests.cs index 43daaf0be7f..7f3d876f993 100644 --- a/tests/SmokeTests/MongoDB.Driver.SmokeTests.Sdk/LoggingTests.cs +++ b/tests/SmokeTests/MongoDB.Driver.SmokeTests.Sdk/LoggingTests.cs @@ -21,6 +21,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using MongoDB.Driver.Core.Configuration; using Xunit; using Xunit.Abstractions; @@ -57,7 +58,7 @@ public void MongoClient_should_log_only_configured_categories(string categoryNam using (var loggerFactory = GetLoggerFactory(logsTracer, categories)) { var settings = GetMongoClientSettings(); - settings.LoggerFactory = loggerFactory; + settings.LoggingSettings = new LoggingSettings(loggerFactory); var mongoClient = new MongoClient(settings); try