前回のブログ投稿では、ジョブの実行に Hangfire を使用している私たちに Application Insights テレメトリを関連付ける方法を紹介しました。
しかし、Optimizely のスケジュールされたジョブ フレームワークに基づいてスケジュールされたジョブを作成したとしても、ジョブの実行中に生成されたすべてのテレメトリを関連付けることができます。
簡単なクラスを作成しましたが、 JobTelemetryScope
これにより、ジョブの実行中に操作テレメトリが簡単にラップされます。 次のようになります。
using System;
using EPiServer.ServiceLocation;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;namespace SampleSite.ScheduledJobs;
public sealed class JobTelemetryScope : IDisposable
{
private readonly Injected_telemetryClientInjected;
private readonly IOperationHolder_operationHolder; public bool Success { get; set; }
public JobTelemetryScope(string jobName)
{
var telemetryClient = _telemetryClientInjected.Service;
if (!telemetryClient.IsEnabled())
{
return;
}_operationHolder = telemetryClient.StartOperation
($"JOB {jobName}");
}public void Dispose()
{
if (_operationHolder == null)
{
return;
}_operationHolder.Telemetry.Success = Success;
_operationHolder.Dispose();
}
}
これは、次のように、カスタムのスケジュールされたジョブで使用できます。
using System; using EPiServer.PlugIn; using EPiServer.Scheduler; namespace SampleSite.ScheduledJobs; [ScheduledPlugIn( DisplayName = "Test job", GUID = "F62C2AC3-A775-40E1-8F7D-62056E6E7C5E")] public class TestJob : ScheduledJobBase { public TestJob() { IsStoppable = true; } public override string Execute() { // Use in a try-catch-finally block. var telemetryScope = new JobTelemetryScope("TestJob"); try { // TODO: Add your own code here. Remember to set Success to true. telemetryScope.Success = true; } catch (Exception ex) { // Success is false by default. No need to set it explicitly. return "Not OK"; } finally { // End the telemetry correlation scope. telemetryScope.Dispose(); } // Or a using statement. using var telemetryScope2 = new JobTelemetryScope("TestJob"); try { // TODO: Add your own code here. Remember to set Success to true. telemetryScope2.Success = true; } catch (Exception ex) { return "Not OK"; } return "OK"; } }
これは、スコープ ブロックを追加できる独自のスケジュールされたジョブに対してのみ機能することに注意してください。 組み込みの Optimizely スケジュール ジョブには (まだ) 適用できません。