Table of Contents
Problem Description
Solution
In the Access control (IAM) page of Redis, search through the application name in step 1 and grant permission to Monitoring Reader
Step 3: Write Python code, use requests to send psot, get request
Powershell
Home Database Redis How to use Python code to obtain monitoring indicator values ​​​​of Azure Redis

How to use Python code to obtain monitoring indicator values ​​​​of Azure Redis

May 28, 2023 am 11:16 AM
python redis

Problem Description

Through the Metrics monitoring page, we can know the running status and various indicators of the current resources (such as Redis). What if we need to download indicators locally or generate JSON data and import it to a third-party monitoring platform? Can Azure export various indicator data through Python code or Powershell script?

如何使用Python代码获取Azure Redis的监控指标值

Solution

Yes!​ ​ PowerShell command can use Get-AzMetric or az monitor metrics list command to obtain the Metrics value of the resource.

  • Get-AzMetric:Gets the metric values ​​of a resource. https://docs.microsoft.com/en-us/powershell/module /az.monitor/get-azmetric?view=azps-5.4.0&viewFallbackFrom=azps-5.2.0

  • ## az monitor metrics list: List the metric values ​​for a resource. https://docs.microsoft.com/en-us/cli/azure/monitor/metrics?view=azure-cli-latest#az_monitor_metrics_list

And Using Python code, you can use Metrics' REST API to implement

  • Metrics – List: Lists the metric values ​​for a resource. https://docs .microsoft.com/en-us/rest/api/monitor/metrics/list

  • Register the application in AAD to obtain the Access Token for accessing Redis Metrics in Python code: (Apply The program is registered to the Microsoft identity platform: https://docs.azure.cn/zh-cn/active-directory/develop/quickstart-register-app)

Note: You must first log in to Azure to use Powershell. Use the command Connect-AzAccount -Environment AzureChinaCloud or az cloud set –name AzureChinaCloud and az login.

To use Python code, you need to first obtain the Token to access Redis Metrics. To obtain the Token, you can register an application in Azure AD, and then give the application the reader permission in Redis access control to read Metris data.

Execution steps

Python

Step 1: Register AAD application, copy application ID, client access password

  • Log in to the Azure platform, enter the AAD page, click

    App registrations: https://portal.azure.cn/?l=en.en-us#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps

  • Click the "

    New Registration" button, enter the application name, leave other values ​​as default, click Save

  • After the creation is successful, enter the application page , import it to the "

    Certificates & secrets" page, create the Client Secret you need to use and copy it. In the third step, you need to use

  • to copy the ## on the application page. #Tenant ID, Applicaiton ID

    needs to be used in the third step of the code

See the following animation for the specific operation process:

如何使用Python代码获取Azure Redis的监控指标值Step 2: Grant permission to obtain Metrics

In the Access control (IAM) page of Redis, search through the application name in step 1 and grant permission to Monitoring Reader

如何使用Python代码获取Azure Redis的监控指标值Note: If permission is not granted, a similar error will be reported in the code:

##Status Code: Response Content: b'{"error":{"code":"AuthorizationFailed","message":"The client 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' with object id 'xxxxxxxx -xxxx-xxxx-xxxx-36166b5f7276' does not have authorization to perform action 'microsoft.insights/metrics/read' over scope '/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/xxxx-rg/providers/Microsoft .Cache/Redis/xxxx/providers/microsoft.insights' or the scope is invalid. If access was recently granted, please refresh your credentials."}}'

Step 3: Write Python code, use requests to send psot, get request

  • There are two main parts in the code: one is to obtain Access Token, and the other is to obtain Metrics Data

  • The highlighted content needs to be replaced with the corresponding resource information and the information prepared in the first step

  • After obtaining the Access Token In the Body content, grant_type is a fixed value, which is client_credentials. The value of resource is the management endpoint of azure in China: https://management.chinacloudapi.cn

import requestsimport json##Part 1: Get Access Tokenaadurl="https://login.chinacloudapi.cn/<your aad tenant id>/oauth2/token"aadbody={&#39;grant_type&#39;:&#39;client_credentials&#39;,&#39;client_id&#39;:&#39;your aad client id&#39;,&#39;client_secret&#39;:&#39;your aad client secret&#39;,&#39;resource&#39;:&#39;https://management.chinacloudapi.cn&#39;}
rtoken= requests.post(aadurl, data=aadbody)##print(rtoken)objtoken = json.loads(rtoken.text)##print(obj[&#39;access_token&#39;])##Part 2: Get the Metrics Value by Tokenheaders = {&#39;content-type&#39;: "application/json",           &#39;Authorization&#39;: &#39;Bearer &#39;+objtoken[&#39;access_token&#39;]
        }

url= "https://management.chinacloudapi.cn/subscriptions/<subscriptions>/resourceGroups/<resourceGroups>/providers/Microsoft.Cache/Redis/<your redis name>/providers/microsoft.insights/metrics?api-version=2018-01-01&metricnames=expiredkeys,usedmemory"r = requests.get(url, headers=headers)print(&#39;Status Code: &#39; + str(r))print(&#39;Response Content: &#39; + str(r.content))
Copy after login

The operation effect is as follows:

如何使用Python代码获取Azure Redis的监控指标值

Powershell

  • Log in to azure

  • Prepare az monitor metrics list command

az cloud set --name AzureChinaCloud

az login

az monitor metrics list --resource /subscriptions/<your subscriptions>/resourceGroups/<resourceGroups>/providers/Microsoft.Cache/Redis/<your redis name> --metric usedmemory --aggregation Maximum --interval PT1M
Copy after login

The execution effect is as follows:

如何使用Python代码获取Azure Redis的监控指标值 如何使用Python代码获取Azure Redis的监控指标值


The above is the detailed content of How to use Python code to obtain monitoring indicator values ​​​​of Azure Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles