There is a TraceIdentifier for one request in asp.net, how to write such an id into logs or some other way automatic. Thx
Request.HttpContext.TraceIdentifier
my purpose can collect all the log messages for one request
I haven't found solutions with Illogger.But there is a way to do it with Serilog.
Install nugetpackage
Serilog
Serilog.AspNetCore
Serilog.Sinks.Console
//install if log to console
Serilog.Sinks.File
//install if log to file
SumoLogic.Logging.Serilog
Serilog.Enrichers.GloabalLogContext
in Program.cs add
Log.Logger = new LoggerConfiguration()
.Enrich.FromGlobalLogContext() //for pushing httpcontext properties later
.WriteTo.Console(new JsonFormatter()) //write to console
.WriteTo.File(new JsonFormatter(), "mylog.json") //write to file
.WriteTo.BufferedSumoLogic(new Uri("https://collectors.us2.sumologic.com/receiver/v1/http/your_endpoint_here=="), formatter: new JsonFormatter()) //send to sumologic
.CreateLogger();
in controller method
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet("test")]
public void test()
{
GlobalLogContext.PushProperty("TraceIdentifier", Request.HttpContext.TraceIdentifier);
Log.Information("hello");
Log.Information("bye");
}
}
output
A general way to add additional property in serilog is when config in program.cs use .Enrich.WithProperty(key,value)
, but because we cannot use httpcontext in program.cs so we use pushproperty to reconfig in method.
-------------------------------------------orignal answer------------------------------------------------
Install nuget package SumoLogic.Logging.AspNetCore
[ApiController]
public class ValuesController : ControllerBase
{
ILogger logger = LoggerFactory.Create(config =>
{
config.AddConsole(); //to see in console window
config.AddSumoLogic( //send log to sumologic
new LoggerOptions
{
Uri = "https://collectors.us2.sumologic.com/receiver/v1/http/your_endpoint_here=="
}
);
}).CreateLogger<ValuesController>();
[HttpGet("test")]
public void test()
{
logger.LogInformation(Request.HttpContext.TraceIdentifier);
}
}
I just create a instance directly, you can also defube _logger
by inject.