当前位置: 首页 > 知识库问答 >
问题:

从命令行添加Azure Application Insights状态监视器

卢锋
2023-03-14

http://azure.microsoft.com/en-us/documentation/articles/app-insights-monitor-performance-live-website-now/

我有几个站点托管在azure上的VM上,该VM与云服务Webroles一起部署。

有人见过从代码或命令行安装状态监视器的例子吗?目标是自动将IIS站点添加到Azure App Insight中,而无需登录到远程桌面,如上面的链接所示。

共有1个答案

夏祯
2023-03-14

我们也遇到了这个问题,并编写了一个脚本,该脚本应该插入到现有的安装VS在线应用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

我在这里写了一篇关于它的博客文章,所以如果我们遇到了问题,而我忘了更新这篇文章,你应该可以在那里看到更新。

多亏了pksorensen提供的直接链接,Web平台安装程序从这里下载包。我对此做了更多的工作,现在有了一个完全自动化的过程。我有一个示例存储库可用在这里与一个工作项目…这个提交应该描述您需要对您自己的web项目做什么,以使状态监视器在web角色上工作。

Sergey Kanzhelev的一篇文章表明,对工人角色也应该可以这样做。

下面是所需的各个步骤。我会尝试提供一个关于非Web角色的更新,如果我有机会研究它:

将以下启动条目添加到web部署项目中,它将在创建或部署角色时运行。

<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>

这是启动任务调用的批处理文件。它必须放在您的web项目中。将属性设置为始终将文件复制到输出目录。

:: 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

与bootstrap.bat文件一样,设置属性以将该文件也复制到输出目录。这是先前发布的脚本的更新版本

# 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"

如果您需要添加要跟踪的自定义属性的功能,例如能够根据角色名称或角色实例区分依赖关系,那么您需要在文档中描述的之前进入pipleline的应用程序洞察。

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;
            }
        }
    }
}

但不是将其插入代码,而是将其添加到ApplicationInsights.config文件:

<?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>
 类似资料:
  • ps 命令可以一次性给出当前系统中进程状态,但使用此方式得到的信息缺乏时效性,并且,如果管理员需要实时监控进程运行情况,就必须不停地执行 ps 命令,这显然是缺乏效率的。 为此,Linux 提供了  top 命令。top 命令可以动态地持续监听进程地运行状态,与此同时,该命令还提供了一个交互界面,用户可以根据需要,人性化地定制自己的输出,进而更清楚地了进程的运行状态。 top 命令的基本格式如下:

  • 我正在使用命令运行ASP.NET核心项目。但是,默认情况下,它将作为环境。 我尝试了这两个选项,使用: 但它仍然把生产作为一种环境。 注意:在visual studio中,环境变量在项目属性中默认设置为“开发”,从visual studio运行时选择该变量。 问题是:如何从命令行运行dotnet core project开发中的任何一个?:

  • 我不得不格式化我的驱动器,但我的一个项目不再工作了。所有其他相同类型的项目都运行良好。这是Laravel Vue JS。问题是我无法运行npm run watch/dev或prodution。他们都给出了错误。Laravel 5.7 npm ver 6.4.1 node ver 10.15.0 windows 10 我安装/卸载了不同的节点版本,没有骰子。我已经多次删除/安装节点模块,什么都没有。

  • 运行 php start.php status 可以查看到WorkerMan的运行状态,类似如下: ----------------------------------------------GLOBAL STATUS---------------------------------------------------- Workerman version:3.5.13 PHP

  • 问题内容: 如何将轮询线程传递给另一个线程进行处理。程序执行在具有主方法和线程池的控制器类中: 主类控制器 具有轮询类的线程的方法 具有proc类的线程的方法 轮询类和控制器类 我的任务和问题是: 1.控制器应同时处理轮询器和处理器线程,并且应仅调用轮询器和处理器线程 2.现在我的问题是如何使轮询线程等待3秒并并行通知处理器。 我得到如下错误: 这里如何实现异步处理? 问题答案: 你需要阅读的东西

  • 问题内容: 好的,我知道这个问题以前已经被问过很多次了,但是我已经搜索了一下,查看了示例,并查看了过去一个月中关于SO的问题,我真的无法解决这个问题。我认为问题是我希望能够从Eclipse和命令行运行该程序。我也在使用OSX,我认为我正在阅读的许多示例都是针对Windows / Linux的。 如果我有一个要在命令行中运行的,在Eclipse中编译的简单程序,请执行以下操作: 我有另一个程序在Ec