文档

阿里云成本分析

更新时间:

通过内置阿里云成本分析模板,可以快速获取所需的成本分析数据。本文介绍日志服务阿里云成本分析的使用方法。

前提条件

  • 已创建RAM用户并完成授权。具体操作,请参见创建RAM用户并完成授权

  • 已配置环境变量ALIBABA_CLOUD_ACCESS_KEY_IDALIBABA_CLOUD_ACCESS_KEY_SECRET。具体操作,请参见配置环境变量

    重要
    • 阿里云账号的AccessKey拥有所有API的访问权限,建议您使用RAM用户的AccessKey进行API访问或日常运维。

    • 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里,否则可能导致AccessKey泄露,威胁您账号下所有资源的安全。

  • 已开通日志服务成本管家。更多操作,请参见自助分析阿里云账单

步骤一:初始化日志服务Client

LogClient是日志服务的Python客户端,用于管理Project、Logstore等日志服务资源。使用Python SDK发起日志服务请求,您需要初始化一个Client实例。示例代码如下所示:

# Setup basic client
# !pip install -U matplotlib
import time
import os
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import aliyun.log as sls

# 日志服务的服务入口。
endpoint = "cn-beijing.log.aliyuncs.com"

# 本示例从环境变量中获取AccessKey ID和AccessKey Secret。
accessId = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID', '')
accessKey = os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET', '')
# Project名称。
project  = "YOUR_SLS_PROJECT"
# MetricStore名称。
metricstore = "YOUR_SLS_METRICSTORE"
# 保存巡检结果的Logstore。
sink_logstore = 'YOUR_SLS_LOGSTORE_FOR_RESULTS_WRITE' 
# 设置任务名称。
task_name = "YOUR_TASK_NAME" 
# 创建LogClient。
client = sls.LogClient(endpoint, accessId, accessKey)

步骤二:获取账单数据

示例代码如下所示:

import time
import pandas as pd

import matplotlib.pyplot as plt

project  = "YOUR_SLS_PROJECT"
logstore = "YOUR_SLS_LOGSTORE"

def query_logstore(query, stime, etime):

    datas = []
    for i in client.get_log_all(project, logstore, stime, etime, query=query):
        for log in i.logs:
            datas.append(log.get_contents())

    # Convert datas to pandas dataframe
    df_ret = pd.DataFrame(datas)
    return df_ret

步骤三:统计和分析账单

  • 查看账单总体趋势

    示例代码如下:

    %matplotlib inline
    
    etime = int(time.time())
    stime = etime - 86400 * 7
    
    query = '''
    source:bill | 
    select date_format(__time__,'%Y-%m-%d') as ds, round(sum(PretaxAmount),3) as cost group by ds order by ds
    '''
    
    df_bill = query_logstore(query, stime, etime)
    df_bill['cost'] = df_bill['cost'].astype(float)
    
    #  Plot Total Cost Bar
    figure = plt.figure(figsize=(18,5),dpi=98)
    plt.title(u"Total Cost", fontproperties='SimHei',fontsize = 15)
    plt.bar(df_bill['ds'], df_bill['cost'],label='Cost(CNY)')
    plt.legend(loc='best')
  • 统计云产品费用

    示例代码如下:

    %matplotlib inline
    
    etime = int(time.time())
    stime = etime - 86400 * 7
    
    query = '''
    source:bill | 
    select ProductName,ProductCode, round(sum(PretaxAmount),3) as cost from log group by ProductCode,ProductName
    '''
    
    df_product_bill = query_logstore(query, stime, etime)
    df_product_bill['cost'] = df_product_bill['cost'].astype(float)
    
    df_product_bill.sort_values(by=['cost'], ascending=False).head(10)
  • 查看ECS一周账单趋势

    示例代码如下:

    %matplotlib inline
    
    etime = int(time.time())
    stime = etime - 86400 * 7
    
    query = '''
    source:bill and ProductCode:ecs | 
    select date_format(__time__,'%Y-%m-%d') as ds, round(sum(PretaxAmount),3) as cost group by ds order by ds
    '''
    
    df_ecs_bill = query_logstore(query, stime, etime)
    df_ecs_bill['cost'] = df_ecs_bill['cost'].astype(float)
    
    # Plot ECS Cost Bar
    figure = plt.figure(figsize=(18,5),dpi=98)
    plt.title(u"ECS Cost", fontproperties='SimHei',fontsize = 15)
    plt.bar(df_ecs_bill['ds'], df_ecs_bill['cost'],label='Cost(CNY)')
    plt.legend(loc='best')
  • 查看ECS一周账单明细

    示例代码如下:

    etime = int(time.time())
    stime = etime - 86400 * 7
    
    query = '''
    ProductCode:ECS and source: instance_bill | 
    select BillingDate,Region,instanceid,Nickname,BillingItem,InstanceConfig,IntranetIP,PretaxAmount limit 10000
    '''
    
    df_ecs_bill_detail = query_logstore(query, stime, etime)
    
    df_ecs_bill_detail['PretaxAmount'] = df_ecs_bill_detail['PretaxAmount'].astype(float)
    df_ecs_bill_detail.sort_values(by=['PretaxAmount'],ascending=False)[['BillingDate','Region','Nickname','InstanceConfig','PretaxAmount']].head(10)
  • 本页导读 (1)
文档反馈