Beispiel #1
0
 public MongoClientFactory(IDependencyTracker dependencyTracker,
                           MongoClientSettingsFactorySettings settings = null,
                           ILogger logger = null)
 {
     _configurator = new MongoTrackingConfigurator(dependencyTracker, settings, logger);
 }
        public MongoTrackingConfigurator(IDependencyTracker dependencyTracker,
                                         MongoClientSettingsFactorySettings settings = null,
                                         ILogger logger = null)
        {
            _dependencyTracker = dependencyTracker ?? throw new ArgumentNullException($"{nameof(dependencyTracker)} is required");
            var notTrackedCommands = (settings ?? new MongoClientSettingsFactorySettings()).NotTrackedCommands.Select(v => v.ToLower()).ToImmutableHashSet();

            OnCommandStartEvent = e =>
            {
                try
                {
                    if (e.Command != null && !notTrackedCommands.Contains(e.CommandName.ToLower()))
                    {
                        // ReSharper disable once SpecifyACultureInStringConversionExplicitly
                        _queriesBuffer.TryAdd(e.RequestId, e.Command.ToString());
                    }
                }
                catch (Exception exception)
                {
                    logger?.Exception(exception);
                }
            };

            OnCommandSucceededEvent = e =>
            {
                if (notTrackedCommands.Contains(e.CommandName.ToLower()))
                {
                    return;
                }

                try
                {
                    if (_queriesBuffer.TryRemove(e.RequestId, out var query))
                    {
                        OnCommandCompleted(
                            new MongoCommandCompletedEventArgs(e.CommandName, query, true,
                                                               e.Duration));
                    }
                }
                catch (Exception exception)
                {
                    logger?.Exception(exception);
                }
            };

            OnCommandFailedEvent = e =>
            {
                if (notTrackedCommands.Contains(e.CommandName.ToLower()))
                {
                    return;
                }
                try
                {
                    if (_queriesBuffer.TryRemove(e.RequestId, out var query))
                    {
                        OnCommandCompleted(
                            new MongoCommandCompletedEventArgs(e.CommandName, query, false,
                                                               e.Duration));
                    }
                }
                catch (Exception exception)
                {
                    logger?.Exception(exception);
                }
            };
        }