예제 #1
0
        public static async void callAPIPage(string scope, string skipToken, string workspaceid, string workspacekey, string logName, ILogger log, string myJson)
        {
            var    azureServiceTokenProvider = new AzureServiceTokenProvider();
            string AuthToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");

            using (var client = new HttpClient())
            {
                // Setting Authorization.
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);


                // Setting Base address.
                client.BaseAddress = new Uri("https://management.azure.com");
                // Setting content type.
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Initialization.
                HttpResponseMessage response = new HttpResponseMessage();

                AzureLogAnalytics logAnalytics = new AzureLogAnalytics(
                    workspaceId: $"{workspaceid}",
                    sharedKey: $"{workspacekey}",
                    logType: $"{logName}");

                string newURL = "/" + scope + "/providers/Microsoft.CostManagement/query?api-version=2019-11-01&" + skipToken;
                response = await client.PostAsync(newURL, new StringContent(myJson, Encoding.UTF8, "application/json"));

                QueryResults result = JsonConvert.DeserializeObject <QueryResults>(response.Content.ReadAsStringAsync().Result);


                jsonResult = "[";
                for (int i = 0; i < result.properties.rows.Length; i++)
                {
                    object[] row  = result.properties.rows[i];
                    double   cost = Convert.ToDouble(row[0]);

                    if (i == 0)
                    {
                        jsonResult += $"{{\"PreTaxCost\": {cost},\"Date\": \"{row[1]}\",\"ResourceId\": \"{row[2]}\",\"ResourceType\": \"{row[3]}\",\"SubscriptionName\": \"{row[4]}\",\"ResourceGroup\": \"{row[5]}\"}}";
                    }
                    else
                    {
                        jsonResult += $",{{\"PreTaxCost\": {cost},\"Date\": \"{row[1]}\",\"ResourceId\": \"{row[2]}\",\"ResourceType\": \"{row[3]}\",\"SubscriptionName\": \"{row[4]}\",\"ResourceGroup\": \"{row[5]}\"}}";
                    }
                }

                jsonResult += "]";

                //log.LogInformation($"Cost Data: {jsonResult}");
                logAnalytics.Post(jsonResult);

                if (result.properties.nextLink != null)
                {
                    string nextLink = result.properties.nextLink.ToString();
                    skipToken = nextLink.Split('&')[1];
                    Console.WriteLine(skipToken);
                    callAPIPage(scope, skipToken, workspaceid, workspacekey, logName, log, myJson);
                }
            }
        }
