When dealing with applications built utilizing ASP.NET Core 6, you may typically desire to utilize tracing and logging to monitor your application s efficiency and to identify mistakes. You can likewise use tracing in a production environment to determine how your application is performing at run time.This post goes over how we can utilize tracing in ASP.NET Core 6. We will take a look at how to utilize trace listeners to gather trace messages and direct the trace output to an occasion log utilizing ILogger.To deal with
the code examples provided in this post, you must have Visual Studio 2022 installed in your system. If you put on t currently have a copy, you can download Visual Studio 2022 here.Create an ASP.NET
Core Web API project in Visual Studio 2022 To begin with, let s produce an ASP.NET
Core job in Visual Studio 2022. Following these steps will produce a brand-new ASP.NET Core 6 Web API project in Visual Studio 2022: Launch the Visual Studio 2022 IDE. Click on Produce new project.
- In the Produce new job window
- , choose ASP.NET Core Web API from the list of design templates showed. Click Next. In the Configure your new project window, define the name and location
- for the new project
- . Optionally inspect the Location solution and project in the same directory check box, depending on your
- preferences. Click Next. In the Extra Info window shown next, ensure that the checkbox that says Use controllers is checked
- because we ll not be utilizing minimal APIs in this example. Leave the Authentication Type as None (default ). Make sure that the check boxes Enable Docker, Configure for HTTPS, and Enable Open API Support are unattended as we won t be using any of those functions here.
- Click Create. We ll use this ASP.NET Core 6 Web API job to deal with trace listeners in the subsequent sections of this article.What is tracing?Compared to occasion logging, which tracks major occasions, tracing
- permits a far more
complete view of the running application and its elements. Logs comprise structured or disorganized time stamped information that shows a record of the events that take place in your application. Tracing supplies much more presence into the specific demand and how it is processed. The System.Diagnostics namespace contains the Trace and the Debug classes. While the Trace class is utilized in production environments, the Debug class is used at development time.Tracing normally includes the following three stages: Instrumentation: We compose the needed code to catch pertinent info Tracing: We compose the trace messages to a defined target
, i.e., an occasion log, a text file, a database table, etc. Analysis: We examine the info collected from traces to identify the traffic jams in the application.
What are trace listeners? Why are they needed?Trace listeners collect trace messages, save them, and direct them to an appropriate target such as a text file
EventLogTraceListener sends trace messages to occasion
logs. TextWriterTraceListener sends trace messages to a text file. XmlWriterTraceListener transforms trace messages to XML. The System.Diagnostics.Debug and System.Diagnostics.Trace classes can
- send messages to trace listeners, which in turn
- route the messages to an appropriate target.Create a trace listener using a config file
- in ASP.NET Core 6 You can create a trace listener either by using a config file or by composing custom-made code. The code bit
- shown below illustrates how to create a trace listener utilizing
- your application configuration file.
< remove name=" Default"/ >
All listeners included to the Listeners collection will get trace output. Nevertheless, you can utilize a listener without adding it to the Listeners collection. In this case, you send out output using the Write or WriteLine approach within the listener.
<); myFirstListener.WriteLine("This is a test message."); myFirstListener.Flush (); Create a custom trace listener in ASP.NET Core 6 The trace listeners that come with.NET 6 by default will satisfy your requirements most of the times. Nevertheless, if you wish to output your trace messages to a different destination
, you can execute your own trace listener.To construct a customized trace listener, you should produce a class that extends the TraceListener abstract class. There are several virtual and abstract techniques in the TraceListener class.
You ought to a minimum of implement the Write and the WriteLine techniques. At a bare minimum, your customized trace listener must appear like this: public class CustomTraceListener: TraceListener public CustomTraceListener (ILoggerFactory loggerFactory)< public override void Write(string? message, string? classification) public override space Write(string? message) public override void WriteLine(string? message)
So, your custom trace listener class should have an argument constructor and the Write and WriteLine approaches. You will likewise require an ILogger instance that represents the logger, a logger factory to develop the logger, anda StringBuilder to store the trace messages
are sent out to the log target. personal readonly ILoggerFactory _ loggerFactory; private readonly ILogger _ iLogger; personal readonly StringBuilder _ stringBuilder=new()
; You can take benefit
of dependence injection to inject an instance of ILoggerFactory in the fitter and then use the
circumstances to produce a circumstances of ILogger.public CustomTraceListener(ILoggerFactory loggerFactory)> _ loggerFactory=loggerFactory; _ iLogger=loggerFactory.CreateLogger( nameof(CustomTraceListener) ); Here is a very little execution of the Write and the WriteLine techniques: public override space Write(string? message, string
? category )_ stringBuilder.Append( message+"- "+category); public override space Write(string? message)_ stringBuilder.Append(message); public override space WriteLine(string? message)_ stringBuilder.AppendLine(message);utilizing System.Diagnostics; using System.Text; namespace TraceListenerDemo public class CustomTraceListener:the Program.cs file To utilize the customized trace
listener, you ought to register it with the Listeners collection using the following code.var loggerFactory =app.Services.GetRequiredService (); Trace.Listeners.Add( brand-new LoggerTraceListener ( loggerFactory)); Since our custom trace listener
has been contributed to the listeners collection,
it will capture all trace messages generated by the runtime and send out the output to our logger. It will likewise send any trace messages that
we send explicitly in the application (like we performed in the
previously ). So, any listener contributed to the Listeners collection can catch
the traces created by the runtime in addition to any trace messages sent out explicitly in the application. However, if a trace listener is not contributed to the collection
, it can just send out trace messages sent explicitly in the application.
It will not record any trace messages produced by the runtime.When dealing with custom trace listeners, you must keep in mind to close or flush the trace listener to guarantee that the output buffer is cleared. You can
take benefit of the StringBuilderCache class to optimize your
code ( in the CustomTraceListener class)that
Copyright 2022 Swilio Communications, Inc.