azure - 在 .net 核心应用程序中使用 Loggerfactory 自定义日志消息
问题描述
我有 2 个控制台应用程序,一个是在 .Net 框架 4.6 中创建的。.net core 2.0 中的另一个。
对于日志记录,在我正在使用的 .Net 框架中log4Net
,在 .net 核心中我正在使用 Logger。此记录器直接在 Azure 中直接写入 Application Insights。
现在我的问题是,如何使用 Logger 自定义日志消息。
在中,我根据我的要求log4Net
使用并定义了一种转换模式。aiappender
例如,
<appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
<layout type="log4net.Layout.PatternLayout">
<parameterName value="@Extra"/>
<conversionPattern value="%date{dd/MM/yy HH:mm:ss} [%thread] %level :: Extra = %property{Extra} %message%newline" />
</layout>
</appender>
我已将其写在变量中,log4net.config
并为Extra
变量赋值,如下所示。
log4net.GlobalContext.Properties["Extra"] = "SomeValue";
我想在 .Net 核心中对 Logger 进行类似的自定义。这是我的示例代码。
public class Startup
{
public Startup()
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
var logger = loggerFactory.CreateLogger<ConsoleLogger>();
logger.LogInformation("Executing Configure()");
}
}
public class HomeController : Controller
{
ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("Executing Home/Index");
return View();
}
}
在这段代码中,如果我想要类似于 Log4Net 模式的额外信息,我该怎么做?任何想法都受到高度赞赏。
PS:我无法从 logger 更改为 log4Net ,因为实际上代码非常大。此外,我不想在每次记录一些数据时都附加所需的信息。
解决方案
您可以使用遥测初始化程序向所有遥测项添加额外属性,或修改现有属性:
public class CustomInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
// modify trace message
if (telemetry is TraceTelemetry trace)
trace.Message = $"Modified Message: {trace.Message}";
if (!(telemetry is ISupportProperties supportedTelemetry))
return;
// add custom property
supportedTelemetry.Properties["MyProp"] = "MyValue";
}
}
将其添加到您的服务中:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ITelemetryInitializer, CustomInitializer>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
并确保将 Ilogger 输出定向到 App Insights:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace);
app.UseMvc();
}
推荐阅读
- scala - 单元测试写入scala中的套接字
- c - 为什么我的阶乘函数总是返回 1?
- graphics - 我可以在 jupyter 中使用 python 生成图像吗
- c - 传递 'functions' 的参数 1 从一个整数中生成一个没有强制转换的指针
- javascript - 使用查询选择器编辑 html 内容
- python - Apache Spark 和 groupBy 与 Python 的相关性
- mongodb - 在存储的 Javascript 或视图中应用更新/插入
- spring - Spring MVC 控制器打开错误的 .jsp 文件
- flutter - 嵌套导航器 pushNamedAndRemoveUntil 谓词路由为空
- python - 计算连续的非二进制和非单个字符串