[Azure] Azure Traffic Manager - 使用 C# 拿到 時間區間內的 Activity Logs

2020-12-24

最近就是在跟 Azure Traffic Manager 交手,其實是最近打算做一個系統來控制我們專案的東西,但是如何知道我們操作行為錯誤,不能只靠程式的  Exception 吧,後來發現其實會有 Activity Log ,所以我們試著去讀取紀錄,來判斷我們操作的行為對不對..



先說一下操控案例,延續我前幾天寫的文章,我會以讀取我操控 Traffic Manager 的 Activity Log 來當作範例。

1.首先你得先去 拿Azure  操控權限,詳情請參考  https://blog.no2don.com/2020/09/azurec-c-azure.html
2. 專案這邊 安裝該安裝的 nuget

https://www.nuget.org/packages/Microsoft.Azure.Management.Fluent/

https://www.nuget.org/packages/Microsoft.Azure.Management.ResourceManager.Fluent/

3. 程式碼的部分

.StartingFrom(DateTime.Now.AddHours(-24))
        .EndsBefore(DateTime.Now)

這邊是代表,我要從現在開始拿到過去24小時的紀錄,取到的時間是 UTC ,其中你可以透過 Caller 如果是你的 Azure 帳號,代表你是在官網上面操控的,如果是 跟你在 Step1 的 appId 是一樣的代表就是你用 API操控的,其他資訊就看你怎麼判斷了,需要注意的大概就是我上面敘述的,其他就看 code 吧


var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal( "aaaaaaa-bbbb-cccc-dddd-xxxxxx", "p-passwordtoekntoken_9MtA_JNzW_", "aaaaaaa-bbbb-cccc-dddd-ba7182d7e4d7", AzureEnvironment.AzureGlobalCloud); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); var logs = azure.ActivityLogs.DefineQuery() .StartingFrom(DateTime.Now.AddHours(-24)) .EndsBefore(DateTime.Now) .WithAllPropertiesInResponse() .FilterByResource("/subscriptions/dsadsdas-asda-asdas-sdas-dsadsadasdsad/resourceGroups/spinus/providers/Microsoft.Network/trafficManagerProfiles/site1") .Execute(); Console.WriteLine("Check Traffic Manager Activity Logs : "); var i = 0; foreach (var eventData in logs) { Console.WriteLine("Time: " + eventData.EventTimestamp.Value.ToString("yyyy-MM-dd HH:mm:ss")); Console.WriteLine("Operation: " + eventData.OperationName?.LocalizedValue); Console.WriteLine("Caller: " + eventData.Caller); Console.WriteLine("APP_ID: " + eventData.Claims.GetValueOrDefault("appid")); if (eventData.Status.Value == "Failed") { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Status: " + eventData.Status.Value); Console.WriteLine("ErrorMessage: " + eventData.Properties.GetValueOrDefault("statusMessage")); } else { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Status: " + eventData.Status.Value); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("--------"); Console.ForegroundColor = ConsoleColor.White; }

result:


當麻許的碎念筆記 2014 | Donma Hsu Design.