Step by step: Serilog with ASP.NET Core
Step by step: Serilog with ASP.NET Core
Categories:
2 minute read
NOTE: This post is out of date. Please read: Updated Step by step: Serilog with ASP.NET Core for an update.
Last week I wrote about .NET Core and Microsoft Bot Framework and I’m still learning and playing with it. The thing is that once I implemented more features and deployed the bot to Azure it didn’t work. So I had to find a way to log and trace what was happening in order to diagnose and fix the problem.
This time I decided to give a chance to Serilog and as you should know by now, getting the correct dependencies to work with .Net Core is not always easy, so here is my Step by step: Serilog with ASP.NET Core
Add the following dependencies in your project.json file
"Serilog": "2.2.0",
"Serilog.Extensions.Logging": "1.2.0",
"Serilog.Sinks.RollingFile": "2.0.0",
"Serilog.Sinks.File": "3.0.0"
Add the following lines to the constructor of your Startup class
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.RollingFile(Path.Combine(env.ContentRootPath, "log-{Date}.txt"))
.CreateLogger();
Add the following line to the configure method of your Startup class
loggerFactory.AddSerilog();
Inject the logger to your services or controllers
public class Chat : IChat
{
// Instancia del logger
ILogger logger;
// Injectamos el logger en el constructor
public Chat(ILogger logger)
{
this.logger = logger;
}
// Método de envÃo de los mensajes
public virtual void SendMessage(string message)
{
try
{
// Envío de Mensaje
}
catch (System.Exception ex)
{
// Enviamos al log los errores.
this.logger.LogError(ex.Message);
}
}
}
Learn More
Fundamentals: Logging in .NET Core and ASP.NET Core
Hope it helps!