我是最小 api net7 的新手。我想在出现任何异常时记录应用程序见解,并从另一个公共库中的 app.settings.json 读取配置。在这里,我使用端点的概念来隔离最小的 api net7。
这是例子:
public class RegisterEndpoint : IEndpoint
{
public void RegisterEndpoints(WebApplication app)
{
var apiRoute = app.MapGroup("api/register");
apiRoute.MapGet("user", User user, IRegisterService _regService) =>
{
//check user exists or not
if(!isUserExists)
{
// register the user in this methos if any exception
//raise log into application insights and if any configuration is required need to send
// how to do that ?
// need to send as a parameter app.logger and builder.configuration to every method
}
});
}
}
注册服务位于另一个公共类库中,想要记录应用程序见解并从
app.settings.json
读取配置。最好的方法是什么?
我们可以使用依赖注入从公共类库记录 Application Insights。
安装所需的 NuGet 包
Microsoft.ApplicationInsights.AspNetCore
或从 Application Insights Telemetry
添加 Connected Services
。
读取公共类库中的配置
在新创建的公共库中,从
appsettings.json
文件中获取Instrumentation Key。
我的
CommonCL.cs
文件:
using Microsoft.Extensions.Configuration;
public class CommonCL
{
private readonly IConfiguration myconfig;
private readonly ILogger<CommonCL> mylog;
public CommonCL(IConfiguration configuration, ILogger<CommonCL> logger)
{
myconfig = configuration;
mylog = logger;
}
public void LogTraces(string mytraces)
{
mylog.LogInformation(mytraces);
}
public void LogExceptions(Exception ex)
{
mylog.LogError(ex,"Exception occurred.");
}
public string? GetInstrumentation(string Instrumentation)
{
return myconfig[Instrumentation];
}
}
在
Program.cs
中,注册类库。
builder.Services.AddSingleton<CommonCL>();
请参阅此 SO Thread,其中解释了类库的配置、MinimalAPI 和 appsettings 配置以获取更多信息。