以下の内容はhttps://noxi515.hateblo.jp/entry/2019/04/14/222017より取得しました。


ApplicationInsightsに.NETアプリのログを出力する

MicroBatchFramework でバッチアプリを開発しているときにそのままログを ApplicationInsights に送信してみたので、その防備録です。


MicroBatchFramework のアプリに ApplicationInsights を追加する

MicroBatchFramework はログに Microsoft.Extensions のものを使用しているため、ロガーからの出力をそのまま Application Insights に送信できます。 Application Insights へ送信するためのログプロバイダーは Microsoft.Extensions.Logging.ApplicationInsights パッケージを NuGet からインストールします。

f:id:noxi515:20190414213224p:plain
NuGetからインストール

NuGet からパッケージを追加したら、コード上もログプロバイダーを追加します。

static async Task Main(string[] args)
{
    await BatchHost.CreateDefaultBuilder()
        .ConfigureServices(ConfigureDelegate)
        .ConfigureLogging(ConfigureLogging)
        .RunBatchEngineAsync<BatchTask>(args);
}

private static void ConfigureLogging(HostBuilderContext hostContext, ILoggingBuilder log)
{
    log.AddApplicationInsights("Instrumentation Key");
}

Application Insights の Instrumentation Key はログプロバイダー追加時に指定する以外は IOptions<TelemetryConfiguration> に対して設定することができます。

Application Insights に対してログを出力するには、ロガーに対して普通にログを出せば良いです。次の例では BatchBase.Context.Logger からログを出していますが、コンストラクタで ILogger<any> を受け取ってそこからログを出しても良いです。違いはカテゴリー名だけなので、後にどう使用するかで使い分ければ良いと思います。

public async Task RunAsync(string name = "default value", int count = 10)
{
    var data = new Dictionary<string, object>
    {
        {"Name", name},
        {"Count", count}
    };
    Context.Logger.LogInformation("name: {name}, count: {count}", data["Name"], data["Count"]);
}

これを Application Insights 側で見るとこうなります。パラメーター名別にカスタムプロパティに含まれているのがありがたいです。

f:id:noxi515:20190414220607p:plain
Application Insightsで見たログ

Telemetry のフラッシュ

ただログプロバイダーに Application Insights を追加しただけだと、アプリが終了した時点で送信キューに残っている Telemetry は送信されません。バッチの終了をハンドルしてログを送信しましょう。

noxi515.hateblo.jp

実際の実装としては、 IOptions<TelemetryConfiguration> にある TelemetryChannel.Flush を呼び出します。

_telemetryConfiguration.Value?.TelemetryChannel.Flush();



以上の内容はhttps://noxi515.hateblo.jp/entry/2019/04/14/222017より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14