【问题标题】:Customize log messages using Loggerfactory in .net core application在 .net 核心应用程序中使用 Loggerfactory 自定义日志消息
【发布时间】:2018-12-20 08:54:39
【问题描述】:

我有 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-core log4net azure-application-insights loggerfactory


    【解决方案1】:

    您可以使用telemetry initializer 为所有遥测项添加额外属性,或修改现有属性:

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

    【讨论】:

      猜你喜欢
      • 2017-11-10
      • 1970-01-01
      • 2022-07-04
      • 1970-01-01
      • 2014-08-13
      • 2021-05-13
      • 1970-01-01
      • 2021-03-16
      • 2015-04-02
      相关资源
      最近更新 更多