Thursday, June 23, 2022
HomeITMethods to work with hint listeners in ASP.NET Core 6

Methods to work with hint listeners in ASP.NET Core 6


When engaged on functions constructed utilizing ASP.NET Core 6, you would possibly usually wish to use tracing and logging to watch your utility’s efficiency and to diagnose errors. You too can use tracing in a manufacturing setting to measure how your utility is acting at run time.

This text discusses how we are able to use tracing in ASP.NET Core 6. We’ll look at how you can use hint listeners to gather hint messages and direct the hint output to an occasion log utilizing ILogger.

To work with the code examples offered on this article, it’s best to have Visible Studio 2022 put in in your system. Should you don’t have already got a duplicate, you’ll be able to obtain Visible Studio 2022 right here.

Create an ASP.NET Core Net API venture in Visible Studio 2022

First off, let’s create an ASP.NET Core venture in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core 6 Net API venture in Visible Studio 2022:

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new venture.”
  3. Within the “Create new venture” window, choose “ASP.NET Core Net API” from the checklist of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new venture” window, specify the title and site for the brand new venture.
  6. Optionally verify the “Place answer and venture in the identical listing” verify field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Further Info” window proven subsequent, make sure that the checkbox that claims “Use controllers…” is checked since we’ll not be utilizing minimal APIs on this instance. Depart the “Authentication Kind” as “None” (default).
  9. Be sure that the verify containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Assist” are unchecked as we received’t be utilizing any of these options right here.
  10. Click on Create.

We’ll use this ASP.NET Core 6 Net API venture to work with hint listeners within the subsequent sections of this text.

What’s tracing?

In comparison with occasion logging, which tracks main occasions, tracing permits for a way more full view of the operating utility and its elements. Logs comprise structured or unstructured time stamped information that reveals a report of the occasions that happen in your utility. Tracing supplies way more visibility into the person request and the way it’s processed.

The System.Diagnostics namespace comprises the Hint and the Debug courses. Whereas the Hint class is utilized in manufacturing environments, the Debug class is used at improvement time.

Tracing sometimes includes the next three phases:

  • Instrumentation: We write the required code to seize related data
  • Tracing: We write the hint messages to a specified goal, i.e., an occasion log, a textual content file, a database desk, and many others.
  • Evaluation: We analyze the data gathered from traces to find out the bottlenecks within the utility.

What are hint listeners? Why are they wanted?

Hint listeners gather hint messages, retailer them, and direct them to an acceptable goal similar to a textual content file. .NET supplies a number of hint listeners together with the next:

  • ConsoleTraceListener – sends hint messages to the console window.
  • DefaultTraceListener – sends hint messages to plain debug output.
  • DelimitedListTraceListener – sends hint output in a delimited format to a stream, a stream author, or a textual content author.
  • EventLogTraceListener – sends hint messages to occasion logs.
  • TextWriterTraceListener – sends hint messages to a textual content file.
  • XmlWriterTraceListener – converts hint messages to XML.

The System.Diagnostics.Debug and System.Diagnostics.Hint courses can ship messages to hint listeners, which in flip route the messages to an acceptable goal.

Create a hint listener utilizing a config file in ASP.NET Core 6

You may create a hint listener both by utilizing a config file or by writing customized code. The code snippet proven under illustrates how you can create a hint listener utilizing your utility configuration file.

<configuration>
  <system.diagnostics>
    <hint autoflush="false" indentsize="4">
      <listeners>
        <add title="MyFirstListener"
        sort="System.Diagnostics.TextWriterTraceListener"
        initializeData="TraceOutput.txt" />
        <take away title="Default" />
      </listeners>
    </hint>
  </system.diagnostics>
</configuration>

All listeners added to the Listeners assortment will obtain hint output. Nevertheless, you should use a listener with out including it to the Listeners assortment. On this case, you ship output utilizing the Write or WriteLine technique throughout the listener.

The next code illustrates a listener that isn’t added to the Listeners assortment however continues to be able to sending hint messages to an output window, a file, or any pre-configured output.

TextWriterTraceListener myFirstListener = new
TextWriterTraceListener("Output.txt", "myFirstListener");
myFirstListener.WriteLine("This can be a check message.");
myFirstListener.Flush();

