private ITableEntity CreateTableEntity(LogEventInfo logEvent, string partitionKey)
        {
            var rowKey = RenderLogEvent(RowKey, logEvent);

            if (ContextProperties.Count > 0)
            {
                var  entity = new TableEntity(partitionKey, rowKey);
                bool logTimeStampOverridden = "LogTimeStamp".Equals(ContextProperties[0].Name, StringComparison.OrdinalIgnoreCase);
                if (!logTimeStampOverridden)
                {
                    entity.Add("LogTimeStamp", logEvent.TimeStamp.ToUniversalTime());
                }

                for (int i = 0; i < ContextProperties.Count; ++i)
                {
                    var contextproperty = ContextProperties[i];
                    if (string.IsNullOrEmpty(contextproperty.Name))
                    {
                        continue;
                    }

                    var propertyValue = contextproperty.Layout != null?RenderLogEvent(contextproperty.Layout, logEvent) : string.Empty;

                    if (logTimeStampOverridden && i == 0 && string.IsNullOrEmpty(propertyValue))
                    {
                        continue;
                    }

                    entity.Add(contextproperty.Name, propertyValue);
                }

                return(entity);
            }
            else
            {
                var layoutMessage = RenderLogEvent(Layout, logEvent);
                return(new NLogEntity(logEvent, layoutMessage, _machineName, partitionKey, rowKey, LogTimeStampFormat));
            }
        }
Esempio n. 2
0
        async Task IAzureTableStoreClient.AddRecordAsync <T>(string tableName, string partitionKey, string rowKey, T record, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(tableName))
            {
                throw new ArgumentNullException(nameof(tableName));
            }
            if (string.IsNullOrWhiteSpace(partitionKey))
            {
                throw new ArgumentNullException(nameof(partitionKey));
            }
            if (string.IsNullOrWhiteSpace(rowKey))
            {
                throw new ArgumentNullException(nameof(rowKey));
            }
            if (record is null)
            {
                throw new ArgumentNullException(nameof(record));
            }
            if (0 >= record.Count)
            {
                throw new ArgumentOutOfRangeException("The record does not contain any data");
            }
            if (record.ContainsKey("PartitionKey"))
            {
                throw new ArgumentOutOfRangeException("The record cannot contain a key called PartitionKey");
            }
            if (record.ContainsKey("RowKey"))
            {
                throw new ArgumentOutOfRangeException("The record cannot contain a key called RowKey");
            }

            cancellationToken.ThrowIfCancellationRequested();

            var managedIdentityCredential = new DefaultAzureCredential();

            var tableClientOptions = GetTableClientOptions(_geoRedundantServiceUrl);

            var tableServiceClient = new TableServiceClient(_primaryServiceUrl, managedIdentityCredential, tableClientOptions);

            var tableClient = tableServiceClient.GetTableClient(tableName);

            var entity = new TableEntity(partitionKey, rowKey);

            foreach (var kvp in record)
            {
                entity.Add(kvp.Key, kvp.Value);
            }

            try
            {
                using var response = await tableClient.AddEntityAsync(entity, cancellationToken);

                if (!IsSuccessStatusCode(response?.Status ?? int.MinValue))
                {
                    Debug.Assert(response is not null);

                    _logger?.LogDebug("Unable to write a record to table storage '{TableName}'.  {ClientRequestId} - Reported '{ReasonPhrase}' with status code: '{StatusCode} {StatusCodeName}'", response.ClientRequestId, tableName, response.ReasonPhrase, response.Status, Enum.Parse(typeof(HttpStatusCode), Convert.ToString(response.Status, CultureInfo.InvariantCulture)));

                    // TODO - Add custom table storage exception

                    throw new ApplicationException($"{response.ClientRequestId}: Unable to write the record to table storage '{tableName}'.  Please consult log files for more information");
                }
            }
            catch (AuthenticationFailedException ex)
            {
                _logger?.LogError(ex, "Unable to authenticate with the Azure Table Storage service using the default credentials.  Please ensure the user account this application is running under has permissions to access the Blob Storage account we are targeting");

                throw;
            }
            catch (RequestFailedException ex)
            {
                _logger?.LogError(ex, "Unable to access the Table storage endpoint as the Add request failed: '{StatusCode} {StatusCodeName}'", ex.Status, Enum.Parse(typeof(HttpStatusCode), Convert.ToString(ex.Status, CultureInfo.InvariantCulture)));

                throw;
            }
        }