我正在尝试制定一种方法来在某些程序中记录我的痕迹。但我很难连接到我的 Azure Application Insights 并查看我想要记录的数据。
static void Main(string[] args)
{
// Create a service collection and configure Application Insights
var services = new ServiceCollection();
services.AddLogging(loggingBuilder => loggingBuilder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>("Category", LogLevel.Information));
services.AddApplicationInsightsTelemetryWorkerService((ApplicationInsightsServiceOptions options) => options.ConnectionString = "cnxn string");
// Build ServiceProvider.
IServiceProvider serviceProvider = services.BuildServiceProvider();
// Obtain logger instance from DI.
ILogger<Program> logger = serviceProvider.GetRequiredService<ILogger<Program>>();
logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
我尝试按照 Microsoft 自己的文档了解如何登录 Application Insights: https://learn.microsoft.com/en-us/azure/azure-monitor/app/worker-service#net-corenet-framework-console-application
手动部分工作正常,我和我可以手动登录并刷新到Azure,但这不是我想要的。
最后,如果我可以简单地将
logger
作为未来方法的参数发送,那就太好了,这样我就可以轻松登录到 Azure。
最后,如果我可以简单地将
作为未来方法的参数发送,那就太好了,这样我就可以轻松登录到 Azure。logger
我引入了一个名为
ILoggerService
的接口,它具有三种日志记录方法:LogInformation
、LogWarning
和 LogError
。该接口定义了日志服务的契约。
using Microsoft.ApplicationInsights;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace WorkerSDKOnConsole
{
public interface ILoggerService
{
void LogInformation(string message);
void LogWarning(string message);
void LogError(string message);
}
public class AzureLoggerService : ILoggerService
{
private readonly TelemetryClient _telemetryClient;
public AzureLoggerService(TelemetryClient telemetryClient)
{
_telemetryClient = telemetryClient;
}
public void LogInformation(string message)
{
_telemetryClient.TrackTrace(message, Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information);
}
public void LogWarning(string message)
{
_telemetryClient.TrackTrace(message, Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Warning);
}
public void LogError(string message)
{
_telemetryClient.TrackTrace(message, Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error);
}
}
class Program
{
static async Task Main(string[] args)
{
// Create the telemetry client.
var telemetryClient = new TelemetryClient()
{
InstrumentationKey = "Ins-key"
};
// Create the logger service.
var loggerService = new AzureLoggerService(telemetryClient);
var httpClient = new HttpClient();
while (true) // This app runs indefinitely. Replace with actual application termination logic.
{
loggerService.LogInformation($"Worker running at: {DateTimeOffset.Now}");
loggerService.LogWarning("A sample warning message. By default, logs with severity Warning or higher are captured by Application Insights");
loggerService.LogInformation("Calling bing.com");
var res = await httpClient.GetAsync("https://bing.com");
loggerService.LogInformation($"Calling bing completed with status: {res.StatusCode}");
telemetryClient.TrackEvent("Bing call event completed");
await Task.Delay(1000);
}
// No need to flush telemetry client here.
}
}
}
Program
类以创建 AzureLoggerService
的实例,而不是直接使用 TelemetryClient
。TelemetryClient.TrackTrace
的直接调用替换为对 loggerService
实例相应方法的调用(例如,loggerService.LogInformation
)。Main
方法中删除了遥测客户端的显式刷新。由于我们使用的是 Application Insights SDK,因此它会自动处理刷新。这样,我可以通过在需要时注入
ILoggerService
依赖项,在整个应用程序中轻松记录到 Azure Application Insights。
更新:
[TestClass]
public class ProgramTests
{
[TestMethod]
public async Task Main_LogsInformation()
{
// Arrange
var loggerServiceMock = new Mock<ILoggerService>();
var program = new Program(loggerServiceMock.Object);
// Act
await program.Main(new string[] { });
// Assert
loggerServiceMock.Verify(x => x.LogInformation(It.IsAny<string>()), Times.AtLeastOnce);
}
}