In my project, logging is implemented using Serilog. When I try to log a line, I would like to add some values that should not be included in the message, but should be in the log.
My _Logger doesn't have a ".ForContext" () method for this. Maybe I'm wrong registered serilog?
Handler class:
public class LogHandler
{
private readonly ILogger<LogHandler> _logger;
public LogHandler(ILogger<LogHandler> logger)
{
_logger = logger;
}
**_logger.(HAS NO METHOD)ForContext("Hello", ...);**
}
Program.cs:
namespace LoggingExample
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(loggingConfiguration => loggingConfiguration.ClearProviders())
.UseSerilog((hostingContext, loggerConfiguration) =>
loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext());
}
}
Startup:
namespace LoggingExample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ILogHandler, LogHandler>()
.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
Settings:
{
"Serilog": {
"Using": [ "Serilog.Sinks.Graylog", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Warning",
"Override": {
"LoggingExample.Handler": "Information"
}
},
"WriteTo": [
{
"Name": "Graylog",
"Args": {
"hostnameOrAddress": "127.0.0.1",
"port": "1514",
"transportType": "Tcp"
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName"
],
"Properties": {
"Application": "Centralized logging application"
}
},
"AllowedHosts": "*"
}