Get a DemoStart Free TrialSign In

Resources, How To Guides

8 min read

If you use the programming language C# there’s a chance that you’re already familiar with .NET (pronounced ‘dot net’), an open-source application platform supported by Microsoft. C# is the programming language for .NET but the platform can run programs written in multiple languages. Microsoft’s ambition with .NET is to offer developers one platform to solve any problem.

This article is another entry into Logit.io’s series of how-to guides which detail how to gain from the extensive capabilities of the Logit.io platform for a variety of sources whilst offering an in-depth overview of the specific source. For this article, we discuss .NET, including the benefits of conducting .NET logging, the .NET ecosystem, and how to integrate and visualize .NET logs in Logit.io.

Contents

What is .NET?

.NET is an open-source development platform from Microsoft, which can be used to create a vast number of applications that run on desktops, mobile, cloud services, and websites. It provides an extensive class library and a well-integrated, coherent programming model that the developer uses to develop any form of software on various platforms and devices.

.NET supports multiple operating systems, including Windows, macOS, and Linux, allowing developers to create cross-platform applications. The .NET ecosystem includes .NET Core, a cross-platform, high-performance framework for building modern applications, .NET Framework, the original implementation of .NET, mainly utilized for building Windows-based applications, and .NET 5/6+, which is the unification of .NET Core and .NET Framework into a single platform that can be used to build applications across different platforms.

Why Conduct .NET Logging?

Logging in .NET is crucial due to the specific characteristics and demands of .NET applications, which often operate in diverse environments and manage critical business processes. Firstly, .NET offers significant support for structured logging, especially out-of-the-box with frameworks like Serilog or Microsoft.Extensions.Logging. With structured logging in .NET, developers can log data that will be more queryable and analyzable. This makes capturing detailed and meaningful log information key to diagnosing issues, understanding application behavior, and monitoring performance.

In addition to this, .NET logging works well with other members of the .NET ecosystem, including ASP.NET for web applications, Entity Framework for database access, and Azure for cloud services. Log data is captured consistently across various layers of the application, providing a full overview of how the system is working. For instance, in. NET, the logging frameworks provide granular logs of HTTP requests, database queries, and background tasks, which are valuable in monitoring and troubleshooting.

Furthermore, such applications, especially those that are resource-intensive or receive high traffic, must be capable of high performance. In .NET applications, logging will go a long way in tracking metrics such as the time it takes for methods to execute, memory usage, and CPU load. These logs serve to give insight into possible bottlenecks or inefficiencies within the .NET runtime that developers might need to work on to optimize their code for better performance.

Moreover, Application monitoring is crucial in modern DevOps. Most of the time, .NET logging is integrated well with monitoring utilities such as Azure Monitor, Elastic Stack, or Application Insights. It provides an in-built feature for real-time monitoring, alerting, and analysis of application logs. These are key elements in maintaining high availability, detection of issues before users are impacted, and smooth operating .NET applications in production.

Lastly, .NET applications often handle sensitive data and operate in regulated environments where security and compliance are of utmost importance. Logging again helps in the context of security by providing audit trails about user activities, system access, or changes made to applications. This becomes important for identification against unauthorized access, data integrity, and industry regulations such as GDPR or HIPAA. Also, security for your apps can further be enhanced by .NET logging frameworks through secure log storage and transmission.

The .NET Ecosystem: Explained

The .NET ecosystem is a comprehensive and versatile development platform created by Microsoft, designed to support the creation of a wide range of applications across various platforms. Below is an overview of the key frameworks offered by .NET.

  • .NET Core / .NET 5/6/7+: This represents the standard for cross-platform, open-source, modern .NET development. In it, developers can create applications running on Windows, macOS, and Linux. The migration from .NET Core to .NET 5 and subsequent versions unified the .NET ecosystem, moving features from both .NET Framework and .NET Core into one platform.
  • .NET Framework: The original implementation of .NET, which is used for building applications running on Windows only. For now, it's mostly relevant to legacy apps and is being overtaken by .NET 5/6/7+.
  • ASP.NET Core: This is a modern, powerful, scalable, high-performance framework used for building web applications. It has taken a significant place in the .NET ecosystem that supports the development of cloud-native apps while having integrations with front-end technologies.
  • Blazor: As a part of ASP.NET Core, Blazor allows developers to create interactive web UIs using C# instead of JavaScript. It supports applications on both the server side and client side using WebAssembly, offering modern web development.
  • Xamarin/.NET MAUI: This provides developers with the ability to build a cross-platform mobile application in Xamarin, reusing code bases for iOS, Android, and even Windows. .NET MAUI is the evolution of Xamarin and targets the development of native front-ends for mobile and desktop applications from one single code base.

.NET Programming Languages

The .NET platform supports several programming languages, each designed to serve different purposes and preferences of developers. One of the strongest features of the .NET platform is its Common Language Runtime (CLR), a virtual environment whereby code written in different .NET languages compiles to a shared common intermediate language (CIL) and runs on the same runtime. This means, that while developing a project, different .NET languages can be used, and various parts of an application can be written within the best-suited language for each task and still function seamlessly together. The primary languages used in .NET development are detailed below.

  • C#: Within the .NET ecosystem, C# is the most widely used programming language. It is a modern object-oriented language designed by Microsoft explicitly to fulfill all the demands of .NET. C# is highly versatile and can be used in a wide range of applications, including but not limited to web, desktop, mobile, cloud, and game development.
  • F#: F# is a functional-first language that also supports object-oriented and imperative programming paradigms. It is succinct, expressive, and powerful and is the best fit for extensive algorithms, data processing, and financial modeling.
  • Visual Basic .NET (VB.NET): Visual Basic .NET is the successor of the classical implementation of the Visual Basic language. It is uncomplicated and easy to learn. Hence, it finds its application in business applications, among other areas where speed in development and ease of comprehension are required.
  • C++/CLI: This is a variant of C++ that has been implemented for .NET. It lets developers using C++ create managed code that runs on the .NET runtime. Typically, this is used in either interoperability with unmanaged code or for applications where performance is critical.
  • IronPython and IronRuby: These are implementations of the languages Python and Ruby on .NET. They enable a Python or Ruby developer to write code that sits on top of the .NET framework. However, today, they are used less in .NET development.
  • PowerShell: A scripting language built on .NET, primarily used for task automation and configuration management in Windows environments.

