Step by step: Serilog with ASP.NET Core

by Carlos Mendible on 19 Sep 2016 » dotNetCore

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

1. 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"

2. 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();

3. Add the following line to the configure method of your Startup class


     loggerFactory.AddSerilog();

4. 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);
            }
        }
    }

Hope it helps!