Add more good/bad examples for ILogger (#1309)

* more good/bad examples for ILogger

* more examples

* simply the example

* add link to the official doc
This commit is contained in:
Reiley Yang 2020-09-28 22:47:28 -07:00 committed by GitHub
parent 6633dc846e
commit 3ef4f82a74
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 61 additions and 1 deletions

View File

@ -0,0 +1,33 @@
// <copyright file="LoggerExtensions.cs" company="OpenTelemetry Authors">
// 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.
// </copyright>
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<ILogger, object, Exception> LogExAction = LoggerMessage.Define<object>(
LogLevel.Information,
new EventId(1, nameof(LogEx)),
"LogEx({obj}).");
public static void LogEx(this ILogger logger, object obj)
{
LogExAction(logger, obj, null);
}
}

View File

@ -14,6 +14,7 @@
// limitations under the License.
// </copyright>
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
public class Program
@ -26,7 +27,33 @@ public class Program
});
var logger = loggerFactory.CreateLogger<Program>();
// 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<string, object>
{
["Name"] = "truffle",
["Price"] = 299.99,
});
}
internal struct Food
{
public string Name { get; set; }
public double Price { get; set; }
}
}