我在.Net中使用Azure功能和WebJob,并使用TelemetryClient将日志发送到ApplicationInsights。
我有几乎相同的WebJob和Azure功能的日志代码。
对于azure函数,我可以在Requests,Traces和customMetrics中查看我的数据,但对于WebJob,customMetrics中只有Traces和Requests中没有数据可用。
我的EventHub WebJob记录代码
public Task ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
foreach (var eventData in messages)
{
Log log = LogManager.GetLogger();
RequestTelemetry requestTelemetry = new RequestTelemetry { Name = "EventhubWebJob" };
requestTelemetry.Properties.Add("MessageId", Guid.NewGuid().ToString());
IOperationHolder<RequestTelemetry> operation = log.TelemetryClient.StartOperation(requestTelemetry);
operation.Telemetry.Success = true;
log.Trace($"Message processing start...");
try
{
log.Trace("Message received.");
Console.WriteLine($"Message received.");
}
catch (Exception ex)
{
operation.Telemetry.Success = false;
log.Trace(ex.Message);
throw;
}
finally
{
log.Trace($"Message processing completed.");
log.TelemetryClient.StopOperation(operation);
}
}
return context.CheckpointAsync();
}
我可以看到下面的功能与WebJob所需的功能相同。
如果你想将ApplicationInsights
与WebJob一起使用,你需要使用Microsoft.Azure.WebJobs.Logging.ApplicationInsights
nuget包,即使它目前是beta版。
你总共需要三个包:
配置JobHostConfiguration
string instrumentationKey = Environment.GetEnvironmentVariable("APPINSIGHTS_INSTRUMENTATIONKEY");
if (!string.IsNullOrEmpty(instrumentationKey))
{
// build up a LoggerFactory with ApplicationInsights and a Console Logger
config.LoggerFactory = new LoggerFactory().AddApplicationInsights(instrumentationKey, null).AddConsole();
config.Tracing.ConsoleLevel = TraceLevel.Off;
}
注意:不要忘记在应用程序设置中添加APPINSIGHTS_INSTRUMENTATIONKEY
。
关于ILogger
过滤,您可以参考Application Insights Integration
wiki,CategoryLevels
允许您指定特定类别的日志级别,以便您可以微调日志记录输出。
你可以添加LogError
代码:
public static void ProcessQueueMessage([QueueTrigger("queue")] string message, ILogger logger)
{
//you can directly use this line of code.
logger.LogError(new Exception(),"it is a test error...");
}
更新:
更新: