// Copyright Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace EpicGames.Core
{
///
/// Extension methods for more convenient attaching of properties to log messages
///
public static class LoggerPropertyExtensions
{
///
/// Builder struct for attaching properties to log messages
/// Wraps and disposes log scope.
///
public readonly struct LogScopedPropertyBuilder
{
private readonly Dictionary _properties;
private readonly ILogger _logger;
///
/// Constructor
///
/// Logger to wrap
public LogScopedPropertyBuilder(ILogger logger)
{
_properties = [];
_logger = logger;
}
///
/// Set a key/value property for current log scope
///
/// Arbitrary key
/// Arbitrary value
///
public LogScopedPropertyBuilder WithProperty(string key, object value)
{
_properties[key] = value;
return this;
}
///
/// Starts new scope on underlying logger, passing previously set properties
///
/// Original IDisposable from ILogger.BeginScope()
public IDisposable? BeginScope()
{
return _logger.BeginScope(_properties);
}
}
///
/// Creates a new log scope and attaches a key/value property
/// Additional properties can be added with .
///
/// Logger to use
/// Arbitrary key
/// Arbitrary value
/// A disposable log property builder that wraps the original ILogger scope
///
/// Simple example of attaching two properties
///
/// using (_logger.WithProperty("stream", "ue5").WithProperty("os", "windows").BuildScope())
/// {
/// _logger.LogInformation("A log message with properties attached");
/// }
///
///
public static LogScopedPropertyBuilder WithProperty(this ILogger logger, string key, object value)
{
LogScopedPropertyBuilder builder = new LogScopedPropertyBuilder(logger);
builder.WithProperty(key, value);
return builder;
}
}
}