在命令行中添加Azure应用程序的洞察力状态监视器 [英] add Azure Application insight Status Monitor from command line

查看:404
本文介绍了在命令行中添加Azure应用程序的洞察力状态监视器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<一个href=\"http://azure.microsoft.com/en-us/documentation/articles/app-insights-monitor-performance-live-website-now/\" rel=\"nofollow\">http://azure.microsoft.com/en-us/documentation/articles/app-insights-monitor-performance-live-website-now/

我主持上部署与云服务Webroles在Azure虚拟机的几个网站。

I have a few sites hosted on a VM on azure that is deployed with Cloud Service Webroles.

从有code或命令行安装状态监视器的人看到的例子吗?目标是增加全自动IIS站点天青应用洞察没有如上面的链接登录到远程桌面。

Have anyone seen examples of installing the status monitor from code or command line? Goal is to add IIS sites automaticly to Azure App Insight without logging into remote desktop as shown in the link above.

推荐答案

我们遇到了这个问题也并写了一个脚本,它应该插入<一个href=\"http://blogs.msdn.com/b/visualstudioalm/archive/2014/04/16/new-agent-for-application-insights-available.aspx\"相对=nofollow>安装VS在线应用程序洞察现有的方法。

We ran into this issue also and wrote a script, which should plug into the existing method for installing VS Online App Insights.

if(${env:InstalledStatusMonitor} -eq 1)
{
    Write-Host "Status monitor has already been installed on this machine by this script" -ForegroundColor Green
}

Write-Host "Using chocolatey to install the Web Platform Installer ..."  -ForegroundColor Green
iex ((new-object net.webclient).downloadstring('https://chocolatey.org/install.ps1'))
cinst webpi -y
Stop-Process -Name WebPlatformInstaller

Write-Host "Using Web Platform Installer to install Status Monitor ..." -ForegroundColor Green
&"$env:ProgramFiles\Microsoft\Web Platform Installer\WebpiCmd.exe" /Install /AcceptEula /Products:ApplicationInsightsStatusMonitor

Write-Host "Adding app pool account to the 'Performance Monitor Users' local group" -ForegroundColor Green
$group = "Performance Monitor Users"
$user = "Network Service"
$computer = $(Get-WmiObject Win32_Computersystem).name
$de = [ADSI]"WinNT://$computer/$group,group" 
$de.psbase.Invoke("Add",([ADSI]"WinNT://$user").path)
Write-Host "Waiting 30 seconds for Status Monitor to finish its install ..." -ForegroundColor Green
Start-Sleep -Seconds 30

Write-Host "Stop-Starting services to enable tracing..." -ForegroundColor Green
# For some reason, even though Status Monitor calls "iisreset.exe /restart"
# calling it here leaves IIS and website stopped.
&iisreset.exe /restart

Write-Host "waiting a few seconds..." -ForegroundColor Yellow
Start-Sleep -Seconds 2
Write-Host "starting..." -ForegroundColor Yellow

Start-Service -Name W3SVC
Get-WebApplication | Select ApplicationPool -Unique | %{ Start-WebAppPool $_.applicationPool }
Get-Website | Start-Website
Write-Host "started" -ForegroundColor Yellow

Write-Host "Cleaning up running applications" -ForegroundColor Green
Stop-Process -Name Microsoft.Diagnostics.Agent.StatusMonitor


Write-Host "Setting environment variable to indicate status monitor has been installed" -ForegroundColor Green
[Environment]::SetEnvironmentVariable("InstalledStatusMonitor", "1", "Machine")

Write-Host "Installation complete" -ForegroundColor Green

<一个href=\"http://www.greenfinch.ie/how-to-deploy-application-insights-status-monitor-$p$pview-on-a-cloud-service-webrole/\"相对=nofollow>我写了一篇博客文章在这里的,所以如果我们碰到的问题,我忘了更新这篇文章,你应该能看到有更新。

I wrote a blog post about it here, so if we run into issues and I forget to update this post you should be able to see updates there.

由于pksorensen的直接联系,它看起来像这就是Web平台安装程序下载从包。我做更多的一些这方面的,现在有一个完全自动化的过程工作。 我可以在这里有一个工作项目的样本资源库。。 <一href=\"https://github.com/greenfinch/sample-net-AzureApplicationInsightsStatusMonitor/commit/4a6a47dd5cfdceaf18ce2126240b2d8ec5184042\"相对=nofollow>这个承诺应该说明你需要做的,自己的Web项目获得状态监控器上的Web角色的工作是什么。

Thanks to pksorensen for the direct link, it looks like this is where the Web Platform installer downloads the package from. I've done some more with this and now have a fully automated process working. I have a sample repository available here with a working project.. This commit should describe what you need to do to your own web project to get Status Monitor working on a Web Role.