Create a customized hint listener in ASP.NET Core 6

The hint listeners that include .NET 6 by default will meet your necessities normally. Nevertheless, if you wish to output your hint messages to a special vacation spot, you’ll be able to implement your individual hint listener.

To construct a customized hint listener, it’s best to create a category that extends the TraceListener summary class. There are a number of digital and summary strategies within the TraceListener class. It’s best to not less than implement the Write and the WriteLine strategies. At a naked minimal, your customized hint listener ought to seem like this:

public class CustomTraceListener : TraceListener
{
    public CustomTraceListener(ILoggerFactory loggerFactory)
    {
    }
    public override void Write(string? message, string? class)
    {           
    }  
    public override void Write(string? message)
    {           
    }
    public override void WriteLine(string? message)
    {           
    }
}

So, your customized hint listener class will need to have an argument constructor and the Write and WriteLine strategies.

Additionally, you will want an ILogger occasion that represents the logger, a logger manufacturing facility to create the logger, and a StringBuilder to retailer the hint messages earlier than they’re despatched to the log goal. 

non-public readonly ILoggerFactory _loggerFactory;
non-public readonly ILogger _iLogger;
non-public readonly StringBuilder _stringBuilder = new();

You may benefit from dependency injection to inject an occasion of ILoggerFactory within the constructor after which use the occasion to create an occasion of ILogger.

public CustomTraceListener(ILoggerFactory loggerFactory)
{
   _loggerFactory = loggerFactory;
   _iLogger = loggerFactory.CreateLogger(nameof(CustomTraceListener));
}

Here’s a minimal implementation of the Write and the WriteLine strategies:

public override void Write(string? message, string? class)
{
     _stringBuilder.Append(message + "-" + class);
}
public override void Write(string? message)
{
     _stringBuilder.Append(message);
}
public override void WriteLine(string? message)
{
   _stringBuilder.AppendLine(message);
   _iLogger.LogInformation(_stringBuilder.ToString());
   _stringBuilder.Clear();
}

Full customized hint listener instance in ASP.NET Core 6

Under is the whole supply code of our minimal implementation of a customized hint listener to your reference.

utilizing System.Collections.Concurrent;
utilizing System.Diagnostics;
utilizing System.Textual content;
namespace TraceListenerDemo
{
    public class CustomTraceListener : TraceListener
    {
        non-public readonly ILoggerFactory _loggerFactory;
        non-public readonly ILogger _iLogger;
        non-public readonly StringBuilder _stringBuilder = new();
        public CustomTraceListener(ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory;
            _iLogger =
             loggerFactory.CreateLogger(nameof(CustomTraceListener));
        }
        public override void Write(string? message, string? class)
        {
            _stringBuilder.Append(message + "-" + class);
        }
        public override void Write(string? message)
        {
            _stringBuilder.Append(message);
        }
        public override void WriteLine(string? message)
        {
            _stringBuilder.AppendLine(message);
            _iLogger.LogInformation(_stringBuilder.ToString());
            _stringBuilder.Clear();
        }
    }
}

Register the customized hint listener within the Program.cs file

To make use of the customized hint listener, it’s best to register it with the Listeners assortment utilizing the next code.

var loggerFactory = app.Providers.GetRequiredService<ILoggerFactory>();
Hint.Listeners.Add(new LoggerTraceListener(loggerFactory));

As a result of our customized hint listener has been added to the listeners assortment, it should seize all hint messages generated by the runtime and ship the output to our logger. It can additionally ship any hint messages that we ship explicitly within the utility (like we did within the myFirstListener instance earlier).

So, any listener added to the Listeners assortment can seize the traces generated by the runtime in addition to any hint messages despatched explicitly within the utility. Nevertheless, if a hint listener isn’t added to the gathering, it could solely ship hint messages despatched explicitly within the utility. It is not going to seize any hint messages generated by the runtime.

When working with customized hint listeners, you have to bear in mind to shut or flush the hint listener to make sure that the output buffer is emptied. You may benefit from the StringBuilderCache class to optimize your code (within the CustomTraceListener class) that makes use of StringBuilder.

Copyright © 2022 IDG Communications, Inc.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments