コード例 #1
0
        public async Task <Server[]> DiscoverAsync(CancellationToken cancellationToken)
        {
            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            Server[] servers = null;

            discoveryCancellationTokenSource?.Cancel();
            discoveryCancellationTokenSource = new();

            _logger?.LogInformation("Network discovery started");

            discoveryCancellationTokenSource.CancelAfter(Configuration.Timeout);

            using (var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(discoveryCancellationTokenSource.Token, cancellationToken))
            {
                var linkedCancellationToken = linkedCancellationTokenSource.Token;

                _ = BroadcastAsync(linkedCancellationToken).ConfigureAwait(false);

                servers = await ListenAsync(linkedCancellationToken).ConfigureAwait(false);
            }

            _logger?.LogInformation("Network discovery ended");

            discoveryCancellationTokenSource.Cancel();

            return(servers);
        }
コード例 #2
0
        private async Task <Server[]> GetServersAsync(CancellationToken cancellationToken)
        {
            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            return(await Task.Run(async() =>
            {
                var servers = new ConcurrentBag <Server>();

                try
                {
                    var populationTasks = new List <Task>();

                    var registryInstances = LocalServers.LookupRegistryInstances();

                    foreach (var(hive, instances) in registryInstances)
                    {
                        foreach (var instance in instances)
                        {
                            populationTasks.Add(PopulateLocalServerAsync(servers, hive, instance, cancellationToken));
                        }
                    }

                    await Task.WhenAll(populationTasks).ConfigureAwait(false);
                }
                catch (TaskCanceledException)
                {
                    _logger?.LogDebug($"[{LoggingExtensions.CurrentFunction()}] Cancelled");
                }

                return servers.Distinct().ToArray();
            }, cancellationToken).ConfigureAwait(false));
        }
コード例 #3
0
        private async Task <Server[]> ListenAsync(CancellationToken cancellationToken)
        {
            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            var servers = new ConcurrentBag <Server>();

            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    var result = await client.ReceiveAsync().WithCancellation(cancellationToken).ConfigureAwait(false);

                    _ = ProcessResponse(servers, result.Buffer, result.RemoteEndPoint, cancellationToken).ConfigureAwait(false);
                }
                catch (TaskCanceledException)
                {
                    _logger?.LogDebug($"[{LoggingExtensions.CurrentFunction()}] Cancelled");
                }
                catch (Exception ex)
                {
                    _logger?.LogError(ex, "Error occured while receiving responses");

                    if (Configuration.ReceiveExceptionAction is Architecture.ExceptionActions.LogAndThrow)
                    {
                        throw;
                    }
                }
            }

            return(servers.Distinct().ToArray());
        }
コード例 #4
0
        private Task PopulateLocalServerAsync(ConcurrentBag <Server> servers, RegistryKey hive, string instance, CancellationToken cancellationToken)
        {
            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            return(Task.Run(() =>
            {
                try
                {
                    var localServer = new LocalServer();

                    localServer.Populate(hive, instance);

                    var server = localServer.ToServer();

                    servers.Add(server);

                    OnLocalServerDiscovered?.Invoke(this, localServer);
                    OnServerDiscovered?.Invoke(this, server);
                }
                catch (TaskCanceledException)
                {
                    _logger?.LogDebug($"[{LoggingExtensions.CurrentFunction()}] Cancelled");
                }
            }, cancellationToken));
        }
コード例 #5
0
        /// <summary>
        /// Sends message to a remote SMPP server
        /// </summary>
        /// <param name="message">A message to send</param>
        /// <param name="timeOut">A value in miliseconds after which the send operation times out</param>
        public void SendMessage(ShortMessage message, int timeOut)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            //Check if connection is open
            if (vState != SmppConnectionState.Connected)
            {
                throw new SmppClientException("Sending message operation failed because the SmppClient is not connected");
            }

            string messageId = null;

            foreach (SendSmPDU pdu in message.GetMessagePDUs(vProperties.DefaultEncoding, vSmppEncodingService))
            {
                if (_Log.IsDebugEnabled)
                {
                    _Log.DebugFormat("SendMessage SendSmPDU: {0}", LoggingExtensions.DumpString(pdu, vSmppEncodingService));
                }
                ResponsePDU resp         = SendPdu(pdu, timeOut);
                var         submitSmResp = resp as SubmitSmResp;
                if (submitSmResp != null)
                {
                    if (_Log.IsDebugEnabled)
                    {
                        _Log.DebugFormat("SendMessage Response: {0}", LoggingExtensions.DumpString(resp, vSmppEncodingService));
                    }
                    messageId = ((SubmitSmResp)resp).MessageID;
                }
                message.ReceiptedMessageId = messageId;
                RaiseMessageSentEvent(message);
            }
        }