有一个职位由谢尔盖Kanzhelev ,表明它应该有可能做到这一点,以辅助角色太

There is a post by Sergey Kanzhelev, indicating that it should be possible to do this to worker roles too.

下面是所需的各个步骤。我会尽量提供对非Web角色的更新,如果我得到一个机会来看看它:

Here are the individual steps required. I will try to provide an update on non-web roles if I get a chance to look into it:

添加下列启动项到您的网络部署项目,在创建时的作用或部署到它将运行。

Add the following Startup entry into your web deployment project, it will run when the role is being created or deployed to.

<ServiceDefinition>
  <WebRole>

    ...

    <Startup>
      <Task commandLine="Role_Start\Bootstrap.bat" executionContext="elevated" taskType="simple">
        <Environment>
          <Variable name="EMULATED">
            <RoleInstanceValue xpath="/RoleEnvironment/Deployment/@emulated" />
          </Variable>
        </Environment>
      </Task>
    </Startup>
  </WebRole>
</ServiceDefinition>

2。 WebProject / Role_Start / Bootstrap.bat

这是由启动任务调用批处理文件。它被放置在Web项目。设置属性的文件总是复制到输出目录。

2. WebProject/Role_Start/Bootstrap.bat

This is the batch file called by the startup task. It has to be placed in your web project. Set the properties to always copy the file to output directory.

:: The basis for this script is described here
:: http://blogs.msdn.com/b/visualstudioalm/archive/2014/04/16/new-agent-for-application-insights-available.aspx
:: The scripts can be downloaded directly from
:: http://go.microsoft.com/fwlink/?LinkID=329971

@echo off

:: Do not attempt to install the agent on an emulated environment
if "%EMULATED%"=="true" goto :EndOfScript

:: Set appropriate execution policy on the host machine
set ExecutionPolicyLevel=RemoteSigned
for /F "usebackq" %%i in (`powershell -noprofile -command "Get-ExecutionPolicy"`) do (
    set ExecutionPolicy=%%i
    if /I "%%i"=="Unrestricted" goto :AllIsWell
    if /I "%%i"=="RemoteSigned" goto :AllIsWell
    Powershell.exe -NoProfile -Command "Set-ExecutionPolicy RemoteSigned" < NUL >> NUL 2>> NUL
)

:AllIsWell

Powershell.exe -NoProfile -Command "& '%~dp0InstallStatusMonitor.ps1'" < NUL  >> NUL 2>> NUL
echo "done" >"%ROLEROOT%\startup.task.done.sem"

:EndOfScript

exit 0

3。 WebProject / Role_Start / InstallStatusMonitor.ps1

像Bootstrap.bat文件,设置属性,此文件也复制到输出目录。这是较早公布脚本的更新版

3. WebProject/Role_Start/InstallStatusMonitor.ps1

Like the Bootstrap.bat file, set the properties to copy this file to the output directory also. This is an updated version of the script posted earlier

# The basis for this script is described here
# http://blogs.msdn.com/b/visualstudioalm/archive/2014/04/16/new-agent-for-application-insights-available.aspx
# The scripts can be downloaded directly from
# http://go.microsoft.com/fwlink/?LinkID=329971

#Constants
$downloadUrl = "https://go.microsoft.com/fwlink/?LinkID=512247&clcid=0x409"

# Variables
$rootDir = Split-Path $MyInvocation.MyCommand.Path
$downloadPath = Join-Path $rootDir "ApplicationInsightsAgent.msi"

# Functions
# Infrastructure functions
function TryV1
{
    param
    (
        [ScriptBlock] $Command = $(throw "The parameter -Command is required."),
        [ScriptBlock] $Catch   = { throw $_ },
        [ScriptBlock] $Finally = { }
    )

    & {
        $local:ErrorActionPreference = "SilentlyContinue"

        trap
        {
            trap
            {
                & {
                    trap { throw $_ }
                    & $Finally
                }

                throw $_
            }

            $_ | & { & $Catch }
        }

        & $Command
    }

    & {
        trap { throw $_ }
        & $Finally
    }
}

function Retry
{
    param (
        [ScriptBlock] $RetryCommand
    )

    for ($attempts=0; $attempts -lt 5; $attempts++)
    {        
        TryV1 {

            & $RetryCommand
            break

        } -Catch {

            if($attempts -lt 4)
            {
                Log-Message "Attempt:$attempts Exception Occured. Sleeping and Retrying..."
                Log-Message $_
                Log-Message $_.InvocationInfo.PositionMessage
                Start-Sleep -Seconds 1
            }
            else
            {
                throw $_
            }
        }
    }

}

