diff --git a/docs/logs/getting-started/LoggerExtensions.cs b/docs/logs/getting-started/LoggerExtensions.cs new file mode 100644 index 000000000..0cb86c71c --- /dev/null +++ b/docs/logs/getting-started/LoggerExtensions.cs @@ -0,0 +1,33 @@ +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +using System; +using System.Runtime.CompilerServices; +using Microsoft.Extensions.Logging; + +internal static class LoggerExtensions +{ + // https://docs.microsoft.com/aspnet/core/fundamentals/logging/loggermessage + private static readonly Action LogExAction = LoggerMessage.Define( + LogLevel.Information, + new EventId(1, nameof(LogEx)), + "LogEx({obj})."); + + public static void LogEx(this ILogger logger, object obj) + { + LogExAction(logger, obj, null); + } +} diff --git a/docs/logs/getting-started/Program.cs b/docs/logs/getting-started/Program.cs index 65b5142b2..23f3924d0 100644 --- a/docs/logs/getting-started/Program.cs +++ b/docs/logs/getting-started/Program.cs @@ -14,6 +14,7 @@ // limitations under the License. // +using System.Collections.Generic; using Microsoft.Extensions.Logging; public class Program @@ -26,7 +27,33 @@ public class Program }); var logger = loggerFactory.CreateLogger(); + // unstructured log logger.LogInformation("Hello, World!"); - logger.LogInformation("Hello from {name} {price}.", "artichoke", 3.99); + + // unstructured log with string interpolation + logger.LogInformation($"Hello from potato {0.99}."); + + // structured log with template + logger.LogInformation("Hello from {name} {price}.", "tomato", 2.99); + + // structured log with strong type + logger.LogEx(new Food { Name = "artichoke", Price = 3.99 }); + + // structured log with anonymous type + logger.LogEx(new { Name = "pumpkin", Price = 5.99 }); + + // structured log with general type + logger.LogEx(new Dictionary + { + ["Name"] = "truffle", + ["Price"] = 299.99, + }); + } + + internal struct Food + { + public string Name { get; set; } + + public double Price { get; set; } } }