예제 #2
0
        public static async Task Run([EventHubTrigger("ehapimcustomlogspostapi", Connection = "EventHubConnectionAppSetting")] EventData[] events, ILogger log)
        {
            var exceptions = new List <Exception>();

            foreach (EventData eventData in events)
            {
                try
                {
                    string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);

                    // Replace these two lines with your processing logic.
                    log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
                    await Task.Yield();

                    var logAnalyticsWorkspaceId            = Environment.GetEnvironmentVariable("LogAnalyticsWorkspaceId");
                    var logAnalyticsWorkspaceKey           = Environment.GetEnvironmentVariable("LogAnalyticsWorkspaceKey");
                    var logAnalyticsWorkspaceWorkspaceName = Environment.GetEnvironmentVariable("LogAnalyticsWorkspaceWorkspaceName");

                    AzureLogAnalytics azureLogAnalytics = new AzureLogAnalytics(
                        logAnalyticsWorkspaceId,
                        logAnalyticsWorkspaceKey,
                        logAnalyticsWorkspaceWorkspaceName,
                        "2016-04-01"
                        );

                    string[] words = messageBody.Split(',');
                    //DateTime.UtcNow, context.Deployment.ServiceName, context.RequestId, context.Request.IpAddress, context.Operation.Name, customCorrelationId
                    // 0,              1,                              2,                 3,                         4,                      5
                    var logMsg = new
                    {
                        DateTime            = words[0],
                        ServiceName         = words[1],
                        RequestId           = words[2],
                        IpAddress           = words[3],
                        OpName              = words[4],
                        customCorrelationID = words[5].Substring(21)
                    };

                    var jsonLogMsg = JsonConvert.SerializeObject(logMsg);
                    azureLogAnalytics.Post(jsonLogMsg);
                }

                catch (Exception e)
                {
                    // We need to keep processing the rest of the batch - capture this exception and continue.
                    // Also, consider capturing details of the message that failed processing so it can be processed again later.
                    exceptions.Add(e);
                }
            }
            // Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.
            if (exceptions.Count > 1)
            {
                throw new AggregateException(exceptions);
            }

            if (exceptions.Count == 1)
            {
                throw exceptions.Single();
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            var    azureServiceTokenProvider = new AzureServiceTokenProvider();
            string AuthToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");

            Console.WriteLine(AuthToken);

            using (var client = new HttpClient())
            {
                // Setting Authorization.
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthToken);

                // Setting Base address.
                client.BaseAddress = new Uri("https://management.azure.com");

                // Setting content type.
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Initialization.
                HttpResponseMessage response = new HttpResponseMessage();

                DateTime startTime = DateTime.Now.AddDays(-30);
                DateTime endTime   = DateTime.Now;
                string   start     = startTime.ToString("MM/dd/yyyy");
                string   end       = endTime.ToString("MM/dd/yyyy");

                string myJson = @"{
                        'dataset': {
                            'aggregation': {
                            'totalCost': {
                                'function': 'Sum',
                                'name': 'PreTaxCost'
                            }
                        },
                        'granularity': 'Daily',
                        'grouping': [
                            {
                                'name': 'ResourceId',
                                'type': 'Dimension'
                            },
                            {
                                'name': 'ResourceType',
                                'type': 'dimension'
                            },
                            {
                                'name': 'SubscriptionName',
                                'type': 'dimension'
                            },
                            {
                                'name': 'ResourceGroup',
                                'type': 'dimension'
                            }
                        ]
                    },
                    'timePeriod': {
                        'from': '" + start + @"',
                        'to': '" + end + @"'
                    },
                    'timeframe': 'Custom',
                    'type': 'Usage'
                }";

                log.LogInformation($"Cost Query: {myJson}");

                AzureLogAnalytics logAnalytics = new AzureLogAnalytics(
                    workspaceId: $"{workspaceid}",
                    sharedKey: $"{workspacekey}",
                    logType: $"{logName}");

                foreach (string scope in scopes)
                {
                    log.LogInformation($"Scope: {scope}");
                    // HTTP Post
                    response = await client.PostAsync("/" + scope + "/providers/Microsoft.CostManagement/query?api-version=2019-11-01", new StringContent(myJson, Encoding.UTF8, "application/json"));

                    Console.WriteLine(client);
                    QueryResults result = Newtonsoft.Json.JsonConvert.DeserializeObject <QueryResults>(response.Content.ReadAsStringAsync().Result);


                    jsonResult = "[";
                    for (int i = 0; i < result.properties.rows.Length; i++)
                    {
                        object[] row  = result.properties.rows[i];
                        double   cost = Convert.ToDouble(row[0]);

                        if (i == 0)
                        {
                            jsonResult += $"{{\"PreTaxCost\": {cost},\"Date\": \"{row[1]}\",\"ResourceId\": \"{row[2]}\",\"ResourceType\": \"{row[3]}\",\"SubscriptionName\": \"{row[4]}\",\"ResourceGroup\": \"{row[5]}\"}}";
                        }
                        else
                        {
                            jsonResult += $",{{\"PreTaxCost\": {cost},\"Date\": \"{row[1]}\",\"ResourceId\": \"{row[2]}\",\"ResourceType\": \"{row[3]}\",\"SubscriptionName\": \"{row[4]}\",\"ResourceGroup\": \"{row[5]}\"}}";
                        }
                    }

                    jsonResult += "]";

                    log.LogInformation($"Cost Data: {jsonResult}");
                    logAnalytics.Post(jsonResult);

                    string nextLink = result.properties.nextLink.ToString();

                    if (!string.IsNullOrEmpty(nextLink))
                    {
                        string skipToken = nextLink.Split('&')[1];
                        callAPIPage(scope, skipToken, workspaceid, workspacekey, logName, log, myJson);
                    }

                    //return new OkObjectResult(jsonResult);
                }
            }

            return(new OkObjectResult(jsonResult));
        }