コード例 #6
0
 internal MockAgentTimer(string dbgName = null, IApmLogger logger = null)
 {
     WhenStarted = new AgentTimeInstant(this, TimeSpan.Zero);
     Now         = WhenStarted;
     _dbgName    = dbgName ?? "#" + RuntimeHelpers.GetHashCode(this).ToString("X");
     _logger     = logger == null ? (IApmLogger) new NoopLogger() : LoggingExtensions.Scoped(logger, $"{ThisClassName}-{_dbgName}");
 }
コード例 #7
0
        // For cached queries, local values are passed in closure object. The problem is that a single closure is created for a method,
        // and a query might use only some of closure values. So for each field in closure we check that it is actually used in the query we report.
        private static string FormatClosureValues(string fromExpression, string paramName, object obj)
        {
            if (obj == null)
            {
                return(paramName + "=null");
            }
            var type = obj.GetType();

            if (!type.IsAnonymousType())
            {
                return(paramName + "=" + LoggingExtensions.ToLogString(obj));
            }
            //Anonymous type
            var fields    = type.GetFields();
            var strValues = new StringList();

            for (int i = 0; i < fields.Length; i++)
            {
                var fld         = fields[i];
                var fullRefName = paramName + "." + fld.Name;
                if (fromExpression.Contains(fullRefName))
                {
                    strValues.Add(fullRefName + "=" + LoggingExtensions.ToLogString(fld.GetValue(obj)));
                }
            }
            return(string.Join(", ", strValues));
        }
コード例 #8
0
        public void Stop()
        {
            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            _logger?.LogInformation("Local discovery cancelled");

            discoveryCancellationTokenSource?.Cancel();
        }
コード例 #9
0
        public static void InitializeAssembly(TestContext testContext)
        {
            TestLogUtils.InitializeLog(testContext);
            // Force LoggingExtensions class initialization.
            using (LoggingExtensions.Indent()) { }

            FrameworkElementFormatter.GetInstance().SetTypeFormatter(typeof(DataGridRow), new DataGridRowFormatter());
        }
コード例 #10
0
        public IEnumerable <TEntity> GetAll()
        {
            var callerInfo = LoggingExtensions.Caller();

            return(_profiler.Profile(
                       () => _readerDelegate.GetAll(),
                       callerInfo
                       ));
        }
コード例 #11
0
        public void Stop()
        {
            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            _logger?.LogInformation("Discovery cancelled");

            networkDiscovery?.Stop();
            localDiscovery?.Stop();
        }
コード例 #12
0
        public void Remove(TEntity entity)
        {
            var callerInfo = LoggingExtensions.Caller();

            _profiler.Profile(
                () => _writerDelegate.Remove(entity),
                $"{callerInfo} - entity=[{JsonLogging.Serialize(entity)}];"
                );
        }
コード例 #13
0
        public void AddRange(IEnumerable <TEntity> entities)
        {
            var callerInfo = LoggingExtensions.Caller();

            _profiler.Profile(
                () => _writerDelegate.AddRange(entities),
                $"{callerInfo} - entities=[{JsonLogging.Serialize(entities)}];"
                );
        }
コード例 #14
0
        public IEnumerable <TEntity> Find(Expression <Func <TEntity, bool> > predicate)
        {
            var callerInfo = LoggingExtensions.Caller();

            return(_profiler.Profile(
                       () => _readerDelegate.GetAll(),
                       $"{callerInfo} - predicate=[{predicate}];"
                       ));
        }
コード例 #15
0
        public TEntity Get(long id)
        {
            var callerInfo = LoggingExtensions.Caller();

            return(_profiler.Profile(
                       () => _readerDelegate.Get(id),
                       $"{callerInfo} - id=[{id}]"
                       ));
        }
コード例 #16
0
        public async Task <Server[]> DiscoverLocalServers(CancellationToken cancellationToken)
        {
            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            localDiscovery = new(_logger);
            localDiscovery.OnLocalServerDiscovered += OnLocalServerDiscovered;
            localDiscovery.OnServerDiscovered      += OnServerDiscovered;

            return(await localDiscovery.DiscoverAsync(cancellationToken).ConfigureAwait(false));;
        }
コード例 #17
0
        public async Task <Server[]> DiscoverNetworkServers(CancellationToken cancellationToken, NetworkConfiguration configuration = null)
        {
            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            networkDiscovery = new(_logger, configuration);
            networkDiscovery.OnNetworkServerDiscovered += OnNetworkServerDiscovered;
            networkDiscovery.OnServerDiscovered        += OnServerDiscovered;

            return(await networkDiscovery.DiscoverAsync(cancellationToken).ConfigureAwait(false));;
        }
