I have two console applications, one created in .Net framework 4.6. And other one in .net core 2.0. For logging, in .Net framework I'm using log4Net
, in .net core I'm using Logger. This logger directly writes into Application Insights directly in Azure.
Now my question is, how to customize the logging messages using Logger. In log4Net
, I have used aiappender
and defined a conversion pattern based on my requirement. For example:
<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>
I have written this in the log4net.config
and assigned values to Extra
variable as below.
log4net.GlobalContext.Properties["Extra"] = "SomeValue";
I want to do the similar customization for Logger in .Net core. This the sample code I have:
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();
}
}
In this code, if I want extra information similar to Log4Net pattern, how do I do it?
PS: I cannot change from logger to log4Net, as in reality the code is pretty big. Also I do not want to append the required information every time I'm logging some data.
You can use a telemetry initializer to add extra properties to all telemetry items, or to modify existing properties:
Add it to your services:
and make sure the Ilogger output is directed to App Insights: