First, download and install the .NET SDK on your computer.
Create a new console application and run it:
dotnet new console --output getting-started
cd getting-started
dotnet run
You should see the following output:
Hello World!
Install the latest Microsoft.Extensions.Logging
package:
dotnet add package Microsoft.Extensions.Logging
Install the OpenTelemetry.Exporter.Console package:
dotnet add package OpenTelemetry.Exporter.Console
Update the Program.cs
file with the code from Program.cs:
Run the application again (using dotnet run
) and you should see the log output
on the console.
LogRecord.Timestamp: 2023-01-21T00:33:08.1467491Z
LogRecord.CategoryName: GettingStarted.Program
LogRecord.LogLevel: Information
LogRecord.State (Key:Value):
name: tomato
price: 2.99
OriginalFormat (a.k.a Body): Hello from {name} {price}.
LogRecord.EventId: 123
Congratulations! You are now collecting logs using OpenTelemetry.
What does the above program do?
The program creates a
LoggerFactory
with OpenTelemetry added as a
LoggerProvider.
This LoggerFactory
is used to create an
ILogger
instance, which is then used to do the logging. The log is sent to the
OpenTelemetryLoggerProvider
, which is configured to export logs to
ConsoleExporter
. ConsoleExporter
simply displays it on the console.
Note Certain types of applications (e.g. ASP.NET Core and .NET Worker) have an
ILogger
based logging pipeline set up by default. In such apps, enabling OpenTelemetry should be done by adding OpenTelemetry as a provider to the existing logging pipeline, and users should not create a newLoggerFactory
(which sets up a totally new logging pipeline). Also, obtainingILogger
instance could be done differently as well. See Example ASP.NET Core application for an example which shows how to add OpenTelemetry to the logging pipeline already setup by the application.