首页 > 解决方案 > 在 .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 ,因为实际上代码非常大。此外,我不想在每次记录一些数据时都附加所需的信息。

标签: azure.net-corelog4netazure-application-insightsloggerfactory

解决方案


您可以使用遥测初始化程序向所有遥测项添加额外属性,或修改现有属性:

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();
    }

推荐阅读