Table of Contents
The following tutorials have demonstrated the best practices for logging with OpenTelemetry .NET:
- Getting Started - ASP.NET Core Application
- Getting Started - Console Application
- Logging with Complex Objects
✔️ You should use structured logging.
- Structured logging is more efficient than unstructured logging.
- Filtering and redaction can happen on individual key-value pairs instead of the entire log message.
- Storage and indexing are more efficient.
- Structured logging makes it easier to manage and consume logs.
🛑 You should avoid string interpolation.
Warning
The following code has bad performance due to string interpolation:
var food = "tomato";
var price = 2.99;
logger.LogInformation($"Hello from {food} {price}.");
Refer to the logging performance benchmark for more details.
✔️ You should always use the
ILogger
interface (including
ILogger<TCategoryName>
)
from the latest stable version of
Microsoft.Extensions.Logging
package, regardless of the .NET runtime version being used:
- If you are using the latest stable version of OpenTelemetry .NET
SDK, you do not have to worry about the
version of
Microsoft.Extensions.Logging
package because it is already taken care of for you via package dependency. - Starting from version
3.1.0
, the .NET runtime team is holding a high bar for backward compatibility onMicrosoft.Extensions.Logging
even during major version bumps, so compatibility is not a concern here.
.NET supports high performance, structured logging via the
Microsoft.Extensions.Logging.ILogger
interface (including
ILogger<TCategoryName>
)
to help monitor application behavior and diagnose issues.
In order to use the ILogger
interface, you need to first get a logger. How to
get a logger depends on two things:
- The type of application you are building.
- The place where you want to log.
Here is the rule of thumb:
- If you are building an application with dependency injection (DI) (e.g. ASP.NET Core and .NET Worker), in most cases you should use the logger provided by DI, there are special cases when you want log before DI logging pipeline is available or after DI logging pipeline is disposed. Refer to the .NET official document and Getting Started with OpenTelemetry .NET Logs in 5 Minutes - ASP.NET Core Application tutorial to learn more.
- If you are building an application without DI, create a LoggerFactory instance and configure OpenTelemetry to work with it. Refer to the Getting Started with OpenTelemetry .NET Logs in 5 Minutes - Console Application tutorial to learn more.
✔️ You should use dot-separated UpperCamelCase as the log category name, which makes it convenient to filter logs. A common practice is to use fully qualified class name, and if further categorization is desired, append a subcategory name. Refer to the .NET official document to learn more.
loggerFactory.CreateLogger<MyClass>(); // this is equivalent to CreateLogger("MyProduct.MyLibrary.MyClass")
loggerFactory.CreateLogger("MyProduct.MyLibrary.MyClass"); // use the fully qualified class name
loggerFactory.CreateLogger("MyProduct.MyLibrary.MyClass.DatabaseOperations"); // append a subcategory name
loggerFactory.CreateLogger("MyProduct.MyLibrary.MyClass.FileOperations"); // append another subcategory name
🛑 You should avoid creating loggers too frequently. Although loggers are not super expensive, they still come with CPU and memory cost, and are meant to be reused throughout the application. Refer to the logging performance benchmark for more details.
✔️ You should use compile-time logging source generation pattern to achieve the best performance.
var food = "tomato";
var price = 2.99;
logger.SayHello(food, price);
internal static partial class LoggerExtensions
{
[LoggerMessage(Level = LogLevel.Information, Message = "Hello from {food} {price}.")]
public static partial void SayHello(this ILogger logger, string food, double price);
}
Note
There is no need to pass in an explicit
EventId
while using
LoggerMessageAttribute.
A durable EventId
will be automatically assigned based on the hash of the
method name during code generation.
✔️ You can use LogPropertiesAttribute from Microsoft.Extensions.Telemetry.Abstractions if you need to log complex objects. Check out the Logging with Complex Objects tutorial for more details.
🛑 You should avoid the extension methods from LoggerExtensions, these methods are not optimized for performance.
Warning
The following code has bad performance due to boxing:
var food = "tomato";
var price = 2.99;
logger.LogInformation("Hello from {food} {price}.", food, price);
Refer to the logging performance benchmark for more details.
In many cases, you can use ILogger without having to interact with
Microsoft.Extensions.Logging.LoggerFactory
directly. This section is intended for users who need to create and manage
LoggerFactory
explicitly.
🛑 You should avoid creating LoggerFactory
instances too frequently,
LoggerFactory
is fairly expensive and meant to be reused throughout the
application. For most applications, one LoggerFactory
instance per process
would be sufficient.
✔️ You should properly manage the lifecycle of LoggerFactory instances if they are created by you.
- If you forget to dispose the
LoggerFactory
instance before the application ends, logs might get dropped due to the lack of proper flush. - If you dispose the
LoggerFactory
instance too early, any subsequent logging API invocation associated with the logger factory could become no-op (i.e. no logs will be emitted).
In OpenTelemetry, logs are automatically correlated to traces. Check the Log Correlation tutorial to learn more.
TBD
The Customizing OpenTelemetry .NET SDK for Logs document has provided instructions for basic filtering based on logger category name and severity level.
For more advanced filtering and sampling, the .NET team has a plan to cover it in .NET 9 timeframe, please use this runtime issue to track the progress or provide feedback and suggestions.
Logs might contain sensitive information such as passwords and credit card numbers, proper redaction is required to prevent privacy and security incidents. Check the Log Redaction tutorial to learn more.