private void LogEndGetLogs(string invocationId, LogListResponse result)
 {
     if (TracingAdapter.IsEnabled)
     {
         TracingAdapter.Exit(invocationId, result);
     }
 }
Пример #2
0
        /// <summary>
        /// The List Log operation lists the logs for the resource.
        /// </summary>
        /// <param name='resourceUri'>
        /// Optional.
        /// </param>
        /// <param name='filterString'>
        /// Optional.
        /// </param>
        /// <param name='definitions'>
        /// Optional.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The List Log values operation response.
        /// </returns>
        public async Task <LogListResponse> GetLogsAsync(string resourceUri, string filterString, IEnumerable <LogDefinition> definitions, CancellationToken cancellationToken)
        {
            // Validate

            // Tracing
            bool   shouldTrace  = TracingAdapter.IsEnabled;
            string invocationId = null;

            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary <string, object> tracingParameters = new Dictionary <string, object>();
                tracingParameters.Add("resourceUri", resourceUri);
                tracingParameters.Add("filterString", filterString);
                tracingParameters.Add("definitions", definitions);
                TracingAdapter.Enter(invocationId, this, "GetLogsAsync", tracingParameters);
            }

            // Construct URL
            string url = "";

            url = url + "/providers/microsoft.insights/logs";
            string baseUrl = this.Client.BaseUri.AbsoluteUri;

            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;

            try
            {
                httpRequest            = new HttpRequestMessage();
                httpRequest.Method     = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers
                httpRequest.Headers.Add("Accept", "application/json");
                httpRequest.Headers.Add("x-ms-version", "2014-04-01");

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    LogListResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                        result = new LogListResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            LogCollection logCollectionInstance = new LogCollection();
                            result.LogCollection = logCollectionInstance;

                            JToken valueArray = responseDoc["value"];
                            if (valueArray != null && valueArray.Type != JTokenType.Null)
                            {
                                foreach (JToken valueValue in ((JArray)valueArray))
                                {
                                    Log logInstance = new Log();
                                    logCollectionInstance.Value.Add(logInstance);

                                    JToken categoryValue = valueValue["category"];
                                    if (categoryValue != null && categoryValue.Type != JTokenType.Null)
                                    {
                                        LocalizableString categoryInstance = new LocalizableString();
                                        logInstance.Category = categoryInstance;

                                        JToken valueValue2 = categoryValue["value"];
                                        if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
                                        {
                                            string valueInstance = ((string)valueValue2);
                                            categoryInstance.Value = valueInstance;
                                        }

                                        JToken localizedValueValue = categoryValue["localizedValue"];
                                        if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
                                        {
                                            string localizedValueInstance = ((string)localizedValueValue);
                                            categoryInstance.LocalizedValue = localizedValueInstance;
                                        }
                                    }

                                    JToken startTimeValue = valueValue["startTime"];
                                    if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTime startTimeInstance = ((DateTime)startTimeValue);
                                        logInstance.StartTime = startTimeInstance;
                                    }

                                    JToken endTimeValue = valueValue["endTime"];
                                    if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                                    {
                                        DateTime endTimeInstance = ((DateTime)endTimeValue);
                                        logInstance.EndTime = endTimeInstance;
                                    }

                                    JToken valueArray2 = valueValue["value"];
                                    if (valueArray2 != null && valueArray2.Type != JTokenType.Null)
                                    {
                                        foreach (JToken valueValue3 in ((JArray)valueArray2))
                                        {
                                            LogValue logValueInstance = new LogValue();
                                            logInstance.Value.Add(logValueInstance);

                                            JToken timeValue = valueValue3["time"];
                                            if (timeValue != null && timeValue.Type != JTokenType.Null)
                                            {
                                                DateTime timeInstance = ((DateTime)timeValue);
                                                logValueInstance.Time = timeInstance;
                                            }

                                            JToken resourceIdValue = valueValue3["resourceId"];
                                            if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
                                            {
                                                string resourceIdInstance = ((string)resourceIdValue);
                                                logValueInstance.ResourceId = resourceIdInstance;
                                            }

                                            JToken operationNameValue = valueValue3["operationName"];
                                            if (operationNameValue != null && operationNameValue.Type != JTokenType.Null)
                                            {
                                                string operationNameInstance = ((string)operationNameValue);
                                                logValueInstance.OperationName = operationNameInstance;
                                            }

                                            JToken operationVersionValue = valueValue3["operationVersion"];
                                            if (operationVersionValue != null && operationVersionValue.Type != JTokenType.Null)
                                            {
                                                string operationVersionInstance = ((string)operationVersionValue);
                                                logValueInstance.OperationVersion = operationVersionInstance;
                                            }

                                            JToken categoryValue2 = valueValue3["category"];
                                            if (categoryValue2 != null && categoryValue2.Type != JTokenType.Null)
                                            {
                                                string categoryInstance2 = ((string)categoryValue2);
                                                logValueInstance.Category = categoryInstance2;
                                            }

                                            JToken resultTypeValue = valueValue3["resultType"];
                                            if (resultTypeValue != null && resultTypeValue.Type != JTokenType.Null)
                                            {
                                                string resultTypeInstance = ((string)resultTypeValue);
                                                logValueInstance.ResultType = resultTypeInstance;
                                            }

                                            JToken resultSignatureValue = valueValue3["resultSignature"];
                                            if (resultSignatureValue != null && resultSignatureValue.Type != JTokenType.Null)
                                            {
                                                string resultSignatureInstance = ((string)resultSignatureValue);
                                                logValueInstance.ResultSignature = resultSignatureInstance;
                                            }

                                            JToken resultDescriptionValue = valueValue3["resultDescription"];
                                            if (resultDescriptionValue != null && resultDescriptionValue.Type != JTokenType.Null)
                                            {
                                                string resultDescriptionInstance = ((string)resultDescriptionValue);
                                                logValueInstance.ResultDescription = resultDescriptionInstance;
                                            }

                                            JToken durationMsValue = valueValue3["durationMs"];
                                            if (durationMsValue != null && durationMsValue.Type != JTokenType.Null)
                                            {
                                                int durationMsInstance = ((int)durationMsValue);
                                                logValueInstance.DurationMs = durationMsInstance;
                                            }

                                            JToken callerIpAddressValue = valueValue3["callerIpAddress"];
                                            if (callerIpAddressValue != null && callerIpAddressValue.Type != JTokenType.Null)
                                            {
                                                string callerIpAddressInstance = ((string)callerIpAddressValue);
                                                logValueInstance.CallerIpAddress = callerIpAddressInstance;
                                            }

                                            JToken correlationIdValue = valueValue3["correlationId"];
                                            if (correlationIdValue != null && correlationIdValue.Type != JTokenType.Null)
                                            {
                                                string correlationIdInstance = ((string)correlationIdValue);
                                                logValueInstance.CorrelationId = correlationIdInstance;
                                            }

                                            JToken identityValue = valueValue3["identity"];
                                            if (identityValue != null && identityValue.Type != JTokenType.Null)
                                            {
                                                string identityInstance = ((string)identityValue);
                                                logValueInstance.Identity = identityInstance;
                                            }

                                            JToken levelValue = valueValue3["level"];
                                            if (levelValue != null && levelValue.Type != JTokenType.Null)
                                            {
                                                string levelInstance = ((string)levelValue);
                                                logValueInstance.Level = levelInstance;
                                            }

                                            JToken locationValue = valueValue3["location"];
                                            if (locationValue != null && locationValue.Type != JTokenType.Null)
                                            {
                                                string locationInstance = ((string)locationValue);
                                                logValueInstance.Location = locationInstance;
                                            }

                                            JToken propertiesSequenceElement = ((JToken)valueValue3["properties"]);
                                            if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
                                            {
                                                foreach (JProperty property in propertiesSequenceElement)
                                                {
                                                    string propertiesKey   = ((string)property.Name);
                                                    string propertiesValue = ((string)property.Value);
                                                    logValueInstance.Properties.Add(propertiesKey, propertiesValue);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return(result);
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
        /// <summary>
        /// Get logs.
        /// </summary>
        /// <param name="resourceUri">The resourceUri</param>
        /// <param name="filterString">The filter string</param>
        /// <param name="definitions">The log definitions</param>
        /// <param name="cancellationToken">The cancellation token</param>
        /// <returns></returns>
        public async Task <LogListResponse> GetLogsAsync(
            string resourceUri,
            string filterString,
            IEnumerable <LogDefinition> definitions,
            CancellationToken cancellationToken)
        {
            if (definitions == null)
            {
                throw new ArgumentNullException("definitions");
            }

            if (resourceUri == null)
            {
                throw new ArgumentNullException("resourceUri");
            }

            // Ensure exactly one '/' at the start
            resourceUri = '/' + resourceUri.TrimStart('/');

            LogListResponse result;
            string          invocationId = TracingAdapter.NextInvocationId.ToString(CultureInfo.InvariantCulture);

            // If no definitions provided, return empty collection
            if (!definitions.Any())
            {
                this.LogStartGetLogs(invocationId, resourceUri, filterString, definitions);
                result = new LogListResponse()
                {
                    RequestId     = Guid.NewGuid().ToString("D"),
                    StatusCode    = HttpStatusCode.OK,
                    LogCollection = new LogCollection()
                    {
                        Value = new Log[0]
                    }
                };

                this.LogEndGetLogs(invocationId, result);

                return(result);
            }

            // Parse LogFilter. Reusing the metric filter.
            // We might consider extracting the parsing functionality to a class with a less specific name
            MetricFilter filter = MetricFilterExpressionParser.Parse(filterString, false);

            if (filter.StartTime == default(DateTime))
            {
                throw new InvalidOperationException("startTime is required");
            }

            if (filter.EndTime == default(DateTime))
            {
                throw new InvalidOperationException("endTime is required");
            }

            this.LogStartGetLogs(invocationId, resourceUri, filterString, definitions);

            var logsPerBlob = new Dictionary <string, Task <Log> >(StringComparer.OrdinalIgnoreCase);

            // We download all the relevant blobs first and then use the data later, to avoid download the same blob more than once.
            foreach (LogDefinition logDefinition in definitions)
            {
                foreach (BlobInfo blobInfo in logDefinition.BlobLocation.BlobInfo)
                {
                    if (blobInfo.EndTime < filter.StartTime || blobInfo.StartTime >= filter.EndTime)
                    {
                        continue;
                    }

                    string blobId = GetBlobEndpoint(blobInfo);
                    if (!logsPerBlob.ContainsKey(blobId))
                    {
                        logsPerBlob.Add(blobId, FetchLogFromBlob(blobInfo.BlobUri, filter, logDefinition.Category));
                    }
                }
            }

            foreach (var task in logsPerBlob.Values)
            {
                await task;
            }

            var logsPerCategory = new Dictionary <string, Log>();

            foreach (var task in logsPerBlob.Values)
            {
                Log log = task.Result;
                Log existingLog;
                if (logsPerCategory.TryGetValue(log.Category.Value, out existingLog))
                {
                    ((List <LogValue>)existingLog.Value).AddRange(log.Value);
                    existingLog.StartTime = this.Min(log.StartTime, existingLog.StartTime);
                    existingLog.EndTime   = this.Max(log.StartTime, existingLog.StartTime);
                }
                else
                {
                    logsPerCategory.Add(log.Category.Value, log);
                }
            }

            result = new LogListResponse
            {
                RequestId     = Guid.NewGuid().ToString("D"),
                StatusCode    = HttpStatusCode.OK,
                LogCollection = new LogCollection
                {
                    Value = logsPerCategory.Values.ToList()
                }
            };

            this.LogEndGetLogs(invocationId, result);

            return(result);
        }