コード例 #18
0
        private string FormatEntry()
        {
            var fullFormat   = "/*{0}*/ {1} {2} -- @{3} ms {4}, {5}";
            var strArgs      = LoggingExtensions.ToSqlArgList(_args);
            var strRowCount  = (_rowCount < 0) ? string.Empty : StringHelper.SafeFormat(", {0} row(s)", _rowCount);
            var strCacheType = _cacheType == CacheType.FullSet ? "FullSetCache" : "SparseCache";
            var result       = StringHelper.SafeFormat(fullFormat, strCacheType, _commandName, strArgs, _executionTime, strRowCount, _dateTime);

            return(result);
        }
コード例 #19
0
        private string FormatStoredProcEntry()
        {
            var fullFormat  = "CALL {0} {1}  -- @{2} ms {3}, {4} ";
            var strParams   = LoggingExtensions.FormatSqlParameters(_command.Parameters, "{1}" /*Value only*/, ", ", maxValueLen: 50);
            var strRowCount = (RowCount < 0) ? string.Empty : Util.SafeFormat(", {0} row(s)", RowCount);
            var strDateTime = base.CreatedOn.ToString("[yyyy/MM/dd HH:mm:ss]");
            var result      = Util.SafeFormat(fullFormat, _command.CommandText, strParams, ExecutionTime, strRowCount, strDateTime);

            return(result);
        }
コード例 #20
0
        public NewRelicFormatter WithPropertyMapping(string propertyName, NewRelicLoggingProperty outputAsNewRelicProperty)
        {
            if (_reservedProperties.Contains(outputAsNewRelicProperty))
            {
                throw new InvalidOperationException($"The New Relic Serilog Extension does not allow mapping of property {outputAsNewRelicProperty}");
            }

            _propertyMappings[propertyName] = LoggingExtensions.GetOutputName(outputAsNewRelicProperty);
            return(this);
        }
コード例 #21
0
ファイル: LoggingPageFilter.cs プロジェクト: assureddt/pact
    public void OnPageHandlerSelected(PageHandlerSelectedContext context)
    {
        var name = context.HandlerMethod?.Name ?? context.HandlerMethod?.MethodInfo.Name;

        if (name != null)
        {
            _diagnosticContext.Set("RazorPageHandler", name);
        }

        LoggingExtensions.EnrichFromFilterContext(_diagnosticContext, context);
    }
コード例 #22
0
        public Startup(IWebHostEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", reloadOnChange: true, optional: true)
                          .AddEnvironmentVariables();

            Configuration = builder.Build();

            Log.Logger = LoggingExtensions.AddLogging(Configuration);
        }
コード例 #23
0
        private void SetInstrinsics(Dictionary <string, object> dictionary, LoggingEvent loggingEvent)
        {
            if (dictionary == null)
            {
                return;
            }

            dictionary.Add(LoggingExtensions.GetOutputName(NewRelicLoggingProperty.Timestamp), loggingEvent.TimeStamp.ToUnixTimeMilliseconds());
            dictionary.Add(LoggingExtensions.GetOutputName(NewRelicLoggingProperty.ThreadName), loggingEvent.ThreadName);
            dictionary.Add(LoggingExtensions.GetOutputName(NewRelicLoggingProperty.MessageText), loggingEvent.RenderedMessage);
            dictionary.Add(LoggingExtensions.GetOutputName(NewRelicLoggingProperty.LogLevel), loggingEvent.Level);
        }
コード例 #24
0
 private void UpdateCurrentCell()
 {
     using (LoggingExtensions.Indent())
     {
         log.Debug("Updating current cell info");
         var cell = GetCurrentCell();
         if (!cell.IsUndefined)
         {
             CurrentCell = CurrentRowCellEnumerationService.GetCellInfo(currentCellPosition.GetCurrentCellIndex(CurrentRowCellEnumerationService));
         }
     }
 }
コード例 #25
0
        public void Mapping_NonReservedProperty_MapsProperly()
        {
            var testNRProperties = new Dictionary <string, string>()
            {
                { StringATestKey, "TestValue1" },
                { StringBTestKey, "TestValue2" }
            };

            var testEnricher = new TestEnricher()
                               .WithNewRelicMetadataValue(testNRProperties);

            // Build test data and configure formatter
            var expectedOutputs = new Dictionary <string, string>();
            var inputValues     = new Dictionary <string, int>();
            var testFormatter   = new NewRelicFormatter();

            foreach (var prop in _newRelicPropertiesNotReserved)
            {
                var propName  = Guid.NewGuid().ToString();
                var propValue = _random.Next(int.MaxValue);

                inputValues.Add(propName, propValue);
                expectedOutputs.Add(LoggingExtensions.GetOutputName(prop), propValue.ToString());

                testEnricher.WithUserPropValue(propName, propValue);
                testFormatter.WithPropertyMapping(propName, prop);
            }

            var testOutputSink = new TestSinkWithFormatter(testFormatter);

            var testLogger = TestHelpers.GetLogger(testOutputSink, testEnricher);

            // Act
            testLogger.Warning(LogMessage);

            // Assert
            Asserts.NoSerilogErrorsCountOutputs(_testRunDebugLogs, testOutputSink.InputsAndOutputs, LogMessage);

            var resultDic = TestHelpers.SerializeOutputJSON(testOutputSink.InputsAndOutputs[0]);

            foreach (var expectedOutput in expectedOutputs)
            {
                Asserts.KeyAndValueMatch(resultDic, expectedOutput.Key, expectedOutput.Value);
            }

            foreach (var inputVal in inputValues)
            {
                Assert.That(resultDic, Does.Not.ContainKey(inputVal.Key));
                Assert.That(resultDic, Does.Not.ContainKey(UserPropertyKeyPrefix + inputVal.Key));
            }
        }