function Log-Message
{
    param(
        [string] $message
    )

    $logString = ("{0}: {1}" -f (Get-Date), $message)
    $unifiedStartupInfoLogPath = Join-Path $rootDir "ApmAgentInstall.log"
    Add-Content $unifiedStartupInfoLogPath $logString
    Write-Host $logString -ForegroundColor Green
}

function Log-Error
{
    param(
        [string] $message
    )
    $logString =  ("{0}: {1}" -f (Get-Date), $message)
    $unifiedStartupErrorLogPath = Join-Path $rootDir "ApmAgentInstallError.log"
    Add-Content $unifiedStartupInfoLogPath $logString
    Write-Host $logString -ForegroundColor Red
}

# Functions
# Operations functions
function Get-AppInsightsInstallationStatus(){

    if(${env:InstalledStatusMonitor} -eq 1)
    {
        return $true
    }
    else
    {
        return $false
    }
}

function Download-StatusMonitor
{
    Retry {

        $wc = New-Object System.Net.WebClient
        $wc.DownloadFile($downloadUrl, $downloadPath)
    }
}

function Install-StatusMonitor(){
    $logPath = Join-Path $rootDir "StatusMonitorInstall.log"
    &$downloadPath /quiet /passive /log $logPath
    Log-Message "Waiting 30 seconds for Status Monitor to finish its install ..."
    Start-Sleep -Seconds 30
}

function Grant-LoggingPermissionToAppPool(){
    $groupName = "Performance Monitor Users"
    $user = "Network Service"
    $group = [ADSI]"WinNT://./$groupName,group"
    if(($group.PSBase.Invoke('Members') | %{$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)}) -contains $user)
    {
        Log-Message "'$user' is already a member of '$groupName', don't need to do anything"
        return
    }    
    else
    {
        Log-Message "'$user' is now a member of '$groupName'"
        $group.Add("WinNT://$user")
    }
}

function Restart-IISOnAzureWebRole(){
    # For some reason, even though Status Monitor calls "iisreset.exe /restart"
    # calling it here leaves IIS and website stopped.
    &iisreset.exe /restart

    Log-Message "waiting a few seconds..."
    Start-Sleep -Seconds 2
    Log-Message "starting..."

    Start-Service -Name W3SVC
    Get-WebApplication | Select ApplicationPool -Unique | %{ Start-WebAppPool $_.applicationPool }
    Get-Website | Start-Website
    Log-Message "started"
}

# Main body
Log-Message "Starting Status Monitor installation"

Log-Message "Downloading component..."
Download-StatusMonitor

Log-Message "Installing component..."
Install-StatusMonitor

Log-Message "Adding app pool account to the 'Performance Monitor Users' local group"
Grant-LoggingPermissionToAppPool

Log-Message "Stop-Starting services to enable tracing..."
Restart-IISOnAzureWebRole

Log-Message "Completed installation successfully"

更新2

如果您需要添加自定义属性的能力,跟踪,例如能够根据您需要进入早于文档中描述的应用洞察pipleline角色名或角色实例歧视的依赖关系。

Update 2

If you need the capability to add custom properties to track on, such as being able to discriminate dependencies based on role names or role instances you need to get into the Application Insights pipleline earlier than is described in the documentation.

比方说,你要能够在角色名称和角色实例ID过滤器,你可以创建一个自定义上下文初始化。

Let's say you want to be able to filter on Role Name and Role Instance Id, you would create a custom context initializer.

using System.Text.RegularExpressions;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace Utilities
{
    public class AppInsightsCurrentRoleIdAsTagInitializer : Microsoft.ApplicationInsights.Extensibility.IContextInitializer
    {
        public void Initialize(TelemetryContext context)
        {
            context.Properties["Greenfinch - RoleName"] = RoleEnvironment.CurrentRoleInstance.Role.Name;
            context.Properties["Greenfinch - RoleInstanceId"] = InstanceId;
        }

        private string InstanceId
        {
            get
            {
                var instanceId = Regex.Match(RoleEnvironment.CurrentRoleInstance.Id, "\\d+$", RegexOptions.Compiled).Value;
                return string.IsNullOrWhiteSpace(instanceId)
                    ? "unable to get instance id"
                    : instanceId;
            }
        }
    }
}

但不是在code在插上,你反而把它添加到ApplicationInsights.config文件:

but instead of plugging it in in code, you would instead add it to the ApplicationInsights.config file:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationInsights xmlns="http://schemas.microsoft.com/ApplicationInsights/2013/Settings" schemaVersion="2014-05-30">

  ...

  <ContextInitializers>

    ...

    <Add Type="Utilities.AppInsightsCurrentRoleIdAsTagInitializer, Utilities" />
  </ContextInitializers>

  ...

</ApplicationInsights>

这篇关于在命令行中添加Azure应用程序的洞察力状态监视器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