// Copyright Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
namespace EpicGames.Core
{
///
/// ILogger implementation that adds a prefix to the start of each line
///
public class PrefixLogger : ILogger
{
readonly string _prefix;
readonly ILogger _inner;
///
/// Constructor
///
/// Prefix to insert
/// Logger to write to
public PrefixLogger(string prefix, ILogger inner)
{
_prefix = prefix;
_inner = inner;
}
///
public IDisposable? BeginScope(TState state) where TState : notnull => _inner.BeginScope(state);
///
public bool IsEnabled(LogLevel logLevel) => _inner.IsEnabled(logLevel);
///
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)
{
if (state is IEnumerable> enumerable)
{
List> copy = new List>(enumerable);
int idx = copy.FindIndex(x => x.Key.Equals("{OriginalFormat}", StringComparison.OrdinalIgnoreCase));
if (idx != -1 && copy[idx].Value is string format)
{
copy[idx] = new KeyValuePair(copy[idx].Key, "{_tag} " + format);
copy.Add(new KeyValuePair("_tag", _prefix));
_inner.Log(logLevel, eventId, copy, exception, (s, e) => $"{_prefix} {formatter(state, exception)}");
return;
}
}
_inner.Log(logLevel, eventId, state, exception, formatter);
}
}
}