コード例 #26
0
ファイル: DbCommandLogEntry.cs プロジェクト: kouweizhong/vita
        private string FormatStoredProcEntry()
        {
            if (string.IsNullOrWhiteSpace(_procCallFormat) || !_procCallFormat.Contains("{0}"))
            {
                _procCallFormat = "{0} {1}";
            }
            var fullFormat  = _procCallFormat + " -- @{2} ms {3}, {4} "; //exec time, row count, datetime
            var strParams   = LoggingExtensions.FormatSqlParameters(_command.Parameters, "{1}" /*Value only*/, ", ", maxValueLen: 50);
            var strRowCount = (RowCount < 0) ? string.Empty : StringHelper.SafeFormat(", {0} row(s)", RowCount);
            var strDateTime = _dateTime.ToString("[yyyy/MM/dd HH:mm:ss]");
            var result      = StringHelper.SafeFormat(fullFormat, _command.CommandText, strParams, ExecutionTime, strRowCount, strDateTime);

            return(result);
        }
コード例 #27
0
        public async Task <Server[]> DiscoverServers(CancellationToken cancellationToken, NetworkConfiguration configuration = null)
        {
            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            _logger?.LogInformation("Discovery started");

            var networkTask = DiscoverNetworkServers(cancellationToken, configuration);
            var localTask   = DiscoverLocalServers(cancellationToken);

            var results = await Task.WhenAll <Server[]>(networkTask, localTask);

            _logger?.LogInformation("Discovery ended");

            return(results.Where(s => s != null).SelectMany(s => s).Distinct().ToArray());
        }
コード例 #28
0
ファイル: DbCommandLogEntry.cs プロジェクト: kouweizhong/vita
        private string FormatSqlEntry()
        {
            const string fullFormat = "{0} \r\n{1} -- Time {2} ms{3}, {4} \r\n"; //sql, params, exec time, row count, datetime
            var          fParams    = string.Empty;

            if (_command.Parameters.Count > 0)
            {
                var strParams = LoggingExtensions.FormatSqlParameters(_command.Parameters, "{0}={1}", ", ", maxValueLen: 50);
                fParams = StringHelper.SafeFormat("-- Parameters: {0} \r\n", strParams);
            }
            var strRowCount = (RowCount < 0) ? string.Empty : StringHelper.SafeFormat("; {0} row(s)", RowCount);
            var strDateTime = _dateTime.ToString("[yyyy/MM/dd HH:mm:ss]");
            var result      = StringHelper.SafeFormat(fullFormat, _command.CommandText, fParams, ExecutionTime, strRowCount, strDateTime);

            return(result);
        }
コード例 #29
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            MappingExtensions.ConfigureMappingServices();
            builder.Services.AddScoped <IDataService, DataService>();
            builder.Services.AddScoped <IConfigurationService, ConfigurationService>();
            builder.Services.AddScoped <IBlobService, BlobService>();
            builder.Services.AddScoped <IImportService, ImportService>();
            builder.Services.AddScoped <ISplunkService, SplunkService>();

            var configuration = builder.GetContext().Configuration;

            builder.Services.AddLogging(loggingBuilder => LoggingExtensions.ConfigureLoggingServices(loggingBuilder, configuration));
            builder.Services.AddHttpClient("SplunkApiClient", options => Configuration.Infrastructure.HttpClient.HttpClientExtensions.ConfigureHttpClient(options))
            .ConfigurePrimaryHttpMessageHandler(() => Configuration.Infrastructure.HttpClient.HttpClientExtensions.CreateHttpMessageHandler());
            builder.Services.AddSmtpClientServices(configuration);
        }
コード例 #30
0
        public NetworkDiscovery(ILogger logger = default, NetworkConfiguration configuration = default)
        {
            _logger = logger;

            _logger?.LogDebug(LoggingExtensions.CurrentFunction());

            if (configuration == null)
            {
                configuration = new();
            }

            Configuration = configuration;

            client = new()
            {
                EnableBroadcast = true
            };
        }