.NET Integration with Logit.io

Logit.io’s powerful log management solution offers users centralized log collection, storage, and analysis to attain deep insights into their system's performance, security, and operational health. Its intuitive interface and comprehensive search capabilities, allow users to quickly pinpoint issues, troubleshoot problems, and make informed decisions to keep their systems running smoothly. If you’re interested in finding out more about log management from Logit.io and how it can enhance your organization's operations, don’t hesitate to contact us or begin exploring the platform for yourself with a 14-day free trial.

To unlock all the benefits of Logit.io, it’s crucial that users can quickly and easily integrate their data into the platform. Therefore, we’ve produced detailed and easy-to-follow integration guides for a vast array of sources in our documentation. For .NET, users can follow the .NET Serilog Configuration guide to use Serilog to send .NET logs to your Logit.io Stack or follow the instructions listed below to begin viewing your .NET logs in Logit.io.

1. Install

If using Visual Studio, create a new application using the ASP.NET Core Web App (Model-View-Controller) template.

If using a terminal application e.g. Powershell run the following command (where 'SerilogTestApp' is the name of the application you want to create):

dotnet new mvc -n SerilogTestApp

You will need to use NuGet or the command line to install three Serilog packages: Serilog.AspNetCore and Serilog.Sinks.Network to send logs using TCP/TLS or UDP.

Serilog.Settings.Configuration is needed to set up Serilog using settings from appsettings.json (instead of hardcoded settings).

In Powershell:

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Sinks.Network

If you are using Visual Studio, navigate to Tools -> NuGet Package Manager -> Manage NuGet packages for solutions, browse for the 3 packages mentioned above, and install them in your new application.

2. Configuring Serilog

Add Serilog settings to your appsettings.json file:

"Serilog": {
  "Using": [ "Serilog.Sinks.Network" ],
  "MinimumLevel": "Debug",
  "WriteTo": [
    {
      "Name": "TCPSink",
      "Args": { "uri": "tls://<your-logstash-host>:<your-ssl-port>" }
    }
  ],
  "Enrich": [ "FromLogContext" ]
}

3. Using Serilog

Inside Program.cs, add Serilog to the WebApplication build process. Below is the updated Program.cs code in full:

using Serilog;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((hostContext, _, configuration) =>
{
    configuration.ReadFrom.Configuration(hostContext.Configuration);
});

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

You can now log from anywhere in your application. For example, the following code will send a warning log to your stack when the application hits the Index action of the Home controller:

using Microsoft.AspNetCore.Mvc;
using SerilogTestApp.Models;
using System.Diagnostics;

namespace SerilogTestApp.Controllers
{
    public class HomeController(ILogger<HomeController> logger) : Controller
    {
        public IActionResult Index()
        {
            logger.LogWarning("This is something you need to be warned about!");
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

After running the application, you can now view your .NET logs in Logit.io.

Visualizing .NET Logs in Logit.io

Logit.io provides extensive visualization capabilities via its numerous open-source tools as Hosted solutions, including Hosted Kibana, Hosted OpenSearch Dashboards, and Hosted Grafana. This offers you enhanced flexibility for in-depth analysis and monitoring of your .NET logs.

Once you've configured Serilog to send .NET logs to Logit.io, you can access and view these logs, along with their details, directly from the initial dashboard. To begin with ‘visualizers’ for .NET logs, it's recommended to use OpenSearch Dashboards, which you can easily launch from the 'Logs Management' page.

  1. Launch Logs: From the initial dashboard, select ‘Launch Logs’ at the top right of your screen or ‘Launch’ next to OpenSearch Dashboards.

Visualize .NET Data 1

  1. OpenSearch Dashboards: After selecting ‘Launch Logs’ or ‘Launch’ you will arrive at the OpenSearch Dashboards welcome page. As you have already configured Serilog to ship .NET logs to Logit.io, from here, select ‘Visualize & Analyze’.

Visualize .NET Data 2

  1. Visualization Options: From this page, you can choose either ‘Discover’ which allows you to search through your data to find insights, or ‘Dashboard’ which allows you to analyze your data in dashboards. For this guide, we will select, ‘Dashboard’.

Visualize .NET Data 3

  1. Create a Dashboard: After selecting ‘Dashboard’ you now need to select ‘Create’ towards the right of your screen and ‘Dashboard’ from the dropdown menu.

Visualize .NET Data 4

  1. Editing and Saving a Dashboard: From this page, you can edit your dashboard by adding existing panels and objects or creating new ones. To create a new object select ‘Create New’ from the left of your screen and choose your preferred data presentation type for viewing .NET logdata. Once you’ve added all the objects you desire, click ‘Save’ in the top right. Now you can visualize your .NET logs in Logit.io.

Visualize .NET Data 5

If you've enjoyed this article why not read How to Integrate Serilog with Logit.io or How to Integrate Node.js with Logit.io next?

Get the latest elastic Stack & logging resources when you subscribe

© 2024 Logit.io Ltd, All rights reserved.