Skip to main content

Adding File logging into .net Core 2.0 application

Will be making use of Serilog to log for our application. To get started we need the following Nuget packages.

  • Serilog.AspNetCore
  • Serilog.Settings.Configuration
  • Serilog.Sinks.Console
  • Serilog.Sinks.RollingFile
StartUp.cs


using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;

namespace MyBlog
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); // <-- add for logging

            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }


        public void ConfigureServices(IServiceCollection services)
        {

            services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(dispose: true)); //<-- added for logging
           
            services.AddMvc();
        }


        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {

            loggerFactory.AddSerilog(); // <--add for logger


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMvc();
        }
    }

}

Program.css

using Microsoft.AspNetCore.Hosting;
using Serilog;

namespace Umbai.HotRecharge
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSerilog() // <-- Add for logging
                .Build();
    }

}

Appsetting.json


"Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": "Debug",
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "logs\\log-{Date}.txt",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
        }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Properties": {
      "Application": "My Application"
    }
  }



and thus it, you can now use it in your code by passing in the logger into your code using dependency injection.

Comments

  1. Replies
    1. The tutorial was designed using .net core 2.0, what exact error are you getting then I can offer more assistance

      Delete

Post a Comment

Popular posts from this blog

Messaging through a service Bus using MassTansit with Asp.Net Core 2.2 tutorial

Today we going to look at a quick tutorial on how to use MassTransit as a messaging bus for your Asp.Net core 2.2 application. I have uploaded the sample project on GitHub , if you want to follow along Spin up new project To begin spin up a new Api project, I am using Visual Studio 2019, I also added 2 nuget packages listed below.     <PackageReference Include="MassTransit.AspNetCore" Version="5.5.5" />     <PackageReference Include="MassTransit.RabbitMQ" Version="5.5.5" /> Startup.cs  In your Startup.cs file public void ConfigureServices(IServiceCollection services)         {             //Register your message consumer             services.AddScoped<OrderConsumer>();             // Register MassTransit             services.AddMassTransit(x =>             {                 x.AddConsumer<OrderConsumer>();                 x.AddBus(provider => Bus.Factory.CreateUsingRabbitMq(cfg =>

Bringing together DotNet Core, Nginx and Supervisor on a linux server

We going to look at a simple tutorial on how to have your .net core site run on a linux server and make use of supervisor to start up and monitor the site. First we going to assume you have supervisor installed on the box, with nginx already running. Configure supervisor firstly browse to the folder /etc/supervisor/conf.d Inside this folder create a .conf file for example dotnettest.conf Open the dotnettest.conf and insert the following lines [program:dotnettest] command=/usr/bin/dotnet  /home/testapp/bin/Debug/netcoreapp2.2/publish/testapp.dll directory=/home/testapp/bin/Debug/netcoreapp2.2/publish/ autostart=true autorestart=true stderr_logfile=/var/log/dotnettest.err.log stdout_logfile=/var/log/dotnettest.out.log environment=ASPNETCORE_ENVIRONMENT=Production user=root stopsignal=INT For the explanation of the above you specify the name of your site by placing "program:" in front of it command you use to specify that you want dotnet which is l