Logging in Asp .Net Core 2.0

core5

Logging is very important part of any application as almost all application requires proper logging.

.Net Core 2.0 has some simplified way of implementing logging.

Let us see what are the changes required to enable logging in .Net Core 2.0 application.

First of all, we need to make changes in appsettings.json file as below:

{
  "Logging": {
    "IncludeScopes": false,
      "LogLevel": {
        "Default": "Debug",
        "System": "Information",
        "Microsoft": "Information"
    }
  }
}

Here we have logger provider along with the levels so it allows us to configure logging levels per logging provider.

Previously, the entry in appsettings.json would only be applicable to the console logger but now the entry in the appsettings.json  has logger provider names in it like Debug, EventLog, TraceSource etc.

Do not forget to make these changes as it is required and it may throw the exception if you have missed this. I saw some StackOverflow questions mainly on this where people forgot to add related details in appsettings.json file.

Once it is done, in Main class, we can configure the logging details as shown below:

public static void Main()
{
  var host = new WebHostBuilder()
               .UseKestrel()
               .UseContentRoot(Directory.GetCurrentDirectory())
               .ConfigureAppConfiguration((hostingContext, config) =>
     {
       var env = hostingContext.HostingEnvironment;
       config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
       .AddJsonFile("hosting.json", optional: false)
       .AddEnvironmentVariables();
       })
       .ConfigureLogging((webhostContext, builder) => {
       builder.AddConfiguration(webhostContext.Configuration.GetSection("Logging"))
       .AddConsole()
       .AddDebug();
})
.UseIISIntegration() .UseStartup() .UseApplicationInsights() .Build(); host.Run(); }

So we can now move the logging configuration part into the WebHostBuilder.

In above code, concentrate on line:

logging.AddConfiguration(hostingContext.Configuration.GetSection(“Logging”));

This method sets up logging to look for configuration in a Logging section, in this case, we can write in appsettings.Development.json file as below:

{
 "Logging": {
   "IncludeScopes": false,
   "Debug": {
   "LogLevel": {
   "Default": "Information"
 }
 },
 "LogLevel": {
   "Default": "Debug"
 }
 }
}

After this, you can directly inject logger service into the controller as shown below:

private readonly IRepository _repository;
private readonly ILogger _logger;

public MyController(IRepository repository,
ILogger logger)
{
    _repository = repository;
    _logger = logger;
}

Now in your controller class, wherever you want to log for Information then it should be:

_logger.LogInformation(“Information”);

And if we want to log for warning then:

_logger.LogWarning(“WARNING!”);

Same goes for other levels as well.

Exception logging:

The logger method allows us to pass an exception as below:

catch (Exception ex) {
     _logger.LogWarning(LoggingEvents.GetItemNotFound, ex, "Error");
}

Please note that different providers handle the exception information in different ways.

Some useful StackOverflow QAs:

https://stackoverflow.com/questions/45214468/asp-net-core-2-0-appsettings-development-json-not-working-with-logging-configura

https://stackoverflow.com/questions/45781873/is-net-core-2-0-logging-broken

 

SPA templates(Angular, React etc) with ASP .NET Core 2.0

In my last post, I have explained about the setup required for .Net Core 2.0 which you can find here.

Along with Core 2.0, there are some newly added default templates has been added by Microsoft team.

The major attraction is the SPA templates that are shipped with Core 2.0.

SPA templates like Angular, React.js, React.js and Redux etc can be seen in default template page:

core3

These three templates create actually the same sample application but the difference is in JavaScript libraries. Notice that these new templates are available only when ASP.NET Core 2 is selected from framework dropdown on top of the dialog.

The best part is, JavaScript Services functionality is used by these SPA templates to embed Node.js within .Net Core on the server. Thus it compiles the Javascript applications server-side as part of .Net build.

The advantage of having SPA templates in the default template section is, most of the required scripts, dlls and other required components are already added in the application so you can start building your application without worrying about the dependencies.

Setup for Asp .Net Core 2.0

core2

Microsoft has announced Core 2.0 and it has some awesome features which I will explain in future blog posts.

For now, let us see how to converts your Core 1.0 application into Core 2.0

First of all, we will change the .Net core version in global.json file as shown below:

{
   "sdk": {
   "version": "2.0.0-preview3-006912"
  }
}

After that we need to change the target library to Core 2.0 as shown below:

1-TargetFramework

Also, change and update below line in .csproj file:

<TargetFramework>netcoreapp2.0</TargetFramework>

Once it is done, we need to add below package in the .csproj file:

<ItemGroup>

<PackageReference Include=“Microsoft.AspNetCore.All” Version=“2.0.0” />

</ItemGroup>

This new metapackage contains references to all of the AspNetCore packages and maintains a complete line-up of compatible packages.  You can still include explicit references to specific Microsoft.AspNetCore.* package versions if you need one that is outside of the lineup

Now we need to change PackageTargetFallback in same .csproj file as below:

<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>

Here we added AssetTargetFallback instead of earlier PackageTargetFallback

Now let us jump to the Main method in Program.cs class. In Core 1.0 we used to add different extended methods like .UseKestrel(), .UseIISIntegration() etc.

For Core 2.0 it is more simplified as shown below:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

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

   public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
     .UseStartup()
      .Build();
  }
}

Now your application is converted into Core 2.0 from Core 1.0

Amplitude 2017: A MasterCard Hackathon

20664840_883428851808374_5819156468309340427_n

MasterCard is going to conduct one of the biggest hackathons of India on November. Name of the hackathon is Amplitude 2017.

The theme of this Hackathon is #CashLessBanoIndia. Name of the theme is self-explanatory, the main focus of this hackathon is to come up with the ideas which will encourage people to use digital payments instead of Cash.

There are mainly 4 themes for this hackathon which includes creating meta data driven rules platform, how to accelerate the adoption of digital payments in India, To develop alternate payment solution for merchants and increase the security of P2P and P2M transactions.

MasterCard has some awesome products which can be used for this hackathon. By the way, developers can use any API or products they want for the hackathon.

Below is the process required for Amplitude 2017:

766a17e

Some useful links:

For Registration: https://www.hackerearth.com/sprints/amplitude-2017/

To know the rules: https://www.hackerearth.com/sprints/amplitude-2017/rules/#rules

To know about the themes: https://www.hackerearth.com/sprints/amplitude-2017/custom-tab/themes/#Themes

So if you are a geek and want to do something for the nation then just register yourself and be a part of the biggest hackathon of MasterCard.