Coder Social home page Coder Social logo

ksdvishnukumar / logging-to-application-insight-in-asp.net-core Goto Github PK

View Code? Open in Web Editor NEW

This project forked from simonkaspersen/logging-to-application-insight-in-asp.net-core

0.0 0.0 0.0 716 KB

My experience in making a generic ILogFactory and logging to Azure Application Insight.

C# 100.00%

logging-to-application-insight-in-asp.net-core's Introduction

log(ging)

Logging in ASP.NET Core using ILoggerFactory-pattern to Azure Application Insight

Disclaimer: Images and steps used in this example may change over time, but may be a good reference.

Goal

Short answer: Make logging great again

Slightly longer answer: Make the application send performance-data to Application Insight. Also make all logging from the frameworks, and logging done by me, automatically be sent to Azure for further analysis.

Packages used

  • NLog - Base package for NLog
  • NLog.Web:AspNetCore - Adds helpers and layout renderes for the ASP.NET core platform
  • Lightinject - IOC-container
  • Lightinject.Microsoft.AspNetCore.Hosting - Enables Lightinject to be used in ASP.NET core applications
  • Microsoft.ApplicationInsight.AspNetCore - Official package for working with Azure Application Insight
  • Microsoft.ApplicationInsight.NLogTarget - Allowing you to send NLog messages to Application Insight

Steps

01 - Azure

  1. First we have to make ourself a Application Insight resource in Azure.

drawing

drawing

  1. Fill in information about your application, and give it a descriptive name

drawing

  1. Now we are almost done. Create it, and take note of the Instrumentation Key. We will use it shortly

drawing

02 - Code

This is based on the example project in this repo. It is a simple project created using the dotnet cli and this command: dotnet new webapi.

After the template is bootstrapped we need some base-files and interfaces. Big shoutout to @andmos for providing me with the base logfiles for this project.

File What it does
ILog.cs Is the base log-interface used when logging.
ILogFactory.cs The abstraction of the log-factory. This gets the implemented logger from the IOC-container
Log.cs Gets bootstrapped to log-actions for common Log Levels.
NLogFactory.cs Implements a factory that produces logging based on NLog.
ILogFactoryInitializer An abstraction for the builder-method that adds the logger to the ASP.Net Core-app.
NLogFactoryInitializer Implements the .UseNLog() used in Program.cs to setup NLog for DI.

Noteable changes to the code:

Program.cs - gets logger factory initializer (wow. good name. thanks) from container and passes the WebHostBuilder to the implementet builder-method.

public static void Main(string[] args)
{
    var container = new ServiceContainer();
    var loggerFactoryInitializer = container.GetInstance<ILogFactoryInitializer>();
    var webhostBuilder = CreateWebHostBuilder(args);
    loggerFactoryInitializer.UseLogger(webhostBuilder);
    
    webhostBuilder.Build().Run();
}

ValuesController.cs - Added examples of logging. With Log Level Information and Error.

// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
    var values = new []{"value1", "value2"};
    _logger.Info($"Request made, returning:{JsonConvert.SerializeObject(values)}");
    return values;
}
// GET api/values
[HttpGet("ThrowPlease")]
public IActionResult ThrowMePlox()
{
    try
    {
        throw new ArithmeticException("Dividing by 0?? Good luck");
    }
    catch (Exception e)
    {
        _logger.Error("This was bad. not good", e);
        return BadRequest();
    }
}

appsettings.json - contains the Application Insight Key for this project. This can also easily be set as an Enviromental Variable. The Application Insight framework will automatically search for this path in appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ApplicationInsights": {
    "InstrumentationKey": "<KEY>"
  },
  "AllowedHosts": "*"
}

03 - Admire the result

result1

result2

Log-entries can be searched and filtered in the search-tab in Application Insight. Other performance-data can be found i Metrics.

Test the example app

# clone the project
git clone https://github.com/simonkaspersen/Logging-to-Application-Insight-in-ASP.NET-Core.git

# enter the project directory
cd Logging-to-Application-Insight-in-ASP.NET-Core

# Add your key to appsettings.json

# install dependencies
dotnet restore

# build solution
dotnet build

# Run
dotnet run

This will open the API at http://localhost:5000.

  • Go to http://localhost:5000/api/values/ to test Information-logging
  • Go to http://localhost:5000/api/values/throwplease to test Error-logging

Links to resources

TODO

  • Deside if Pepsi Max or Coca Cola No Sugar is best
  • Implement NLog
  • Implement Log4Net
  • Implement Serilog

Thanks to

  • @andmos

logging-to-application-insight-in-asp.net-core's People

Contributors

simonkaspersen avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.