Reputation: 2827
PS: My problem was with me, rather than code. The code is fine. I needed to change .WriteTo.Console()
to .WriteTo.Debug()
(and get the correct nuget package).
I am trying to output information from my logs using Serilog within a .NET Core Web Api. However, no relevant information (i.e. the information I want to log) is outputted.
I have installed the following Serilog nuget packages:
I have considered setting my configuration settings in the appSettings.json, but would prefer to do it this way if possible.
Here is my Program.cs
file.
public class Program
{
public static void Main(string[] args)
{
// Create the logger
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Debug()
.WriteTo.Console()
.CreateLogger();
Log.Information("ah there you are");
Log.Debug("super");
Log.Error("super1");
Log.Warning("super2");
try
{
Log.Information("Starting web host");
// Program.Main logic
Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
CreateWebHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
Console.WriteLine(ex.Message);
}
finally
{
// Close and flush the log.
Log.CloseAndFlush();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog(); // set serilog as the loggin provider
}
I have this set up in my Startup.cs
in case that is relevant.
public class Startup
{
private readonly ILogger _logger;
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_logger = logger;
}
}
Below is the output I get when I run my application. It is nothing important (and I have searched through it multiple times to confirm I am not missing anything. Mostly, I am attaching this photo to confirm I am indeed looking in the correct area).
Any ideas?
Upvotes: 5
Views: 11940
Reputation: 1849
You need to configure your logger in the programs.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog((context, configuration) => configuration
.Enrich.FromLogContext()
.MinimumLevel.Debug()
.WriteTo.Console(),
preserveStaticLogger:true);
}
You can remove all other Serilog references (in the startup.cs) and the "Log.CloseAndFlush()" instruction (it will be closed automatically)
Then you can inject an ILogger<T>
interface wherever you want.
Btw: I'm not sure "preserveStaticLogger" is needed.
Upvotes: 14