#define DEBUG using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using NLog.Attributes; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Filters; using NLog.Internal; using NLog.Internal.Fakeables; using NLog.LayoutRenderers; using NLog.LayoutRenderers.Wrappers; using NLog.Layouts; using NLog.MessageTemplates; using NLog.Targets; using NLog.Targets.FileAppenders; using NLog.Targets.FileArchiveHandlers; using NLog.Targets.Wrappers; using NLog.Time; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("NLog.UnitTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100ef8eab4fbdeb511eeb475e1659fe53f00ec1c1340700f1aa347bf3438455d71993b28b1efbed44c8d97a989e0cb6f01bcb5e78f0b055d311546f63de0a969e04cf04450f43834db9f909e566545a67e42822036860075a1576e90e1c43d43e023a24c22a427f85592ae56cac26f13b7ec2625cbc01f9490d60f16cfbb1bc34d9")] [assembly: InternalsVisibleTo("NLog.Benchmarks, PublicKey=0024000004800000940000000602000000240000525341310004000001000100ef8eab4fbdeb511eeb475e1659fe53f00ec1c1340700f1aa347bf3438455d71993b28b1efbed44c8d97a989e0cb6f01bcb5e78f0b055d311546f63de0a969e04cf04450f43834db9f909e566545a67e42822036860075a1576e90e1c43d43e023a24c22a427f85592ae56cac26f13b7ec2625cbc01f9490d60f16cfbb1bc34d9")] [assembly: AllowPartiallyTrustedCallers] [assembly: SecurityRules(SecurityRuleSet.Level1)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("NLog")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (c) 2004-2026 NLog Project - https://nlog-project.org/ ")] [assembly: AssemblyDescription("NLog is a logging platform for .NET with rich log routing and management capabilities.\nNLog supports traditional logging, structured logging and the combination of both.\n\nSupported platforms:\n\n- .NET 6, 7, 8, 9 and 10\n- .NET Standard 2.0 and 2.1\n- .NET Framework 3.5 - 4.8\n- Xamarin Android + iOS (.NET Standard)\n- Mono 4\n\nFor integrating NLog with Microsoft.Extensions.Logging, check: https://www.nuget.org/packages/NLog.Extensions.Logging\n\nFor using NLog with ASP.NET Core, check: https://www.nuget.org/packages/NLog.Web.AspNetCore\n ")] [assembly: AssemblyFileVersion("6.1.1.5033")] [assembly: AssemblyInformationalVersion("6.1.1+0e83056311dfcda0493d7db60b7191d0927eb5da")] [assembly: AssemblyProduct("NLog v6.1.1")] [assembly: AssemblyTitle("NLog for NetStandard 2.1")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/NLog/NLog.git")] [assembly: AssemblyVersion("6.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class ParamCollectionAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class ScopedRefAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string Param { get; } public CallerArgumentExpressionAttribute(string param) { Param = param; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] internal sealed class OverloadResolutionPriorityAttribute : Attribute { public int Priority { get; } public OverloadResolutionPriorityAttribute(int priority) { Priority = priority; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string? Scope { get; set; } public string? Target { get; set; } public string? MessageId { get; set; } public string? Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } } namespace NLog { public static class GlobalDiagnosticsContext { private static readonly object _lockObject = new object(); private static Dictionary _dict = new Dictionary(StringComparer.OrdinalIgnoreCase); private static Dictionary? _dictReadOnly; public static void Set(string item, string? value) { Set(item, (object?)value); } public static void Set(string item, object? value) { Guard.ThrowIfNull(item, "item"); lock (_lockObject) { GetWritableDict()[item] = value; } } public static string Get(string item) { Guard.ThrowIfNull(item, "item"); return Get(item, null); } public static string Get(string item, IFormatProvider? formatProvider) { Guard.ThrowIfNull(item, "item"); return FormatHelper.ConvertToString(GetObject(item), formatProvider); } public static object? GetObject(string item) { Guard.ThrowIfNull(item, "item"); GetReadOnlyDict().TryGetValue(item, out object value); return value; } public static ICollection GetNames() { return GetReadOnlyDict().Keys; } public static bool Contains(string item) { Guard.ThrowIfNull(item, "item"); return GetReadOnlyDict().ContainsKey(item); } public static void Remove(string item) { Guard.ThrowIfNull(item, "item"); lock (_lockObject) { if (_dict.ContainsKey(item)) { GetWritableDict().Remove(item); } } } public static void Clear() { lock (_lockObject) { if (_dict.Count != 0) { GetWritableDict(clearDictionary: true).Clear(); } } } internal static Dictionary GetReadOnlyDict() { Dictionary dictionary = _dictReadOnly; if (dictionary == null) { lock (_lockObject) { dictionary = (_dictReadOnly = _dict); } } return dictionary; } private static Dictionary GetWritableDict(bool clearDictionary = false) { if (_dictReadOnly != null) { _dict = CopyDictionaryOnWrite(clearDictionary); _dictReadOnly = null; } return _dict; } private static Dictionary CopyDictionaryOnWrite(bool clearDictionary) { Dictionary dictionary = new Dictionary((!clearDictionary) ? (_dict.Count + 1) : 0, _dict.Comparer); if (!clearDictionary) { foreach (KeyValuePair item in _dict) { dictionary[item.Key] = item.Value; } } return dictionary; } } public interface IJsonConverter { bool SerializeObject(object? value, StringBuilder builder); } [CLSCompliant(false)] public interface ILogger : ISuppress, ILoggerBase { bool IsTraceEnabled { get; } bool IsDebugEnabled { get; } bool IsInfoEnabled { get; } bool IsWarnEnabled { get; } bool IsErrorEnabled { get; } bool IsFatalEnabled { get; } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Trace(object? value); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, object? value); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Trace([Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Debug(object? value); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, object? value); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Debug([Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Info(object? value); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, object? value); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Info([Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Warn(object? value); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, object? value); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Warn([Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Error(object? value); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, object? value); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, object argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Error([Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Fatal(object? value); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, object? value); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, ulong argument); void Trace(T? value); void Trace(IFormatProvider? formatProvider, T? value); void Trace(LogMessageGenerator messageFunc); void Trace(Exception? exception, [Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Trace(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Trace(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); void Trace([Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Trace([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [Obsolete("Use Trace(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Trace([Localizable(false)] string message, Exception? exception); [MessageTemplateFormatMethod("message")] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Trace([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Trace([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [MessageTemplateFormatMethod("message")] void Trace([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [Obsolete("Use Trace(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void TraceException([Localizable(false)] string message, Exception? exception); void Debug(T? value); void Debug(IFormatProvider? formatProvider, T? value); void Debug(LogMessageGenerator messageFunc); void Debug(Exception? exception, [Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Debug(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Debug(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); void Debug([Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Debug([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Debug([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Debug([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [MessageTemplateFormatMethod("message")] void Debug([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [Obsolete("Use Debug(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Debug([Localizable(false)] string message, Exception exception); [Obsolete("Use Debug(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void DebugException([Localizable(false)] string message, Exception? exception); void Info(T? value); void Info(IFormatProvider? formatProvider, T? value); void Info(LogMessageGenerator messageFunc); void Info(Exception? exception, [Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Info(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Info(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); void Info([Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Info([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Info([Localizable(false)][StructuredMessageTemplate] string message, TArgument argument); [MessageTemplateFormatMethod("message")] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Info([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [MessageTemplateFormatMethod("message")] void Info([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [Obsolete("Use Info(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Info([Localizable(false)] string message, Exception? exception); [Obsolete("Use Info(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void InfoException([Localizable(false)] string message, Exception? exception); void Warn(T? value); void Warn(IFormatProvider? formatProvider, T? value); void Warn(LogMessageGenerator messageFunc); void Warn(Exception? exception, [Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Warn(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Warn(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); void Warn([Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Warn([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Warn([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Warn([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [MessageTemplateFormatMethod("message")] void Warn([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [Obsolete("Use Warn(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Warn([Localizable(false)] string message, Exception? exception); [Obsolete("Use Warn(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void WarnException([Localizable(false)] string message, Exception? exception); void Error(T? value); void Error(IFormatProvider? formatProvider, T? value); void Error(LogMessageGenerator messageFunc); void Error(Exception? exception, [Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Error(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Error(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); void Error([Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Error([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Error([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Error([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [MessageTemplateFormatMethod("message")] void Error([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [Obsolete("Use Error(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Error([Localizable(false)] string message, Exception? exception); [Obsolete("Use Error(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void ErrorException([Localizable(false)] string message, Exception? exception); void Fatal(T? value); void Fatal(IFormatProvider? formatProvider, T? value); void Fatal(LogMessageGenerator messageFunc); void Fatal(Exception? exception, [Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Fatal(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Fatal(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); void Fatal([Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [MessageTemplateFormatMethod("message")] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [Obsolete("Use Fatal(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Fatal([Localizable(false)] string message, Exception? exception); [Obsolete("Use Fatal(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void FatalException([Localizable(false)] string message, Exception? exception); } [CLSCompliant(false)] [Obsolete("ILoggerBase should be replaced with ILogger. Marked obsolete with NLog v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public interface ILoggerBase { string Name { get; } [Obsolete("Factory-property is hard to mock for ILogger-interface. Instead use Logger.Factory. Marked obsolete with NLog v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] LogFactory Factory { get; } [Obsolete("LoggerReconfigured-EventHandler is very exotic for ILogger-interface. Instead use Logger.LoggerReconfigured. Marked obsolete with NLog v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] event EventHandler LoggerReconfigured; [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Log(LogLevel level, object? value); [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, object? value); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, bool argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, char argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, byte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, string? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, int argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, long argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, float argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, double argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, object? argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, uint argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument); [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument); bool IsEnabled(LogLevel level); void Log(LogEventInfo logEvent); void Log(Type wrapperType, LogEventInfo logEvent); void Log(LogLevel level, T? value); void Log(LogLevel level, IFormatProvider? formatProvider, T? value); void Log(LogLevel level, LogMessageGenerator messageFunc); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); void Log(LogLevel level, [Localizable(false)] string message); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [MessageTemplateFormatMethod("message")] void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); [Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Log(LogLevel level, [Localizable(false)] string message, Exception? exception); [Obsolete("Use Log(LogLevel level, Exception exception, [Localizable(false)] string message, params object[] args) instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void LogException(LogLevel level, [Localizable(false)] string message, Exception? exception); } [CLSCompliant(false)] public static class ILoggerExtensions { public static LogEventBuilder ForLogEvent(this ILogger logger, LogLevel? logLevel = null) { if ((object)logLevel != null) { return new LogEventBuilder(logger, logLevel); } return new LogEventBuilder(logger); } public static LogEventBuilder ForTraceEvent(this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Trace); } public static LogEventBuilder ForDebugEvent(this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Debug); } public static LogEventBuilder ForInfoEvent(this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Info); } public static LogEventBuilder ForWarnEvent(this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Warn); } public static LogEventBuilder ForErrorEvent(this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Error); } public static LogEventBuilder ForFatalEvent(this ILogger logger) { return new LogEventBuilder(logger, LogLevel.Fatal); } public static LogEventBuilder ForExceptionEvent(this ILogger logger, Exception? exception, LogLevel? logLevel = null) { return logger.ForLogEvent(logLevel ?? LogLevel.Error).Exception(exception); } [Conditional("DEBUG")] public static void ConditionalDebug(this ILogger logger, T? value) { logger.Debug(value); } [Conditional("DEBUG")] public static void ConditionalDebug(this ILogger logger, IFormatProvider? formatProvider, T? value) { logger.Debug(formatProvider, value); } [Conditional("DEBUG")] public static void ConditionalDebug(this ILogger logger, LogMessageGenerator messageFunc) { logger.Debug(messageFunc); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug(this ILogger logger, Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { logger.Debug(exception, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug(this ILogger logger, Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { logger.Debug(exception, formatProvider, message, args); } [Conditional("DEBUG")] public static void ConditionalDebug(this ILogger logger, [Localizable(false)] string message) { logger.Debug(message); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug(this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { logger.Debug(message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug(this ILogger logger, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { logger.Debug(formatProvider, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug(this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (logger.IsDebugEnabled) { logger.Debug(message, (object?)argument); } } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug(this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (logger.IsDebugEnabled) { logger.Debug(message, (object?)argument1, (object?)argument2); } } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalDebug(this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (logger.IsDebugEnabled) { logger.Debug(message, (object?)argument1, (object?)argument2, (object?)argument3); } } [Conditional("DEBUG")] public static void ConditionalTrace(this ILogger logger, T? value) { logger.Trace(value); } [Conditional("DEBUG")] public static void ConditionalTrace(this ILogger logger, IFormatProvider? formatProvider, T? value) { logger.Trace(formatProvider, value); } [Conditional("DEBUG")] public static void ConditionalTrace(this ILogger logger, LogMessageGenerator messageFunc) { logger.Trace(messageFunc); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace(this ILogger logger, Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { logger.Trace(exception, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace(this ILogger logger, Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { logger.Trace(exception, formatProvider, message, args); } [Conditional("DEBUG")] public static void ConditionalTrace(this ILogger logger, [Localizable(false)] string message) { logger.Trace(message); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace(this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { logger.Trace(message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace(this ILogger logger, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { logger.Trace(formatProvider, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace(this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (logger.IsTraceEnabled) { logger.Trace(message, (object?)argument); } } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace(this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (logger.IsTraceEnabled) { logger.Trace(message, (object?)argument1, (object?)argument2); } } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public static void ConditionalTrace(this ILogger logger, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (logger.IsTraceEnabled) { logger.Trace(message, (object?)argument1, (object?)argument2, (object?)argument3); } } public static void Log(this ILogger logger, LogLevel level, Exception? exception, LogMessageGenerator messageFunc) { if (logger.IsEnabled(level)) { logger.Log(level, exception, messageFunc(), ArrayHelper.Empty()); } } public static void Trace(this ILogger logger, Exception? exception, LogMessageGenerator messageFunc) { if (logger.IsTraceEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); logger.Trace(exception, messageFunc()); } } public static void Debug(this ILogger logger, Exception? exception, LogMessageGenerator messageFunc) { if (logger.IsDebugEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); logger.Debug(exception, messageFunc()); } } public static void Info(this ILogger logger, Exception? exception, LogMessageGenerator messageFunc) { if (logger.IsInfoEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); logger.Info(exception, messageFunc()); } } public static void Warn(this ILogger logger, Exception? exception, LogMessageGenerator messageFunc) { if (logger.IsWarnEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); logger.Warn(exception, messageFunc()); } } public static void Error(this ILogger logger, Exception? exception, LogMessageGenerator messageFunc) { if (logger.IsErrorEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); logger.Error(exception, messageFunc()); } } public static void Fatal(this ILogger logger, Exception? exception, LogMessageGenerator messageFunc) { if (logger.IsFatalEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); logger.Fatal(exception, messageFunc()); } } } internal interface IObjectTypeTransformer { object? TryTransformObject(object obj); } [Obsolete("ISuppress should be replaced with ILogger. Marked obsolete with NLog v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public interface ISuppress { void Swallow(Action action); T? Swallow(Func func); T? Swallow(Func func, T? fallback); void Swallow(Task task); Task SwallowAsync(Task task); Task SwallowAsync(Func asyncAction); Task SwallowAsync(Func> asyncFunc); Task SwallowAsync(Func> asyncFunc, TResult? fallback); } public interface IValueFormatter { bool FormatValue(object? value, string? format, CaptureType captureType, IFormatProvider? formatProvider, StringBuilder builder); } public static class LayoutTypedExtensions { public static T? RenderValue(this Layout? layout, LogEventInfo logEvent, T? defaultValue = default(T?)) { if (layout != null) { return layout.RenderTypedValue(logEvent, defaultValue); } return defaultValue; } } [CLSCompliant(false)] public struct LogEventBuilder { private readonly ILogger _logger; private readonly LogEventInfo? _logEvent; public ILogger Logger => _logger; public LogEventInfo? LogEvent { get { if (_logEvent != null) { return ResolveLogEvent(_logEvent); } return null; } } public LogEventBuilder(ILogger logger) { _logger = Guard.ThrowIfNull(logger, "logger"); _logEvent = new LogEventInfo { LoggerName = _logger.Name }; } public LogEventBuilder(ILogger logger, LogLevel logLevel) { _logger = Guard.ThrowIfNull(logger, "logger"); Guard.ThrowIfNull(logLevel, "logLevel"); if (logger.IsEnabled(logLevel)) { _logEvent = new LogEventInfo { LoggerName = _logger.Name, Level = logLevel }; } else { _logEvent = null; } } public LogEventBuilder Property(string propertyName, T? propertyValue) { Guard.ThrowIfNull(propertyName, "propertyName"); if (_logEvent != null) { _logEvent.Properties[propertyName] = propertyValue; } return this; } public LogEventBuilder Properties(IEnumerable> properties) { Guard.ThrowIfNull(properties, "properties"); if (_logEvent != null) { foreach (KeyValuePair property in properties) { _logEvent.Properties[property.Key] = property.Value; } } return this; } public LogEventBuilder Properties(IReadOnlyCollection> properties) { Guard.ThrowIfNull(properties, "properties"); if (_logEvent != null && properties.Count > 0) { PropertiesDictionary propertiesDictionary = _logEvent.CreatePropertiesInternal(null, properties.Count); foreach (KeyValuePair property in properties) { propertiesDictionary[property.Key] = property.Value; } } return this; } public LogEventBuilder Properties(ReadOnlySpan<(string, object?)> properties) { if (_logEvent != null && !properties.IsEmpty) { PropertiesDictionary propertiesDictionary = _logEvent.CreatePropertiesInternal(null, properties.Length); ReadOnlySpan<(string, object)> readOnlySpan = properties; for (int i = 0; i < readOnlySpan.Length; i++) { (string, object) tuple = readOnlySpan[i]; propertiesDictionary[tuple.Item1] = tuple.Item2; } } return this; } public LogEventBuilder Exception(Exception? exception) { if (_logEvent != null) { _logEvent.Exception = exception; } return this; } public LogEventBuilder TimeStamp(DateTime timeStamp) { if (_logEvent != null) { _logEvent.TimeStamp = timeStamp; } return this; } public LogEventBuilder Message([Localizable(false)] string message) { if (_logEvent != null) { _logEvent.Parameters = null; _logEvent.Message = message; } return this; } [MessageTemplateFormatMethod("message")] public LogEventBuilder Message([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (_logEvent != null) { _logEvent.Message = message; _logEvent.Parameters = new object[1] { argument }; } return this; } [MessageTemplateFormatMethod("message")] public LogEventBuilder Message([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (_logEvent != null) { _logEvent.Message = message; _logEvent.Parameters = new object[2] { argument1, argument2 }; } return this; } [MessageTemplateFormatMethod("message")] public LogEventBuilder Message([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (_logEvent != null) { _logEvent.Message = message; _logEvent.Parameters = new object[3] { argument1, argument2, argument3 }; } return this; } [MessageTemplateFormatMethod("message")] public LogEventBuilder Message([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (_logEvent != null) { _logEvent.Message = message; _logEvent.Parameters = args; } return this; } [MessageTemplateFormatMethod("message")] public LogEventBuilder Message([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (_logEvent != null) { _logEvent.Message = message; _logEvent.Parameters = (args.IsEmpty ? null : args.ToArray()); } return this; } [MessageTemplateFormatMethod("message")] public LogEventBuilder Message(IFormatProvider formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (_logEvent != null) { _logEvent.FormatProvider = formatProvider; _logEvent.Message = message; _logEvent.Parameters = args; } return this; } public LogEventBuilder Callsite(string? callerClassName = null, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) { if (_logEvent != null) { _logEvent.SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber); } return this; } public void Log(LogLevel? logLevel = null, [CallerMemberName] string? callerMemberName = null, [CallerFilePath] string? callerFilePath = null, [CallerLineNumber] int callerLineNumber = 0) { if (_logEvent != null) { LogEventInfo logEventInfo = ResolveLogEvent(_logEvent, logLevel); if (logEventInfo.CallSiteInformation == null && _logger.IsEnabled(logEventInfo.Level)) { _logEvent.SetCallerInfo(null, callerMemberName, callerFilePath, callerLineNumber); } _logger.Log(logEventInfo); } } public void Log(Type wrapperType) { if (_logEvent != null) { LogEventInfo logEvent = ResolveLogEvent(_logEvent); _logger.Log(wrapperType, logEvent); } } private LogEventInfo ResolveLogEvent(LogEventInfo logEvent, LogLevel? logLevel = null) { if ((object)logLevel == null) { if ((object)logEvent.Level == null) { logEvent.Level = ((logEvent.Exception != null) ? LogLevel.Error : LogLevel.Info); } } else { logEvent.Level = logLevel; } if ((logEvent.Message == null || (object)logEvent.Message == string.Empty) && logEvent.Exception != null && _logger.IsEnabled(logEvent.Level)) { logEvent.FormatProvider = ExceptionMessageFormatProvider.Instance; logEvent.Message = "{0}"; logEvent.Parameters = new object[1] { logEvent.Exception }; } return logEvent; } } public class LogEventInfo { private sealed class LayoutCacheLinkedNode { public readonly Layout Key; public readonly object? Value; public LayoutCacheLinkedNode? Next; public LayoutCacheLinkedNode(Layout key, object? value) { Key = key; Value = value; } } public static readonly DateTime ZeroDate = DateTime.UtcNow; private static int globalSequenceId; private string? _formattedMessage; private string _message; private object?[]? _parameters; private IFormatProvider? _formatProvider; private LogMessageFormatter? _messageFormatter; private LayoutCacheLinkedNode? _layoutCache; private PropertiesDictionary? _properties; private int _sequenceId; [Obsolete("Use ${counter:sequence=global} instead of ${sequenceid}. Marked obsolete with NLog 6.0")] [EditorBrowsable(EditorBrowsableState.Never)] public int SequenceID { get { if (_sequenceId == 0) { Interlocked.CompareExchange(ref _sequenceId, Interlocked.Increment(ref globalSequenceId), 0); } return _sequenceId; } } public DateTime TimeStamp { get; set; } public LogLevel Level { get; set; } internal CallSiteInformation? CallSiteInformation { get; private set; } public bool HasStackTrace => CallSiteInformation?.StackTrace != null; [Obsolete("Instead use ${callsite} or CallerMemberName. Marked obsolete with NLog 5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public StackFrame? UserStackFrame => CallSiteInformation?.UserStackFrame; [Obsolete("Instead use ${callsite} or CallerMemberName. Marked obsolete with NLog 5.4")] [EditorBrowsable(EditorBrowsableState.Never)] public int UserStackFrameNumber => CallSiteInformation?.UserStackFrameNumberLegacy ?? CallSiteInformation?.UserStackFrameNumber ?? 0; public StackTrace? StackTrace => CallSiteInformation?.StackTrace; public string? CallerClassName => CallSiteInformation?.GetCallerClassName(null, includeNameSpace: true, cleanAsyncMoveNext: true, cleanAnonymousDelegates: true); public string? CallerMemberName => CallSiteInformation?.GetCallerMethodName(null, includeMethodInfo: false, cleanAsyncMoveNext: true, cleanAnonymousDelegates: true); public string? CallerFilePath => CallSiteInformation?.GetCallerFilePath(0); public int CallerLineNumber => CallSiteInformation?.GetCallerLineNumber(0) ?? 0; public Exception? Exception { get; set; } public string LoggerName { get; set; } public string Message { get { return _message; } set { bool parseMessageTemplateParameters = ResetMessageTemplateParameters(); _message = value; ResetFormattedMessage(parseMessageTemplateParameters); } } public object?[]? Parameters { get { return _parameters; } set { bool parseMessageTemplateParameters = ResetMessageTemplateParameters(); _parameters = value; ResetFormattedMessage(parseMessageTemplateParameters); } } public IFormatProvider? FormatProvider { get { return _formatProvider; } set { if (_formatProvider != value) { _formatProvider = value; ResetFormattedMessage(parseMessageTemplateParameters: false); } } } public LogMessageFormatter MessageFormatter { get { return _messageFormatter ?? LogManager.LogFactory.ActiveMessageFormatter; } set { LogMessageFormatter logMessageFormatter = value ?? LogMessageStringFormatter.Default.MessageFormatter; if ((object)_messageFormatter != logMessageFormatter) { _messageFormatter = logMessageFormatter; _formattedMessage = null; ResetFormattedMessage(parseMessageTemplateParameters: false); } } } public string FormattedMessage { get { if (_formattedMessage == null) { CalcFormattedMessage(); } return _formattedMessage ?? Message; } } public bool HasProperties { get { if (_properties == null) { PropertiesDictionary? propertiesDictionary = TryCreatePropertiesInternal(); if (propertiesDictionary == null) { return false; } return propertiesDictionary.Count > 0; } return _properties.Count > 0; } } public IDictionary Properties => _properties ?? CreatePropertiesInternal(); private bool HasMessageTemplateParameters { get { if (_formattedMessage == null) { object?[]? parameters = _parameters; if (parameters != null && parameters.Length != 0) { return (MessageFormatter.Target as ILogMessageFormatter)?.HasProperties(this) ?? false; } } return false; } } public MessageTemplateParameters MessageTemplateParameters { get { PropertiesDictionary? properties = _properties; if (properties != null && properties.MessageProperties.Count > 0) { return new MessageTemplateParameters(_properties.MessageProperties); } object?[]? parameters = _parameters; if (parameters != null && parameters.Length != 0) { return new MessageTemplateParameters(_message, _parameters); } return NLog.MessageTemplates.MessageTemplateParameters.Empty; } } public LogEventInfo() { TimeStamp = TimeSource.Current.Time; _message = string.Empty; LoggerName = string.Empty; Level = LogLevel.Off; } public LogEventInfo(LogLevel level, string? loggerName, [Localizable(false)] string message) : this(level, loggerName, null, message, null, null) { } public LogEventInfo(LogLevel level, string? loggerName, [Localizable(false)] string message, IList? messageTemplateParameters) : this(level, loggerName, null, message, null, null) { if (messageTemplateParameters == null) { return; } int count = messageTemplateParameters.Count; if (count > 0) { MessageTemplateParameter[] array = new MessageTemplateParameter[count]; for (int i = 0; i < count; i++) { array[i] = messageTemplateParameters[i]; } _properties = new PropertiesDictionary(array); } } public LogEventInfo(LogLevel level, string? loggerName, [Localizable(false)] string formattedMessage, [Localizable(false)] string messageTemplate, IList? messageTemplateParameters) : this(level, loggerName, messageTemplate, messageTemplateParameters) { _formattedMessage = formattedMessage; _messageFormatter = (LogEventInfo l) => l._formattedMessage ?? l.Message ?? string.Empty; } public LogEventInfo(LogLevel level, string? loggerName, [Localizable(false)] string formattedMessage, [Localizable(false)] string messageTemplate, ReadOnlySpan messageTemplateParameters) : this(level, loggerName, messageTemplate) { _formattedMessage = formattedMessage; _messageFormatter = (LogEventInfo l) => l._formattedMessage ?? l.Message ?? string.Empty; if (messageTemplateParameters.Length > 0) { MessageTemplateParameter[] array = new MessageTemplateParameter[messageTemplateParameters.Length]; for (int i = 0; i < messageTemplateParameters.Length; i++) { array[i] = messageTemplateParameters[i]; } _properties = new PropertiesDictionary(array); } } public LogEventInfo(LogLevel level, string? loggerName, [Localizable(false)] string message, IReadOnlyList>? eventProperties) : this(level, loggerName, null, message, null, null) { if (eventProperties == null) { return; } int count = eventProperties.Count; if (count > 0) { _properties = new PropertiesDictionary(count); for (int i = 0; i < count; i++) { KeyValuePair keyValuePair = eventProperties[i]; _properties[keyValuePair.Key] = keyValuePair.Value; } } } public LogEventInfo(LogLevel level, string? loggerName, IFormatProvider? formatProvider, [Localizable(false)] string message, object?[]? parameters) : this(level, loggerName, formatProvider, message, parameters, null) { } public LogEventInfo(LogLevel level, string? loggerName, IFormatProvider? formatProvider, [Localizable(false)] string message, object?[]? parameters, Exception? exception) { TimeStamp = TimeSource.Current.Time; Level = level; LoggerName = loggerName ?? string.Empty; _formatProvider = formatProvider; _message = message; Parameters = parameters; Exception = exception; } internal CallSiteInformation GetCallSiteInformationInternal() { return CallSiteInformation ?? (CallSiteInformation = new CallSiteInformation()); } internal PropertiesDictionary? TryCreatePropertiesInternal(IList? templateParameters = null) { PropertiesDictionary properties = _properties; if (properties == null) { if ((templateParameters != null && templateParameters.Count > 0) || (templateParameters == null && HasMessageTemplateParameters)) { return CreatePropertiesInternal(templateParameters); } } else if (templateParameters != null) { properties.ResetMessageProperties(templateParameters); } return properties; } internal PropertiesDictionary CreatePropertiesInternal(IList? templateParameters = null, int initialCapacity = 0) { if (_properties == null) { PropertiesDictionary value = ((templateParameters == null) ? new PropertiesDictionary(initialCapacity) : new PropertiesDictionary(templateParameters)); Interlocked.CompareExchange(ref _properties, value, null); if (templateParameters == null && HasMessageTemplateParameters) { CalcFormattedMessage(); } } return _properties; } public static LogEventInfo CreateNullEvent() { return new LogEventInfo(LogLevel.Off, string.Empty, null, string.Empty, null, null); } public static LogEventInfo Create(LogLevel logLevel, string? loggerName, [Localizable(false)] string message) { return new LogEventInfo(logLevel, loggerName, null, message, null, null); } [MessageTemplateFormatMethod("message")] public static LogEventInfo Create(LogLevel logLevel, string? loggerName, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object?[]? parameters) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters, null); } public static LogEventInfo Create(LogLevel logLevel, string? loggerName, IFormatProvider? formatProvider, object? message) { Exception ex = message as Exception; if (ex == null && message is LogEventInfo logEventInfo) { logEventInfo.LoggerName = loggerName ?? logEventInfo.LoggerName; logEventInfo.Level = logLevel; logEventInfo.FormatProvider = formatProvider ?? logEventInfo.FormatProvider; return logEventInfo; } formatProvider = formatProvider ?? ((ex != null) ? ExceptionMessageFormatProvider.Instance : null); return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new object[1] { message }, ex); } public static LogEventInfo Create(LogLevel logLevel, string? loggerName, Exception? exception, IFormatProvider? formatProvider, [Localizable(false)] string message) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, null, exception); } [MessageTemplateFormatMethod("message")] public static LogEventInfo Create(LogLevel logLevel, string? loggerName, Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object?[]? parameters) { return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters, exception); } public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation) { return new AsyncLogEventInfo(this, asyncContinuation); } public override string ToString() { return $"Log Event: Logger='{LoggerName}' Level={Level} Message='{FormattedMessage}'"; } public void SetStackTrace(StackTrace stackTrace) { GetCallSiteInformationInternal().SetStackTrace(stackTrace); } [Obsolete("Instead use SetStackTrace or SetCallerInfo. Marked obsolete with NLog 5.4")] [EditorBrowsable(EditorBrowsableState.Never)] public void SetStackTrace(StackTrace stackTrace, int userStackFrame) { GetCallSiteInformationInternal().SetStackTrace(stackTrace, (userStackFrame >= 0) ? new int?(userStackFrame) : null); } public void SetCallerInfo(string? callerClassName, string? callerMemberName, string? callerFilePath, int callerLineNumber) { GetCallSiteInformationInternal().SetCallerInfo(callerClassName, callerMemberName, callerFilePath, callerLineNumber); } internal void AddCachedLayoutValue(Layout layout, object? value) { LayoutCacheLinkedNode layoutCacheLinkedNode = new LayoutCacheLinkedNode(layout, value); LayoutCacheLinkedNode layoutCacheLinkedNode2 = _layoutCache; object value2; while (layoutCacheLinkedNode2 == null || !TryGetCachedLayoutValue(layout, out value2)) { layoutCacheLinkedNode.Next = layoutCacheLinkedNode2; layoutCacheLinkedNode2 = Interlocked.CompareExchange(ref _layoutCache, layoutCacheLinkedNode, layoutCacheLinkedNode2); if (layoutCacheLinkedNode2 == layoutCacheLinkedNode.Next) { break; } } } internal bool TryGetCachedLayoutValue(Layout layout, out object? value) { for (LayoutCacheLinkedNode layoutCacheLinkedNode = _layoutCache; layoutCacheLinkedNode != null; layoutCacheLinkedNode = layoutCacheLinkedNode.Next) { if (layoutCacheLinkedNode.Key == layout) { value = layoutCacheLinkedNode.Value; return true; } } value = null; return false; } private static bool NeedToPreformatMessage(object?[]? parameters) { if (parameters == null || parameters.Length == 0) { return false; } if (parameters.Length > 5) { return true; } for (int i = 0; i < parameters.Length; i++) { if (!IsSafeToDeferFormatting(parameters[i])) { return true; } } return false; } internal static bool NeedToPreformatMessage(in ReadOnlySpan parameters) { if (parameters.IsEmpty) { return false; } if (parameters.Length > 5) { return true; } ReadOnlySpan readOnlySpan = parameters; for (int i = 0; i < readOnlySpan.Length; i++) { if (!IsSafeToDeferFormatting(readOnlySpan[i])) { return true; } } return false; } private static bool IsSafeToDeferFormatting(object? value) { return Convert.GetTypeCode(value) != TypeCode.Object; } internal bool IsLogEventThreadAgnosticImmutable() { if (Exception != null) { return false; } if (_formattedMessage != null) { object?[]? parameters = _parameters; if (parameters != null && parameters.Length != 0) { return false; } } PropertiesDictionary propertiesDictionary = TryCreatePropertiesInternal(); if (propertiesDictionary == null || propertiesDictionary.Count == 0) { return true; } if (propertiesDictionary.Count > 5) { return false; } if (propertiesDictionary.Count == _parameters?.Length && propertiesDictionary.Count == propertiesDictionary.MessageProperties.Count) { return true; } return HasImmutableProperties(propertiesDictionary); } private static bool HasImmutableProperties(PropertiesDictionary properties) { IList messageProperties = properties.MessageProperties; if (properties.Count == messageProperties.Count) { for (int i = 0; i < messageProperties.Count; i++) { if (!IsSafeToDeferFormatting(messageProperties[i].Value)) { return false; } } } else { using PropertiesDictionary.PropertyDictionaryEnumerator propertyDictionaryEnumerator = properties.GetPropertyEnumerator(); while (propertyDictionaryEnumerator.MoveNext()) { if (!IsSafeToDeferFormatting(propertyDictionaryEnumerator.Current.Value)) { return false; } } } return true; } internal void SetMessageFormatter(LogMessageFormatter messageFormatter, LogMessageFormatter? singleTargetMessageFormatter) { bool num = _messageFormatter != null; if (!num) { _messageFormatter = messageFormatter; } if (num || NeedToPreformatMessage(_parameters)) { CalcFormattedMessage(); } else { if (singleTargetMessageFormatter == null) { return; } object?[]? parameters = _parameters; if (parameters != null && parameters.Length != 0) { string message = _message; if (message != null && message.Length < 256) { _messageFormatter = singleTargetMessageFormatter; } } } } private void CalcFormattedMessage() { try { _formattedMessage = MessageFormatter(this); } catch (Exception ex) { _formattedMessage = Message ?? string.Empty; InternalLogger.Warn(ex, "Error when formatting a message."); if (ex.MustBeRethrown()) { throw; } } } internal void AppendFormattedMessage(ILogMessageFormatter messageFormatter, StringBuilder builder) { if (_formattedMessage != null) { builder.Append(_formattedMessage); return; } object?[]? parameters = _parameters; if (parameters != null && parameters.Length != 0 && !string.IsNullOrEmpty(_message)) { int length = builder.Length; try { messageFormatter.AppendFormattedMessage(this, builder); return; } catch (Exception ex) { builder.Length = length; builder.Append(_message); InternalLogger.Warn(ex, "Error when formatting a message."); if (ex.MustBeRethrown()) { throw; } return; } } builder.Append(FormattedMessage); } private void ResetFormattedMessage(bool parseMessageTemplateParameters) { if (_messageFormatter == null || _messageFormatter.Target is ILogMessageFormatter) { _formattedMessage = null; } if (parseMessageTemplateParameters && HasMessageTemplateParameters) { CalcFormattedMessage(); } } private bool ResetMessageTemplateParameters() { if (_properties == null) { return false; } if (HasMessageTemplateParameters) { _properties.ResetMessageProperties(); return true; } return _properties.MessageProperties.Count == 0; } } public class LogFactory : LogFactory where T : Logger, new() { public new T GetLogger(string name) { return GetLogger(name); } [MethodImpl(MethodImplOptions.NoInlining)] public new T GetCurrentClassLogger() { string classFullName = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, needFileInfo: false)); return GetLogger(classFullName); } } public class LogFactory : IDisposable, IAsyncDisposable { private readonly struct LoggerCacheKey : IEquatable { public readonly string Name; public readonly Type ConcreteType; public LoggerCacheKey(string name, Type concreteType) { Name = name; ConcreteType = concreteType; } public override int GetHashCode() { return ConcreteType.GetHashCode() ^ Name.GetHashCode(); } public override bool Equals(object? obj) { if (obj is LoggerCacheKey other) { return Equals(other); } return false; } public bool Equals(LoggerCacheKey other) { if (ConcreteType == other.ConcreteType) { return string.Equals(other.Name, Name, StringComparison.Ordinal); } return false; } } private sealed class LoggerCache { private readonly Dictionary _loggerCache = new Dictionary(); public int Count => _loggerCache.Count; public void InsertOrUpdate(LoggerCacheKey cacheKey, Logger logger) { _loggerCache[cacheKey] = new WeakReference(logger); } public Logger? Retrieve(LoggerCacheKey cacheKey) { if (_loggerCache.TryGetValue(cacheKey, out WeakReference value)) { return value.Target as Logger; } return null; } public List GetLoggers() { List list = new List(_loggerCache.Count); foreach (KeyValuePair item2 in _loggerCache) { if (item2.Value.Target is Logger item) { list.Add(item); } } return list; } public void Reset() { _loggerCache.Clear(); } public void PurgeObsoleteLoggers() { foreach (LoggerCacheKey item in _loggerCache.Keys.ToList()) { if (Retrieve(item) == null) { _loggerCache.Remove(item); } } } } private sealed class LogEnabler : IDisposable { private readonly LogFactory _factory; public LogEnabler(LogFactory factory) { _factory = factory; } void IDisposable.Dispose() { _factory.ResumeLogging(); } } private static readonly TimeSpan DefaultFlushTimeout = TimeSpan.FromSeconds(15.0); private static AppEnvironmentWrapper? defaultAppEnvironment; internal readonly object _syncRoot = new object(); private readonly LoggerCache _loggerCache = new LoggerCache(); private readonly ServiceRepositoryInternal _serviceRepository; private readonly IAppEnvironment _currentAppEnvironment; internal LoggingConfiguration? _config; internal LogMessageFormatter ActiveMessageFormatter; internal LogMessageFormatter? SingleTargetMessageFormatter; internal LogMessageTemplateFormatter? AutoMessageTemplateFormatter; private LogLevel _globalThreshold = LogLevel.MinLevel; private bool _configLoaded; private int _supendLoggingCounter; [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] private List? _candidateConfigFilePaths; private readonly ILoggingConfigurationLoader _configLoader; private bool _autoShutdown = true; internal CultureInfo? _defaultCultureInfo; private bool _isDisposing; internal static IAppEnvironment DefaultAppEnvironment => defaultAppEnvironment ?? (defaultAppEnvironment = new AppEnvironmentWrapper()); internal IAppEnvironment CurrentAppEnvironment => _currentAppEnvironment; public ServiceRepository ServiceRepository => _serviceRepository; public bool ThrowExceptions { get; set; } public bool? ThrowConfigExceptions { get; set; } public bool KeepVariablesOnReload { get; set; } = true; public bool AutoShutdown { get { return _autoShutdown; } set { if (value != _autoShutdown) { _autoShutdown = value; LoggerShutdown -= OnStopLogging; if (value) { LoggerShutdown += OnStopLogging; } } } } [CanBeNull] public LoggingConfiguration? Configuration { get { if (_configLoaded) { return _config; } lock (_syncRoot) { if (_configLoaded || _isDisposing) { return _config; } LoggingConfiguration loggingConfiguration = _configLoader.Load(this); if (loggingConfiguration != null) { ActivateLoggingConfiguration(loggingConfiguration); } return _config; } } set { lock (_syncRoot) { LoggingConfiguration config = _config; if (config != null) { InternalLogger.Info("Closing old configuration."); config.OnConfigurationAssigned(null); Flush(); config.Close(); } if (value == null) { _config = value; _configLoaded = false; } else { ActivateLoggingConfiguration(value); } OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(value, config)); } } } public LogLevel GlobalThreshold { get { return _globalThreshold; } set { lock (_syncRoot) { if (_globalThreshold != value) { InternalLogger.Info("LogFactory GlobalThreshold changing to LogLevel: {0}", value); } _globalThreshold = value ?? LogLevel.MinLevel; ReconfigExistingLoggers(); } } } public CultureInfo? DefaultCultureInfo { get { if (_config != null) { return _config.DefaultCultureInfo; } return _defaultCultureInfo; } set { if (_config != null && (_config.DefaultCultureInfo == _defaultCultureInfo || _config.DefaultCultureInfo == null)) { _config.DefaultCultureInfo = value; } _defaultCultureInfo = value; } } public event EventHandler? ConfigurationChanged; private static event EventHandler LoggerShutdown { add { if (LogFactory._loggerShutdown == null) { InternalLogger.Debug("Registered shutdown event handler for ProcessExit."); DefaultAppEnvironment.ProcessExit += OnLoggerShutdown; } _loggerShutdown += value; } remove { _loggerShutdown -= value; if (LogFactory._loggerShutdown == null && defaultAppEnvironment != null) { InternalLogger.Debug("Unregistered shutdown event handler for ProcessExit."); defaultAppEnvironment.ProcessExit -= OnLoggerShutdown; } } } private static event EventHandler? _loggerShutdown; public LogFactory() : this(new LoggingConfigurationFileLoader(DefaultAppEnvironment)) { } [Obsolete("Constructor with LoggingConfiguration as parameter should not be used. Instead provide LogFactory as parameter when constructing LoggingConfiguration. Marked obsolete in NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public LogFactory(LoggingConfiguration config) : this() { Configuration = config; } internal LogFactory(ILoggingConfigurationLoader configLoader, IAppEnvironment? appEnvironment = null) { _configLoader = configLoader; _currentAppEnvironment = appEnvironment ?? DefaultAppEnvironment; LoggerShutdown += OnStopLogging; _serviceRepository = new ServiceRepositoryInternal(this); _serviceRepository.TypeRegistered += ServiceRepository_TypeRegistered; ActiveMessageFormatter = RefreshMessageFormatter(); } private void ActivateLoggingConfiguration(LoggingConfiguration config) { if (_config == null) { LogNLogAssemblyVersion(); } _config = config; _configLoaded = true; _config.OnConfigurationAssigned(this); _config.Dump(); ReconfigExistingLoggers(); InternalLogger.Info("Configuration initialized: {0}", config); } private void ServiceRepository_TypeRegistered(object? sender, ServiceRepositoryUpdateEventArgs e) { _config?.CheckForMissingServiceTypes(e.ServiceType); if (e.ServiceType == typeof(ILogMessageFormatter)) { RefreshMessageFormatter(); } } private LogMessageFormatter RefreshMessageFormatter() { ILogMessageFormatter service = _serviceRepository.GetService(); ActiveMessageFormatter = service.FormatMessage; if (service is LogMessageTemplateFormatter logMessageTemplateFormatter) { LogMessageTemplateFormatter logMessageTemplateFormatter2 = new LogMessageTemplateFormatter(this, logMessageTemplateFormatter.EnableMessageTemplateParser.GetValueOrDefault(), singleTargetOnly: true); SingleTargetMessageFormatter = logMessageTemplateFormatter2.FormatMessage; AutoMessageTemplateFormatter = (logMessageTemplateFormatter.EnableMessageTemplateParser.GetValueOrDefault() ? null : logMessageTemplateFormatter2); } else { SingleTargetMessageFormatter = null; AutoMessageTemplateFormatter = null; } return ActiveMessageFormatter; } internal static void LogNLogAssemblyVersion() { try { AssemblyHelpers.LogAssemblyVersion(typeof(LogFactory).Assembly); } catch (Exception ex) { InternalLogger.Debug(ex, "Not running in full trust"); } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public async ValueTask DisposeAsync() { lock (_syncRoot) { if (_config == null || !_configLoaded || _isDisposing) { DisposeInternal(closeConfig: false); return; } } try { await FlushAsync(CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); } catch (Exception ex) { InternalLogger.Error(ex, "LogFactory DisposeAsync Flush Failed."); } try { Task task = Task.Delay(DefaultFlushTimeout).ContinueWith(delegate { throw new TaskCanceledException("NLog LogFactory Dispose Timeout"); }); await Task.WhenAny(new Task[2] { Task.Run(delegate { DisposeInternal(); }), task }).Unwrap().ConfigureAwait(continueOnCapturedContext: false); GC.SuppressFinalize(this); } catch (Exception ex2) { InternalLogger.Error(ex2, "LogFactory DisposeAsync Failed."); } } public ISetupBuilder Setup() { return new SetupBuilder(this); } public LogFactory Setup(Action setupBuilder) { Guard.ThrowIfNull(setupBuilder, "setupBuilder"); setupBuilder(new SetupBuilder(this)); return this; } public Logger CreateNullLogger() { return new NullLogger(this); } [MethodImpl(MethodImplOptions.NoInlining)] public Logger GetCurrentClassLogger() { string classFullName = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, needFileInfo: false)); return GetLogger(classFullName); } [MethodImpl(MethodImplOptions.NoInlining)] public T GetCurrentClassLogger() where T : Logger, new() { string classFullName = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, needFileInfo: false)); return GetLogger(classFullName); } [MethodImpl(MethodImplOptions.NoInlining)] [Obsolete("Replaced by GetCurrentClassLogger(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public Logger GetCurrentClassLogger([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type loggerType) { string classFullName = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, needFileInfo: false)); return GetLogger(classFullName, loggerType ?? typeof(Logger)); } public Logger GetLogger(string name) { return GetLoggerThreadSafe(name, Logger.DefaultLoggerType, (Type t) => new Logger()); } public T GetLogger(string name) where T : Logger, new() { return (T)GetLoggerThreadSafe(name, typeof(T), (Type t) => new T()); } [Obsolete("Replaced by GetLogger(). Marked obsolete on NLog 5.2")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2067")] [EditorBrowsable(EditorBrowsableState.Never)] public Logger GetLogger(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type loggerType) { return GetLoggerThreadSafe(name, loggerType ?? typeof(Logger), (Type t) => (!Logger.DefaultLoggerType.IsAssignableFrom(t)) ? null : (Activator.CreateInstance(t, nonPublic: true) as Logger)); } private bool RefreshExistingLoggers() { List loggers; bool result; lock (_syncRoot) { _config?.InitializeAll(); loggers = _loggerCache.GetLoggers(); result = loggers.Count != _loggerCache.Count; } foreach (Logger item in loggers) { item.SetConfiguration(BuildLoggerConfiguration(item.Name)); } return result; } public void ReconfigExistingLoggers() { RefreshExistingLoggers(); } public void ReconfigExistingLoggers(bool purgeObsoleteLoggers) { purgeObsoleteLoggers = RefreshExistingLoggers() && purgeObsoleteLoggers; if (purgeObsoleteLoggers) { lock (_syncRoot) { _loggerCache.PurgeObsoleteLoggers(); } } } public void Flush() { Flush(DefaultFlushTimeout); } public void Flush(TimeSpan timeout) { FlushInternal(timeout, null); } public void Flush(int timeoutMilliseconds) { Flush(TimeSpan.FromMilliseconds(timeoutMilliseconds)); } public void Flush(AsyncContinuation asyncContinuation) { Flush(asyncContinuation, TimeSpan.MaxValue); } public void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds) { Flush(asyncContinuation, TimeSpan.FromMilliseconds(timeoutMilliseconds)); } public void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout) { FlushInternal(timeout, asyncContinuation); } private bool FlushInternal(TimeSpan flushTimeout, AsyncContinuation? asyncContinuation) { AsyncContinuation asyncContinuation2 = asyncContinuation; InternalLogger.Debug("LogFactory Starting Flush with timeout={0} secs", flushTimeout.TotalSeconds); bool result; try { LoggingConfiguration loggingConfiguration; lock (_syncRoot) { loggingConfiguration = _config; if (!_configLoaded) { loggingConfiguration = null; } } if (loggingConfiguration == null) { asyncContinuation2?.Invoke(null); result = true; } else { asyncContinuation2 = ((asyncContinuation2 == null) ? null : AsyncHelpers.PreventMultipleCalls(asyncContinuation2)); using ManualResetEvent manualResetEvent = new ManualResetEvent(initialState: false); ManualResetEvent ev = manualResetEvent; AsyncContinuation asyncContinuation3 = loggingConfiguration.FlushAllTargets(delegate(Exception? ex) { asyncContinuation2?.Invoke(ex); ev?.Set(); }); if (asyncContinuation3 == null) { asyncContinuation2?.Invoke(null); result = true; } else { bool flag = manualResetEvent.WaitOne(flushTimeout); ev = null; asyncContinuation3(null); asyncContinuation2?.Invoke(flag ? null : new NLogRuntimeException("LogFactory Flush Timeout")); result = flag; } } } catch (Exception ex2) { InternalLogger.Error(ex2, "LogFactory failed to flush targets."); asyncContinuation2?.Invoke(ex2); result = false; } return result; } public Task FlushAsync(CancellationToken cancellationToken) { InternalLogger.Debug("LogFactory Starting Flush Async"); LoggingConfiguration config; lock (_syncRoot) { config = _config; if (config == null || !_configLoaded) { return Task.CompletedTask; } } TaskCompletionSource flushCompleted = new TaskCompletionSource(); AsyncContinuation flushTimeoutHandler = config.FlushAllTargets(delegate { flushCompleted.SetResult(result: true); }); if (flushTimeoutHandler == null) { return Task.CompletedTask; } Task task = Task.Delay(cancellationToken.CanBeCanceled ? (-1) : ((int)DefaultFlushTimeout.TotalMilliseconds), cancellationToken).ContinueWith(delegate { throw new TaskCanceledException("NLog LogFactory Flush Timeout"); }); task.ContinueWith(delegate { flushTimeoutHandler(null); flushCompleted.TrySetCanceled(); }); return Task.WhenAny(new Task[2] { flushCompleted.Task, task }).Unwrap(); } public IDisposable SuspendLogging() { lock (_syncRoot) { _supendLoggingCounter++; if (_supendLoggingCounter == 1) { ReconfigExistingLoggers(); } } return new LogEnabler(this); } public void ResumeLogging() { lock (_syncRoot) { _supendLoggingCounter--; if (_supendLoggingCounter == 0) { ReconfigExistingLoggers(); } } } public bool IsLoggingEnabled() { return _supendLoggingCounter <= 0; } protected virtual void OnConfigurationChanged(LoggingConfigurationChangedEventArgs e) { this.ConfigurationChanged?.Invoke(this, e); } internal ITargetWithFilterChain[] BuildLoggerConfiguration(string loggerName) { LogLevel globalLogLevel = (IsLoggingEnabled() ? GlobalThreshold : LogLevel.Off); return _config?.BuildLoggerConfiguration(loggerName, globalLogLevel) ?? TargetWithFilterChain.NoTargetsByLevel; } private void DisposeInternal(bool closeConfig = true) { if (_isDisposing) { return; } _isDisposing = true; _serviceRepository.TypeRegistered -= ServiceRepository_TypeRegistered; LoggerShutdown -= OnStopLogging; if (Monitor.TryEnter(_syncRoot, 500)) { try { _configLoader.Dispose(); LoggingConfiguration config = _config; if (_configLoaded && config != null) { if (closeConfig) { CloseOldConfig(config); } else { InternalLogger.Warn("Target flush timeout. One or more targets did not complete flush operation, skipping target close."); } } } finally { Monitor.Exit(_syncRoot); this.ConfigurationChanged = null; } } else { this.ConfigurationChanged = null; } InternalLogger.Info("LogFactory has been disposed."); } private void CloseOldConfig(LoggingConfiguration oldConfig) { try { oldConfig.OnConfigurationAssigned(null); _config = null; _configLoaded = true; ReconfigExistingLoggers(); oldConfig.Close(); OnConfigurationChanged(new LoggingConfigurationChangedEventArgs(null, oldConfig)); } catch (Exception ex) { InternalLogger.Error(ex, "LogFactory failed to close NLog LoggingConfiguration."); } } protected virtual void Dispose(bool disposing) { if (disposing) { DisposeInternal(); } } public void Shutdown() { InternalLogger.Info("LogFactory shutting down ..."); if (!_isDisposing && _configLoaded) { lock (_syncRoot) { if (_isDisposing || !_configLoaded) { return; } Configuration = null; _configLoaded = true; ReconfigExistingLoggers(); } } InternalLogger.Info("LogFactory shutdown completed."); } [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public IEnumerable GetCandidateConfigFilePaths() { if (_candidateConfigFilePaths != null) { return _candidateConfigFilePaths.AsReadOnly(); } return _configLoader.GetDefaultCandidateConfigFilePaths(); } [Obsolete("Replaced by chaining LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] internal IEnumerable GetCandidateConfigFilePaths(string? filename) { if (_candidateConfigFilePaths != null) { return GetCandidateConfigFilePaths(); } return _configLoader.GetDefaultCandidateConfigFilePaths(string.IsNullOrEmpty(filename) ? null : filename); } [Obsolete("Replaced by chaining LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public void SetCandidateConfigFilePaths(IEnumerable filePaths) { _candidateConfigFilePaths = new List(); if (filePaths != null) { _candidateConfigFilePaths.AddRange(filePaths); } } [Obsolete("Replaced by chaining LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public void ResetCandidateConfigFilePath() { _candidateConfigFilePaths = null; } private Logger GetLoggerThreadSafe(string name, Type loggerType, Func loggerCreator) { if (name == null) { throw new ArgumentNullException("name", "Name of logger cannot be null"); } LoggerCacheKey cacheKey = new LoggerCacheKey(name, loggerType); lock (_syncRoot) { Logger logger = _loggerCache.Retrieve(cacheKey); if (logger != null) { return logger; } Logger logger2 = CreateNewLogger(loggerType, loggerCreator); if (logger2 == null) { cacheKey = new LoggerCacheKey(cacheKey.Name, typeof(Logger)); logger2 = new Logger(); } LoggingConfiguration? obj = _config ?? ((_loggerCache.Count == 0) ? Configuration : null); logger2.Initialize(name, BuildLoggerConfiguration(name), this); if (obj == null && _loggerCache.Count == 0) { InternalLogger.Info("NLog Configuration has not been loaded."); } _loggerCache.InsertOrUpdate(cacheKey, logger2); return logger2; } } internal Logger CreateNewLogger(Type loggerType, Func loggerCreator) { try { Logger logger = loggerCreator(loggerType); if (logger != null) { return logger; } if (Logger.DefaultLoggerType.IsAssignableFrom(loggerType)) { throw new NLogRuntimeException($"GetLogger / GetCurrentClassLogger with type '{loggerType}' could not create instance of NLog Logger"); } if (ThrowExceptions || LogManager.ThrowExceptions) { throw new NLogRuntimeException($"GetLogger / GetCurrentClassLogger with type '{loggerType}' does not inherit from NLog Logger"); } } catch (Exception ex) { InternalLogger.Error(ex, "GetLogger / GetCurrentClassLogger. Cannot create instance of type '{0}'. It should have an default constructor.", new ReadOnlySpan(new object[1] { loggerType })); if (ex.MustBeRethrown()) { throw; } } return new Logger(); } [Obsolete("Replaced by LogFactory.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public LogFactory LoadConfiguration(string configFile) { return LoadConfiguration(configFile, optional: false); } internal LogFactory LoadConfiguration(string? configFile, bool optional) { string text = ((configFile == null || string.IsNullOrEmpty(configFile)) ? "NLog.config" : configFile); if (optional && string.Equals(text.Trim(), "NLog.config", StringComparison.OrdinalIgnoreCase) && _config != null) { return this; } LoggingConfiguration loggingConfiguration = _configLoader.Load(this, configFile); if (loggingConfiguration == null) { if (!optional) { throw new FileNotFoundException(CreateFileNotFoundMessage(configFile), text); } return this; } Configuration = loggingConfiguration; return this; } private string CreateFileNotFoundMessage(string? configFile) { StringBuilder stringBuilder = new StringBuilder("Failed to load NLog LoggingConfiguration."); try { HashSet hashSet = new HashSet(_configLoader.GetDefaultCandidateConfigFilePaths(configFile)); stringBuilder.AppendLine(" Searched the following locations:"); foreach (string item in hashSet) { stringBuilder.Append("- "); stringBuilder.AppendLine(item); } } catch (Exception arg) { InternalLogger.Debug("Failed to GetDefaultCandidateConfigFilePaths in CreateFileNotFoundMessage: {0}", arg); } return stringBuilder.ToString(); } internal int ResetLoggerCache() { int count = _loggerCache.Count; _loggerCache.Reset(); return count; } private static void OnLoggerShutdown(object? sender, EventArgs args) { try { LogFactory._loggerShutdown?.Invoke(null, args); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Error(ex, "LogFactory failed to shutdown properly."); } finally { LogFactory._loggerShutdown = null; if (defaultAppEnvironment != null) { defaultAppEnvironment.ProcessExit -= OnLoggerShutdown; } } } private void OnStopLogging(object? sender, EventArgs args) { try { InternalLogger.Info("AppDomain Shutting down. LogFactory closing..."); bool closeConfig = true; if (PlatformDetector.IsWin32) { closeConfig = FlushInternal(TimeSpan.FromMilliseconds(1500.0), null); } DisposeInternal(closeConfig); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Error(ex, "LogFactory failed to close down."); } } } [CLSCompliant(true)] public class Logger : ILogger, ISuppress, ILoggerBase { internal static readonly Type DefaultLoggerType = typeof(Logger); private ITargetWithFilterChain[] _targetsByLevel = TargetWithFilterChain.NoTargetsByLevel; private Logger _contextLogger; private ThreadSafeDictionary? _contextProperties; private volatile bool _isTraceEnabled; private volatile bool _isDebugEnabled; private volatile bool _isInfoEnabled; private volatile bool _isWarnEnabled; private volatile bool _isErrorEnabled; private volatile bool _isFatalEnabled; public bool IsTraceEnabled => _contextLogger._isTraceEnabled; public bool IsDebugEnabled => _contextLogger._isDebugEnabled; public bool IsInfoEnabled => _contextLogger._isInfoEnabled; public bool IsWarnEnabled => _contextLogger._isWarnEnabled; public bool IsErrorEnabled => _contextLogger._isErrorEnabled; public bool IsFatalEnabled => _contextLogger._isFatalEnabled; public string Name { get; private set; } public LogFactory Factory { get; private set; } public IDictionary Properties => _contextProperties ?? Interlocked.CompareExchange(ref _contextProperties, CreateContextPropertiesDictionary(null), null) ?? _contextProperties; public event EventHandler? LoggerReconfigured; [Conditional("DEBUG")] public void ConditionalDebug(T? value) { Debug(value); } [Conditional("DEBUG")] public void ConditionalDebug(IFormatProvider? formatProvider, T? value) { Debug(formatProvider, value); } [Conditional("DEBUG")] public void ConditionalDebug(LogMessageGenerator messageFunc) { Debug(messageFunc); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { Debug(exception, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { Debug(exception, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { Debug(exception, formatProvider, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { Debug(formatProvider, message, args); } [Conditional("DEBUG")] public void ConditionalDebug([Localizable(false)] string message) { Debug(message); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { Debug(message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { Debug(message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { Debug(message, argument); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { Debug(formatProvider, message, argument1, argument2); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { Debug(message, argument1, argument2); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { Debug(formatProvider, message, argument1, argument2, argument3); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { Debug(message, argument1, argument2, argument3); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void ConditionalDebug(object? value) { this.Debug(value); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, object? value) { this.Debug(formatProvider, value); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2) { this.Debug(message, arg1, arg2); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3) { this.Debug(message, arg1, arg2, arg3); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { this.Debug(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, char argument) { this.Debug(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { this.Debug(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, string? argument) { this.Debug(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, int argument) { this.Debug(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, long argument) { this.Debug(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, float argument) { this.Debug(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, double argument) { this.Debug(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { this.Debug(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { this.Debug(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalDebug([Localizable(false)][StructuredMessageTemplate] string message, object? argument) { this.Debug(message, argument); } [Conditional("DEBUG")] public void ConditionalTrace(T? value) { Trace(value); } [Conditional("DEBUG")] public void ConditionalTrace(IFormatProvider? formatProvider, T? value) { Trace(formatProvider, value); } [Conditional("DEBUG")] public void ConditionalTrace(LogMessageGenerator messageFunc) { Trace(messageFunc); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { Trace(exception, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { Trace(exception, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { Trace(exception, formatProvider, message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { Trace(formatProvider, message, args); } [Conditional("DEBUG")] public void ConditionalTrace([Localizable(false)] string message) { Trace(message); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { Trace(message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { Trace(message, args); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { Trace(message, argument); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { Trace(formatProvider, message, argument1, argument2); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { Trace(message, argument1, argument2); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { Trace(formatProvider, message, argument1, argument2, argument3); } [Conditional("DEBUG")] [MessageTemplateFormatMethod("message")] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { Trace(message, argument1, argument2, argument3); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void ConditionalTrace(object value) { this.Trace(value); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, object? value) { this.Trace(formatProvider, value); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2) { this.Trace(message, arg1, arg2); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3) { this.Trace(message, arg1, arg2, arg3); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { this.Trace(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, char argument) { this.Trace(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { this.Trace(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, string? argument) { this.Trace(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, int argument) { this.Trace(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, long argument) { this.Trace(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, float argument) { this.Trace(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, double argument) { this.Trace(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { this.Trace(message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { this.Trace(formatProvider, message, argument); } [Conditional("DEBUG")] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void ConditionalTrace([Localizable(false)][StructuredMessageTemplate] string message, object? argument) { this.Trace(message, argument); } public void Trace(T? value) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, value); } } public void Trace(IFormatProvider? formatProvider, T? value) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, value); } } public void Trace(LogMessageGenerator messageFunc) { if (IsTraceEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); WriteToTargets(LogLevel.Trace, messageFunc()); } } [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, args); } } public void Trace([Localizable(false)] string message) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, message); } } [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsTraceEnabled) { WriteToTargetsWithSpan(LogLevel.Trace, null, Factory.DefaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Trace(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsTraceEnabled) { WriteToTargetsWithSpan(LogLevel.Trace, exception, Factory.DefaultCultureInfo, message, in args); } } public void Trace(Exception? exception, [Localizable(false)] string message) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, exception, Factory.DefaultCultureInfo, message, null); } } [MessageTemplateFormatMethod("message")] public void Trace(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, exception, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Trace(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, exception, formatProvider, message, args); } } [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(trace, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(trace, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(trace, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(trace, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(trace, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(trace, null, defaultCultureInfo, message, in args); } } public void Debug(T? value) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, value); } } public void Debug(IFormatProvider? formatProvider, T? value) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, value); } } public void Debug(LogMessageGenerator messageFunc) { if (IsDebugEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); WriteToTargets(LogLevel.Debug, messageFunc()); } } [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, args); } } public void Debug([Localizable(false)] string message) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, message); } } [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsDebugEnabled) { WriteToTargetsWithSpan(LogLevel.Debug, null, Factory.DefaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Debug(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsDebugEnabled) { WriteToTargetsWithSpan(LogLevel.Debug, exception, Factory.DefaultCultureInfo, message, in args); } } public void Debug(Exception? exception, [Localizable(false)] string message) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, exception, Factory.DefaultCultureInfo, message, null); } } [MessageTemplateFormatMethod("message")] public void Debug(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, exception, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Debug(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, exception, formatProvider, message, args); } } [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(debug, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(debug, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(debug, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(debug, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(debug, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(debug, null, defaultCultureInfo, message, in args); } } public void Info(T? value) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, value); } } public void Info(IFormatProvider? formatProvider, T? value) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, value); } } public void Info(LogMessageGenerator messageFunc) { if (IsInfoEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); WriteToTargets(LogLevel.Info, messageFunc()); } } [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, args); } } public void Info([Localizable(false)] string message) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, message); } } [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsInfoEnabled) { WriteToTargetsWithSpan(LogLevel.Info, null, Factory.DefaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Info(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsInfoEnabled) { WriteToTargetsWithSpan(LogLevel.Info, exception, Factory.DefaultCultureInfo, message, in args); } } public void Info(Exception? exception, [Localizable(false)] string message) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, exception, Factory.DefaultCultureInfo, message, null); } } [MessageTemplateFormatMethod("message")] public void Info(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, exception, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Info(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, exception, formatProvider, message, args); } } [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(info, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(info, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(info, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(info, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(info, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Info([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(info, null, defaultCultureInfo, message, in args); } } public void Warn(T? value) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, value); } } public void Warn(IFormatProvider? formatProvider, T? value) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, value); } } public void Warn(LogMessageGenerator messageFunc) { if (IsWarnEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); WriteToTargets(LogLevel.Warn, messageFunc()); } } [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, args); } } public void Warn([Localizable(false)] string message) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, message); } } [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsWarnEnabled) { WriteToTargetsWithSpan(LogLevel.Warn, null, Factory.DefaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Warn(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsWarnEnabled) { WriteToTargetsWithSpan(LogLevel.Warn, exception, Factory.DefaultCultureInfo, message, in args); } } public void Warn(Exception? exception, [Localizable(false)] string message) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, exception, Factory.DefaultCultureInfo, message, null); } } [MessageTemplateFormatMethod("message")] public void Warn(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, exception, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Warn(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, exception, formatProvider, message, args); } } [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(warn, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(warn, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(warn, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(warn, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(warn, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(warn, null, defaultCultureInfo, message, in args); } } public void Error(T? value) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, value); } } public void Error(IFormatProvider? formatProvider, T? value) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, value); } } public void Error(LogMessageGenerator messageFunc) { if (IsErrorEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); WriteToTargets(LogLevel.Error, messageFunc()); } } [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, args); } } public void Error([Localizable(false)] string message) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, message); } } [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsErrorEnabled) { WriteToTargetsWithSpan(LogLevel.Error, null, Factory.DefaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Error(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsErrorEnabled) { WriteToTargetsWithSpan(LogLevel.Error, exception, Factory.DefaultCultureInfo, message, in args); } } public void Error(Exception? exception, [Localizable(false)] string message) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, exception, Factory.DefaultCultureInfo, message, null); } } [MessageTemplateFormatMethod("message")] public void Error(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, exception, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Error(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, exception, formatProvider, message, args); } } [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(error, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(error, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(error, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(error, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(error, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Error([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(error, null, defaultCultureInfo, message, in args); } } public void Fatal(T? value) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, value); } } public void Fatal(IFormatProvider? formatProvider, T? value) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, value); } } public void Fatal(LogMessageGenerator messageFunc) { if (IsFatalEnabled) { Guard.ThrowIfNull(messageFunc, "messageFunc"); WriteToTargets(LogLevel.Fatal, messageFunc()); } } [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, args); } } public void Fatal([Localizable(false)] string message) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, message); } } [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsFatalEnabled) { WriteToTargetsWithSpan(LogLevel.Fatal, null, Factory.DefaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Fatal(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsFatalEnabled) { WriteToTargetsWithSpan(LogLevel.Fatal, exception, Factory.DefaultCultureInfo, message, in args); } } public void Fatal(Exception? exception, [Localizable(false)] string message) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, exception, Factory.DefaultCultureInfo, message, null); } } [MessageTemplateFormatMethod("message")] public void Fatal(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, exception, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Fatal(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, exception, formatProvider, message, args); } } [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(fatal, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(fatal, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(fatal, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(fatal, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(fatal, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(fatal, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, object? value) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, object? value) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { arg1, arg2 }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { arg1, arg2, arg3 }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsEnabled(level)) { ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(level, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsEnabled(level)) { CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(level, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, string message, int argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, defaultCultureInfo, message, in args); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Trace(object? value) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, object? value) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { arg1, arg2 }); WriteToTargetsWithSpan(trace, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { arg1, arg2, arg3 }); WriteToTargetsWithSpan(trace, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(trace, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(trace, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, string message, int argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(trace, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsTraceEnabled) { LogLevel trace = LogLevel.Trace; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(trace, null, defaultCultureInfo, message, in args); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Trace([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsTraceEnabled) { WriteToTargets(LogLevel.Trace, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Debug(object? value) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, object? value) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { arg1, arg2 }); WriteToTargetsWithSpan(debug, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { arg1, arg2, arg3 }); WriteToTargetsWithSpan(debug, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(debug, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(debug, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(debug, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsDebugEnabled) { LogLevel debug = LogLevel.Debug; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(debug, null, defaultCultureInfo, message, in args); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Debug([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsDebugEnabled) { WriteToTargets(LogLevel.Debug, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Info(object? value) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, object? value) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { arg1, arg2 }); WriteToTargetsWithSpan(info, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { arg1, arg2, arg3 }); WriteToTargetsWithSpan(info, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(info, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(info, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(info, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsInfoEnabled) { LogLevel info = LogLevel.Info; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(info, null, defaultCultureInfo, message, in args); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Info([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsInfoEnabled) { WriteToTargets(LogLevel.Info, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Warn(object? value) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, object? value) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { arg1, arg2 }); WriteToTargetsWithSpan(warn, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { arg1, arg2, arg3 }); WriteToTargetsWithSpan(warn, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(warn, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(warn, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(warn, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsWarnEnabled) { LogLevel warn = LogLevel.Warn; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(warn, null, defaultCultureInfo, message, in args); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Warn([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsWarnEnabled) { WriteToTargets(LogLevel.Warn, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Error(object? value) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, object? value) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { arg1, arg2 }); WriteToTargetsWithSpan(error, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { arg1, arg2, arg3 }); WriteToTargetsWithSpan(error, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(error, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(error, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(error, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsErrorEnabled) { LogLevel error = LogLevel.Error; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(error, null, defaultCultureInfo, message, in args); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Error([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsErrorEnabled) { WriteToTargets(LogLevel.Error, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Fatal(object? value) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, object? value) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, value); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { arg1, arg2 }); WriteToTargetsWithSpan(fatal, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, object? arg1, object? arg2, object? arg3) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { arg1, arg2, arg3 }); WriteToTargetsWithSpan(fatal, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, bool argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, char argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, byte argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(fatal, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, string? argument) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(fatal, null, defaultCultureInfo, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, int argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, long argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, float argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, double argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, decimal argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(fatal, null, formatProvider, message, in args); } } [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, object? argument) { if (IsFatalEnabled) { LogLevel fatal = LogLevel.Fatal; CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(fatal, null, defaultCultureInfo, message, in args); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, sbyte argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, uint argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, formatProvider, message, new object[1] { argument }); } } [CLSCompliant(false)] [EditorBrowsable(EditorBrowsableState.Never)] [MessageTemplateFormatMethod("message")] [OverloadResolutionPriority(-1)] public void Fatal([Localizable(false)][StructuredMessageTemplate] string message, ulong argument) { if (IsFatalEnabled) { WriteToTargets(LogLevel.Fatal, Factory.DefaultCultureInfo, message, new object[1] { argument }); } } void ILoggerBase.LogException(LogLevel level, [Localizable(false)] string message, Exception? exception) { Log(level, exception, message, ArrayHelper.Empty()); } void ILoggerBase.Log(LogLevel level, [Localizable(false)] string message, Exception? exception) { Log(level, exception, message, ArrayHelper.Empty()); } [Obsolete("Use Trace(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void TraceException([Localizable(false)] string message, Exception? exception) { Trace(exception, message); } void ILogger.Trace([Localizable(false)] string message, Exception? exception) { Trace(exception, message); } [Obsolete("Use Debug(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void DebugException([Localizable(false)] string message, Exception? exception) { Debug(exception, message); } void ILogger.Debug([Localizable(false)] string message, Exception? exception) { Debug(exception, message); } [Obsolete("Use Info(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void InfoException([Localizable(false)] string message, Exception? exception) { Info(exception, message); } void ILogger.Info([Localizable(false)] string message, Exception? exception) { Info(exception, message); } [Obsolete("Use Warn(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void WarnException([Localizable(false)] string message, Exception? exception) { Warn(exception, message); } void ILogger.Warn([Localizable(false)] string message, Exception? exception) { Warn(exception, message); } [Obsolete("Use Error(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void ErrorException([Localizable(false)] string message, Exception? exception) { Error(exception, message); } void ILogger.Error([Localizable(false)] string message, Exception? exception) { Error(exception, message); } [Obsolete("Use Fatal(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] public void FatalException([Localizable(false)] string message, Exception? exception) { Fatal(exception, message); } void ILogger.Fatal([Localizable(false)] string message, Exception? exception) { Fatal(exception, message); } protected internal Logger() { _contextLogger = this; Name = string.Empty; Factory = LogManager.LogFactory; } public bool IsEnabled(LogLevel level) { return GetTargetsForLevelSafe(level) != null; } public Logger WithProperty(string propertyKey, object? propertyValue) { if (string.IsNullOrEmpty(propertyKey)) { throw new ArgumentException("propertyKey"); } Logger logger = CreateChildLogger(); logger.Properties[propertyKey] = propertyValue; return logger; } public Logger WithProperties(IEnumerable> properties) { Guard.ThrowIfNull(properties, "properties"); Logger logger = CreateChildLogger(); IDictionary properties2 = logger.Properties; foreach (KeyValuePair property in properties) { properties2[property.Key] = property.Value; } return logger; } public Logger WithProperties([ParamCollection] scoped ReadOnlySpan<(string, object?)> properties) { Logger logger = CreateChildLogger(); IDictionary properties2 = logger.Properties; ReadOnlySpan<(string, object)> readOnlySpan = properties; for (int i = 0; i < readOnlySpan.Length; i++) { (string, object) tuple = readOnlySpan[i]; properties2[tuple.Item1] = tuple.Item2; } return logger; } [Obsolete("Instead use WithProperty which is safe. If really necessary then one can use Properties-property. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public void SetProperty(string propertyKey, object? propertyValue) { if (string.IsNullOrEmpty(propertyKey)) { throw new ArgumentException("propertyKey"); } Properties[propertyKey] = propertyValue; } private static ThreadSafeDictionary CreateContextPropertiesDictionary(ThreadSafeDictionary? contextProperties) { contextProperties = ((contextProperties == null) ? new ThreadSafeDictionary() : new ThreadSafeDictionary(contextProperties)); return contextProperties; } public IDisposable PushScopeProperty(string propertyName, object? propertyValue) { return ScopeContext.PushProperty(propertyName, propertyValue); } public IDisposable PushScopeProperty(string propertyName, TValue? propertyValue) { return ScopeContext.PushProperty(propertyName, propertyValue); } public IDisposable PushScopeProperties(IReadOnlyCollection> scopeProperties) { return ScopeContext.PushProperties(scopeProperties); } public IDisposable PushScopeProperties(IReadOnlyCollection> scopeProperties) { return ScopeContext.PushProperties(scopeProperties); } public IDisposable PushScopeNested(T nestedState) { return ScopeContext.PushNestedState(nestedState); } public IDisposable PushScopeNested(object nestedState) { return ScopeContext.PushNestedState(nestedState); } public void Log(LogEventInfo logEvent) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(logEvent.Level); if (targetsForLevelSafe != null) { if (logEvent.LoggerName == null || (object)logEvent.LoggerName == string.Empty) { logEvent.LoggerName = Name; } if (logEvent.FormatProvider == null) { logEvent.FormatProvider = Factory.DefaultCultureInfo; } WriteLogEventToTargets(logEvent, targetsForLevelSafe); } } public void Log(Type wrapperType, LogEventInfo logEvent) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(logEvent.Level); if (targetsForLevelSafe != null) { if (logEvent.LoggerName == null || (object)logEvent.LoggerName == string.Empty) { logEvent.LoggerName = Name; } if (logEvent.FormatProvider == null) { logEvent.FormatProvider = Factory.DefaultCultureInfo; } WriteLogEventToTargets(wrapperType, logEvent, targetsForLevelSafe); } } public void Log(LogLevel level, T? value) { if (IsEnabled(level)) { WriteToTargets(level, Factory.DefaultCultureInfo, value); } } public void Log(LogLevel level, IFormatProvider? formatProvider, T? value) { if (IsEnabled(level)) { WriteToTargets(level, formatProvider, value); } } public void Log(LogLevel level, LogMessageGenerator messageFunc) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { Guard.ThrowIfNull(messageFunc, "messageFunc"); WriteToTargets(targetsForLevelSafe, level, null, Factory.DefaultCultureInfo, messageFunc(), null); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { WriteToTargets(targetsForLevelSafe, level, null, formatProvider, message, args); } } public void Log(LogLevel level, [Localizable(false)] string message) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { WriteToTargets(targetsForLevelSafe, level, null, Factory.DefaultCultureInfo, message, null); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { WriteToTargets(targetsForLevelSafe, level, null, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { WriteToTargets(targetsForLevelSafe, level, exception, Factory.DefaultCultureInfo, message, args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { WriteToTargets(targetsForLevelSafe, level, exception, formatProvider, message, args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[1] { argument }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[2] { argument1, argument2 }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, formatProvider, message, in args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { CultureInfo? defaultCultureInfo = Factory.DefaultCultureInfo; ReadOnlySpan args = new ReadOnlySpan(new object[3] { argument1, argument2, argument3 }); WriteToTargetsWithSpan(targetsForLevelSafe, level, null, defaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { WriteToTargetsWithSpan(targetsForLevelSafe, level, null, Factory.DefaultCultureInfo, message, in args); } } [MessageTemplateFormatMethod("message")] public void Log(LogLevel level, Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { ITargetWithFilterChain targetsForLevelSafe = GetTargetsForLevelSafe(level); if (targetsForLevelSafe != null) { WriteToTargetsWithSpan(targetsForLevelSafe, level, exception, Factory.DefaultCultureInfo, message, in args); } } private void WriteToTargetsWithSpan(LogLevel level, Exception? exception, IFormatProvider? formatProvider, string message, in ReadOnlySpan args) { ITargetWithFilterChain targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { WriteToTargetsWithSpan(targetsForLevel, level, exception, formatProvider, message, in args); } } private void WriteToTargetsWithSpan(ITargetWithFilterChain targetsForLevel, LogLevel level, Exception? exception, IFormatProvider? formatProvider, string message, in ReadOnlySpan args) { if (Factory.AutoMessageTemplateFormatter == null || !LogEventInfo.NeedToPreformatMessage(in args)) { LogEventInfo logEvent = LogEventInfo.Create(level, Name, exception, formatProvider, message, args.IsEmpty ? null : args.ToArray()); WriteLogEventToTargets(logEvent, targetsForLevel); return; } TemplateEnumerator templateEnumerator = new TemplateEnumerator(message); if (templateEnumerator.MoveNext() && !templateEnumerator.Current.MaybePositionalTemplate) { LogEventInfo logEvent2 = RenderPreformattedLogEvent(Factory.AutoMessageTemplateFormatter, level, exception, formatProvider, message, in args, ref templateEnumerator); WriteLogEventToTargets(logEvent2, targetsForLevel); } else { LogEventInfo logEventInfo = LogEventInfo.Create(level, Name, exception, formatProvider, message, args.ToArray()); logEventInfo.MessageFormatter = LogMessageStringFormatter.Default.MessageFormatter; WriteLogEventToTargets(logEventInfo, targetsForLevel); } } private LogEventInfo RenderPreformattedLogEvent(LogMessageTemplateFormatter messageTemplateFormatter, LogLevel level, Exception? exception, IFormatProvider? formatProvider, string messageTemplate, in ReadOnlySpan args, ref TemplateEnumerator templateEnumerator) { string formattedMessage = messageTemplate; IList messageTemplateParameters = null; try { formattedMessage = messageTemplateFormatter.Render(ref templateEnumerator, formatProvider, in args, out messageTemplateParameters); } catch (Exception ex) { InternalLogger.Warn(ex, "Error when formatting a message."); if (ex.MustBeRethrown()) { throw; } } LogEventInfo logEventInfo = new LogEventInfo(level, Name, formattedMessage, messageTemplate, (IList?)null); if (messageTemplateParameters == null) { logEventInfo.Parameters = args.ToArray(); } else { logEventInfo.CreatePropertiesInternal(messageTemplateParameters); } logEventInfo.Exception = exception; return logEventInfo; } private LogEventInfo PrepareLogEventInfo(LogEventInfo logEvent) { if (_contextProperties != null) { foreach (KeyValuePair contextProperty in _contextProperties) { if (!logEvent.Properties.ContainsKey(contextProperty.Key)) { logEvent.Properties[contextProperty.Key] = contextProperty.Value; } } } return logEvent; } public void Swallow(Action action) { try { action(); } catch (Exception value) { Error(value); } } public T? Swallow(Func func) { return Swallow(func, default(T)); } public T? Swallow(Func func, T? fallback) { try { return func(); } catch (Exception value) { Error(value); return fallback; } } public async void Swallow(Task task) { try { await task.ConfigureAwait(continueOnCapturedContext: false); } catch (Exception value) { Error(value); } } public async Task SwallowAsync(Task task) { try { await task.ConfigureAwait(continueOnCapturedContext: false); } catch (Exception value) { Error(value); } } public async Task SwallowAsync(Func asyncAction) { try { await asyncAction().ConfigureAwait(continueOnCapturedContext: false); } catch (Exception value) { Error(value); } } public async Task SwallowAsync(Func> asyncFunc) { return await SwallowAsync(asyncFunc, default(TResult)).ConfigureAwait(continueOnCapturedContext: false); } public async Task SwallowAsync(Func> asyncFunc, TResult? fallback) { try { return await asyncFunc().ConfigureAwait(continueOnCapturedContext: false); } catch (Exception value) { Error(value); return fallback; } } internal void Initialize(string name, ITargetWithFilterChain[] targetsByLevel, LogFactory factory) { Name = name; Factory = factory; SetConfiguration(targetsByLevel); } private void WriteToTargets(ITargetWithFilterChain targetsForLevel, LogLevel level, Exception? exception, IFormatProvider? formatProvider, string message, object?[]? args) { LogEventInfo logEvent = LogEventInfo.Create(level, Name, exception, formatProvider, message, args); WriteLogEventToTargets(logEvent, targetsForLevel); } private void WriteToTargets(LogLevel level, IFormatProvider? formatProvider, string message, object?[] args) { ITargetWithFilterChain targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { LogEventInfo logEvent = LogEventInfo.Create(level, Name, formatProvider, message, args); WriteLogEventToTargets(logEvent, targetsForLevel); } } private void WriteToTargets(LogLevel level, string message) { ITargetWithFilterChain targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { LogEventInfo logEvent = LogEventInfo.Create(level, Name, Factory.DefaultCultureInfo, message, null); WriteLogEventToTargets(logEvent, targetsForLevel); } } private void WriteToTargets(LogLevel level, IFormatProvider? formatProvider, T? value) { ITargetWithFilterChain targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { LogEventInfo logEvent = LogEventInfo.Create(level, Name, formatProvider, value); WriteLogEventToTargets(logEvent, targetsForLevel); } } private void WriteToTargets(LogLevel level, Exception? ex, IFormatProvider? formatProvider, string message, object?[]? args) { ITargetWithFilterChain targetsForLevel = GetTargetsForLevel(level); if (targetsForLevel != null) { LogEventInfo logEvent = LogEventInfo.Create(level, Name, ex, formatProvider, message, args); WriteLogEventToTargets(logEvent, targetsForLevel); } } private void WriteLogEventToTargets(LogEventInfo logEvent, ITargetWithFilterChain targetsForLevel) { try { targetsForLevel.WriteToLoggerTargets(DefaultLoggerType, PrepareLogEventInfo(logEvent), Factory); } catch (Exception ex) { if (Factory.ThrowExceptions || LogManager.ThrowExceptions) { throw; } InternalLogger.Error(ex, "Failed to write LogEvent"); } } private void WriteLogEventToTargets(Type wrapperType, LogEventInfo logEvent, ITargetWithFilterChain targetsForLevel) { try { targetsForLevel.WriteToLoggerTargets(wrapperType ?? DefaultLoggerType, PrepareLogEventInfo(logEvent), Factory); } catch (Exception ex) { if (Factory.ThrowExceptions || LogManager.ThrowExceptions) { throw; } InternalLogger.Error(ex, "Failed to write LogEvent"); } } internal void SetConfiguration(ITargetWithFilterChain[] targetsByLevel) { _targetsByLevel = targetsByLevel; _isTraceEnabled = IsEnabled(LogLevel.Trace); _isDebugEnabled = IsEnabled(LogLevel.Debug); _isInfoEnabled = IsEnabled(LogLevel.Info); _isWarnEnabled = IsEnabled(LogLevel.Warn); _isErrorEnabled = IsEnabled(LogLevel.Error); _isFatalEnabled = IsEnabled(LogLevel.Fatal); OnLoggerReconfigured(EventArgs.Empty); } private ITargetWithFilterChain GetTargetsForLevelSafe(LogLevel? level) { if ((object)level == null) { throw new InvalidOperationException("Log level must be defined"); } return GetTargetsForLevel(level); } private ITargetWithFilterChain GetTargetsForLevel(LogLevel level) { if (_contextLogger == this) { return _targetsByLevel[level.Ordinal]; } return _contextLogger.GetTargetsForLevel(level); } protected virtual void OnLoggerReconfigured(EventArgs e) { this.LoggerReconfigured?.Invoke(this, e); } private Logger CreateChildLogger() { Logger obj = (Logger)MemberwiseClone(); obj.Initialize(Name, _targetsByLevel, Factory); obj._contextProperties = CreateContextPropertiesDictionary(_contextProperties); obj._contextLogger = _contextLogger; return obj; } } internal static class LoggerImpl { private const int StackTraceSkipMethods = 0; internal static void Write(Type loggerType, TargetWithFilterChain targetsForLevel, LogEventInfo logEvent, LogFactory logFactory) { logEvent.SetMessageFormatter(logFactory.ActiveMessageFormatter, (targetsForLevel.NextInChain == null) ? logFactory.SingleTargetMessageFormatter : null); if (targetsForLevel.StackTraceUsage != 0) { CaptureCallSiteInfo(loggerType, targetsForLevel, logEvent, logFactory); } AsyncContinuation asyncContinuation = SingleCallContinuation.Completed; if (logFactory.ThrowExceptions) { int originalThreadId = AsyncHelpers.GetManagedThreadId(); asyncContinuation = delegate(Exception? ex) { if (ex != null && AsyncHelpers.GetManagedThreadId() == originalThreadId) { throw new NLogRuntimeException("Exception occurred in NLog", ex); } }; } IList list = ArrayHelper.Empty(); FilterResult filterResult = FilterResult.Neutral; for (TargetWithFilterChain targetWithFilterChain = targetsForLevel; targetWithFilterChain != null; targetWithFilterChain = targetWithFilterChain.NextInChain) { IList filterChain = targetWithFilterChain.FilterChain; FilterResult filterResult2 = ((list == filterChain) ? filterResult : GetFilterResult(filterChain, logEvent, targetWithFilterChain.FilterDefaultAction)); if (filterResult2 != FilterResult.Ignore && filterResult2 != FilterResult.IgnoreFinal) { targetWithFilterChain.Target.WriteAsyncLogEvent(logEvent.WithContinuation(asyncContinuation)); if (filterResult2 == FilterResult.LogFinal) { break; } } else { InternalLogger.Debug("{0} [{1}] Rejecting message because of a filter.", logEvent.LoggerName, logEvent.Level); if (filterResult2 == FilterResult.IgnoreFinal) { break; } } filterResult = filterResult2; list = filterChain; } } private static void CaptureCallSiteInfo(Type loggerType, TargetWithFilterChain targetsForLevel, LogEventInfo logEvent, LogFactory logFactory) { StackTraceUsage stackTraceUsage = targetsForLevel.StackTraceUsage; bool flag = TryCallSiteClassNameOptimization(stackTraceUsage, logEvent); if (flag && targetsForLevel.TryLookupCallSiteClassName(logEvent, out string callSiteClassName)) { logEvent.GetCallSiteInformationInternal().CallerClassName = callSiteClassName; } else { if (!flag && !MustCaptureStackTrace(stackTraceUsage, logEvent)) { return; } try { bool fNeedFileInfo = (stackTraceUsage & StackTraceUsage.WithFileNameAndLineNumber) != 0; StackTrace stackTrace = new StackTrace(0, fNeedFileInfo); logEvent.GetCallSiteInformationInternal().SetStackTrace(stackTrace, null, loggerType); } catch (Exception ex) { if (logFactory.ThrowExceptions || LogManager.ThrowExceptions) { throw; } InternalLogger.Warn(ex, "{0} Failed to capture CallSite. Platform might not support ${{callsite}}", new ReadOnlySpan(new object[1] { logEvent.LoggerName })); } if (flag) { targetsForLevel.TryRememberCallSiteClassName(logEvent); } } } internal static bool TryCallSiteClassNameOptimization(StackTraceUsage stackTraceUsage, LogEventInfo logEvent) { if ((stackTraceUsage & (StackTraceUsage.WithStackTrace | StackTraceUsage.WithCallSiteClassName)) != StackTraceUsage.WithCallSiteClassName) { return false; } if (string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath)) { return false; } if (logEvent.HasStackTrace) { return false; } return true; } internal static bool MustCaptureStackTrace(StackTraceUsage stackTraceUsage, LogEventInfo logEvent) { if (logEvent.HasStackTrace) { return false; } if ((stackTraceUsage & StackTraceUsage.WithStackTrace) != 0) { return true; } if ((stackTraceUsage & StackTraceUsage.WithCallSite) != 0 && string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerMethodName) && string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath)) { return true; } return false; } private static FilterResult GetFilterResult(IList filterChain, LogEventInfo logEvent, FilterResult filterDefaultAction) { if (filterChain.Count == 0) { return FilterResult.Neutral; } try { for (int i = 0; i < filterChain.Count; i++) { FilterResult filterResult = filterChain[i].GetFilterResult(logEvent); if (filterResult != 0) { return filterResult; } } return filterDefaultAction; } catch (Exception ex) { InternalLogger.Warn(ex, "Exception during filter evaluation. Message will be ignore."); if (ex.MustBeRethrown()) { throw; } return FilterResult.Ignore; } } } [TypeConverter(typeof(LogLevelTypeConverter))] public sealed class LogLevel : IComparable, IComparable, IEquatable, IFormattable { public static readonly LogLevel Trace = new LogLevel("Trace", 0); public static readonly LogLevel Debug = new LogLevel("Debug", 1); public static readonly LogLevel Info = new LogLevel("Info", 2); public static readonly LogLevel Warn = new LogLevel("Warn", 3); public static readonly LogLevel Error = new LogLevel("Error", 4); public static readonly LogLevel Fatal = new LogLevel("Fatal", 5); public static readonly LogLevel Off = new LogLevel("Off", 6); private static readonly IList allLevels = new List { Trace, Debug, Info, Warn, Error, Fatal, Off }.AsReadOnly(); private static readonly IList allLoggingLevels = new List { Trace, Debug, Info, Warn, Error, Fatal }.AsReadOnly(); private readonly int _ordinal; private readonly string _name; public static IEnumerable AllLevels => allLevels; public static IEnumerable AllLoggingLevels => allLoggingLevels; internal static LogLevel MaxLevel => Fatal; internal static LogLevel MinLevel => Trace; public string Name => _name; public int Ordinal => _ordinal; private LogLevel(string name, int ordinal) { _name = name; _ordinal = ordinal; } public static bool operator ==(LogLevel? level1, LogLevel? level2) { if ((object)level1 == level2) { return true; } return (level1 ?? Off).Equals(level2); } public static bool operator !=(LogLevel? level1, LogLevel? level2) { if ((object)level1 == level2) { return false; } return !(level1 ?? Off).Equals(level2); } public static bool operator >(LogLevel? level1, LogLevel? level2) { if ((object)level1 == level2) { return false; } return (level1 ?? Off).CompareTo(level2) > 0; } public static bool operator >=(LogLevel? level1, LogLevel? level2) { if ((object)level1 == level2) { return true; } return (level1 ?? Off).CompareTo(level2) >= 0; } public static bool operator <(LogLevel? level1, LogLevel? level2) { if ((object)level1 == level2) { return false; } return (level1 ?? Off).CompareTo(level2) < 0; } public static bool operator <=(LogLevel? level1, LogLevel? level2) { if ((object)level1 == level2) { return true; } return (level1 ?? Off).CompareTo(level2) <= 0; } public static LogLevel FromOrdinal(int ordinal) { return ordinal switch { 0 => Trace, 1 => Debug, 2 => Info, 3 => Warn, 4 => Error, 5 => Fatal, 6 => Off, _ => throw new ArgumentException($"Unknown loglevel: {ordinal}.", "ordinal"), }; } public static LogLevel FromString(string levelName) { Guard.ThrowIfNull(levelName, "levelName"); if (levelName.Equals("Trace", StringComparison.OrdinalIgnoreCase)) { return Trace; } if (levelName.Equals("Debug", StringComparison.OrdinalIgnoreCase)) { return Debug; } if (levelName.Equals("Info", StringComparison.OrdinalIgnoreCase)) { return Info; } if (levelName.Equals("Warn", StringComparison.OrdinalIgnoreCase)) { return Warn; } if (levelName.Equals("Error", StringComparison.OrdinalIgnoreCase)) { return Error; } if (levelName.Equals("Fatal", StringComparison.OrdinalIgnoreCase)) { return Fatal; } if (levelName.Equals("Off", StringComparison.OrdinalIgnoreCase)) { return Off; } if (levelName.Equals("None", StringComparison.OrdinalIgnoreCase)) { return Off; } if (levelName.Equals("Information", StringComparison.OrdinalIgnoreCase)) { return Info; } if (levelName.Equals("Warning", StringComparison.OrdinalIgnoreCase)) { return Warn; } throw new ArgumentException("Unknown log level: " + levelName, "levelName"); } public override string ToString() { return _name; } string IFormattable.ToString(string? format, IFormatProvider? formatProvider) { if (format == null || !"D".Equals(format, StringComparison.OrdinalIgnoreCase)) { return _name; } return _ordinal.ToString(CultureInfo.InvariantCulture); } public override int GetHashCode() { return _ordinal; } public override bool Equals(object? obj) { return Equals(obj as LogLevel); } public bool Equals(LogLevel? other) { return _ordinal == other?._ordinal; } public int CompareTo(object? obj) { return CompareTo(obj as LogLevel); } public int CompareTo(LogLevel? other) { return _ordinal - (other ?? Off)._ordinal; } } public static class LogManager { private static LogFactory? _logFactory; public static LogFactory LogFactory => _logFactory ?? CreateLogFactorySingleton(); public static bool ThrowExceptions { get { return LogFactory.ThrowExceptions; } set { LogFactory.ThrowExceptions = value; } } public static bool? ThrowConfigExceptions { get { return LogFactory.ThrowConfigExceptions; } set { LogFactory.ThrowConfigExceptions = value; } } public static bool KeepVariablesOnReload { get { return LogFactory.KeepVariablesOnReload; } set { LogFactory.KeepVariablesOnReload = value; } } public static bool AutoShutdown { get { return LogFactory.AutoShutdown; } set { LogFactory.AutoShutdown = value; } } [CanBeNull] public static LoggingConfiguration? Configuration { get { return LogFactory.Configuration; } set { LogFactory.Configuration = value; } } public static LogLevel GlobalThreshold { get { return LogFactory.GlobalThreshold; } set { LogFactory.GlobalThreshold = value; } } public static event EventHandler ConfigurationChanged { add { LogFactory.ConfigurationChanged += value; } remove { LogFactory.ConfigurationChanged -= value; } } private static LogFactory CreateLogFactorySingleton() { LogFactory logFactory = new LogFactory(); if (Interlocked.CompareExchange(ref _logFactory, logFactory, null) != null) { logFactory.Dispose(); } return _logFactory; } public static ISetupBuilder Setup() { return LogFactory.Setup(); } public static LogFactory Setup(Action setupBuilder) { return LogFactory.Setup(setupBuilder); } [Obsolete("Replaced by LogManager.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static LogFactory LoadConfiguration(string configFile) { return LogFactory.LoadConfiguration(configFile); } [Obsolete("Replaced by LogManager.Setup().SetupLogFactory(setup => setup.AddCallSiteHiddenAssembly(assembly)). Marked obsolete on NLog 5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void AddHiddenAssembly(Assembly assembly) { CallSiteInformation.AddCallSiteHiddenAssembly(assembly); } [MethodImpl(MethodImplOptions.NoInlining)] [CLSCompliant(false)] public static Logger GetCurrentClassLogger() { string classFullName = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, needFileInfo: false)); return LogFactory.GetLogger(classFullName); } [MethodImpl(MethodImplOptions.NoInlining)] [CLSCompliant(false)] [Obsolete("Replaced by LogFactory.GetCurrentClassLogger(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static Logger GetCurrentClassLogger([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type loggerType) { string classFullName = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, needFileInfo: false)); return LogFactory.GetLogger(classFullName, loggerType); } public static Logger CreateNullLogger() { return LogFactory.CreateNullLogger(); } public static Logger GetLogger(string name) { return LogFactory.GetLogger(name); } [Obsolete("Replaced by LogFactory.GetLogger(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static Logger GetLogger(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type loggerType) { return LogFactory.GetLogger(name, loggerType); } public static void ReconfigExistingLoggers() { LogFactory.ReconfigExistingLoggers(); } public static void ReconfigExistingLoggers(bool purgeObsoleteLoggers) { LogFactory.ReconfigExistingLoggers(purgeObsoleteLoggers); } public static void Flush() { LogFactory.Flush(); } public static void Flush(TimeSpan timeout) { LogFactory.Flush(timeout); } public static void Flush(int timeoutMilliseconds) { LogFactory.Flush(timeoutMilliseconds); } public static void Flush(AsyncContinuation asyncContinuation) { LogFactory.Flush(asyncContinuation); } public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout) { LogFactory.Flush(asyncContinuation, timeout); } public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds) { LogFactory.Flush(asyncContinuation, timeoutMilliseconds); } [Obsolete("Use SuspendLogging() instead. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static IDisposable DisableLogging() { return LogFactory.SuspendLogging(); } [Obsolete("Use ResumeLogging() instead. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static void EnableLogging() { LogFactory.ResumeLogging(); } public static IDisposable SuspendLogging() { return LogFactory.SuspendLogging(); } public static void ResumeLogging() { LogFactory.ResumeLogging(); } public static bool IsLoggingEnabled() { return LogFactory.IsLoggingEnabled(); } public static void Shutdown() { LogFactory.Shutdown(); } } public delegate string? LogMessageFormatter(LogEventInfo logEvent); public delegate string LogMessageGenerator(); [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static class MappedDiagnosticsContext { [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static IDisposable SetScoped(string item, string? value) { Guard.ThrowIfNull(item, "item"); return ScopeContext.PushProperty(item, value); } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static IDisposable SetScoped(string item, object? value) { Guard.ThrowIfNull(item, "item"); return ScopeContext.PushProperty(item, value); } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static void Set(string item, string? value) { Guard.ThrowIfNull(item, "item"); ScopeContext.SetMappedContextLegacy(item, value); } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static void Set(string item, object? value) { Guard.ThrowIfNull(item, "item"); ScopeContext.SetMappedContextLegacy(item, value); } [Obsolete("Replaced by ScopeContext.TryGetProperty. Marked obsolete on NLog 5.0")] public static string Get(string item) { Guard.ThrowIfNull(item, "item"); return Get(item, null); } [Obsolete("Replaced by ScopeContext.TryGetProperty. Marked obsolete on NLog 5.0")] public static string Get(string item, IFormatProvider? formatProvider) { return FormatHelper.ConvertToString(GetObject(item), formatProvider); } [Obsolete("Replaced by ScopeContext.TryGetProperty. Marked obsolete on NLog 5.0")] public static object? GetObject(string item) { Guard.ThrowIfNull(item, "item"); if (ScopeContext.TryGetProperty(item, out object value)) { return value; } return null; } [Obsolete("Replaced by ScopeContext.GetAllProperties. Marked obsolete on NLog 5.0")] public static ICollection GetNames() { return ScopeContext.GetKeysMappedContextLegacy(); } [Obsolete("Replaced by ScopeContext.TryGetProperty. Marked obsolete on NLog 5.0")] public static bool Contains(string item) { Guard.ThrowIfNull(item, "item"); object value; return ScopeContext.TryGetProperty(item, out value); } [Obsolete("Replaced by dispose of return value from ScopeContext.PushProperty. Marked obsolete on NLog 5.0")] public static void Remove(string item) { Guard.ThrowIfNull(item, "item"); ScopeContext.RemoveMappedContextLegacy(item); } [Obsolete("Replaced by ScopeContext.Clear(). Marked obsolete on NLog 5.0")] public static void Clear() { ScopeContext.ClearMappedContextLegacy(); } } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static class MappedDiagnosticsLogicalContext { [Obsolete("Replaced by ScopeContext.TryGetProperty. Marked obsolete on NLog 5.0")] public static string Get(string item) { return Get(item, null); } [Obsolete("Replaced by ScopeContext.TryGetProperty. Marked obsolete on NLog 5.0")] public static string Get(string item, IFormatProvider? formatProvider) { return FormatHelper.ConvertToString(GetObject(item), formatProvider); } [Obsolete("Replaced by ScopeContext.TryGetProperty. Marked obsolete on NLog 5.0")] public static object? GetObject(string item) { Guard.ThrowIfNull(item, "item"); if (ScopeContext.TryGetProperty(item, out object value)) { return value; } return null; } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static IDisposable SetScoped(string item, string? value) { Guard.ThrowIfNull(item, "item"); return MappedDiagnosticsLogicalContext.SetScoped(item, value); } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static IDisposable SetScoped(string item, object? value) { Guard.ThrowIfNull(item, "item"); return MappedDiagnosticsLogicalContext.SetScoped(item, value); } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static IDisposable SetScoped(string item, T? value) { Guard.ThrowIfNull(item, "item"); return ScopeContext.PushProperty(item, value); } [Obsolete("Replaced by ScopeContext.PushProperties or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static IDisposable SetScoped(IReadOnlyList> items) { return ScopeContext.PushProperties(items); } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static void Set(string item, string? value) { MappedDiagnosticsLogicalContext.Set(item, value); } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static void Set(string item, object? value) { MappedDiagnosticsLogicalContext.Set(item, value); } [Obsolete("Replaced by ScopeContext.PushProperty or Logger.PushScopeProperty using ${scopeproperty}. Marked obsolete on NLog 5.0")] public static void Set(string item, T? value) { Guard.ThrowIfNull(item, "item"); ScopeContext.SetMappedContextLegacy(item, value); } [Obsolete("Replaced by ScopeContext.GetAllProperties. Marked obsolete on NLog 5.0")] public static ICollection GetNames() { return ScopeContext.GetKeysMappedContextLegacy(); } [Obsolete("Replaced by ScopeContext.TryGetProperty. Marked obsolete on NLog 5.0")] public static bool Contains(string item) { Guard.ThrowIfNull(item, "item"); object value; return ScopeContext.TryGetProperty(item, out value); } [Obsolete("Replaced by dispose of return value from ScopeContext.PushProperty. Marked obsolete on NLog 5.0")] public static void Remove(string item) { Guard.ThrowIfNull(item, "item"); ScopeContext.RemoveMappedContextLegacy(item); } [Obsolete("Replaced by ScopeContext.Clear(). Marked obsolete on NLog 5.0")] public static void Clear() { Clear(free: true); } [Obsolete("Replaced by ScopeContext.Clear(). Marked obsolete on NLog 5.0")] public static void Clear(bool free) { ScopeContext.ClearMappedContextLegacy(); } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class MessageTemplateFormatMethodAttribute : Attribute { public string ParameterName { get; } public MessageTemplateFormatMethodAttribute(string parameterName) { ParameterName = parameterName; } } [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static class NestedDiagnosticsContext { [Obsolete("Replaced by ScopeContext.PeekNestedState. Marked obsolete on NLog 5.0")] public static string TopMessage => FormatHelper.ConvertToString(TopObject, null); [Obsolete("Replaced by ScopeContext.PeekNestedState. Marked obsolete on NLog 5.0")] public static object? TopObject => PeekObject(); [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static IDisposable Push(string text) { return ScopeContext.PushNestedState(text); } [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static IDisposable Push(object value) { return ScopeContext.PushNestedState(value); } [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static string Pop() { return Pop(null); } [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static string Pop(IFormatProvider? formatProvider) { return FormatHelper.ConvertToString(PopObject() ?? string.Empty, formatProvider); } [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static object? PopObject() { return ScopeContext.PopNestedContextLegacy(); } [Obsolete("Replaced by ScopeContext.PeekNestedState. Marked obsolete on NLog 5.0")] public static object? PeekObject() { return ScopeContext.PeekNestedState(); } [Obsolete("Replaced by ScopeContext.Clear. Marked obsolete on NLog 5.0")] public static void Clear() { ScopeContext.ClearNestedContextLegacy(); } [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static string[] GetAllMessages() { return GetAllMessages(null); } [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static string[] GetAllMessages(IFormatProvider? formatProvider) { IFormatProvider formatProvider2 = formatProvider; object[] allObjects = GetAllObjects(); if (allObjects.Length == 0) { return ArrayHelper.Empty(); } return allObjects.Select((object o) => FormatHelper.ConvertToString(o, formatProvider2)).ToArray(); } [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static object[] GetAllObjects() { return ScopeContext.GetAllNestedStates(); } } [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static class NestedDiagnosticsLogicalContext { [Obsolete("Required to be compatible with legacy NLog versions, when using remoting. Marked obsolete on NLog 5.0")] private interface INestedContext : IDisposable { INestedContext Parent { get; } int FrameLevel { get; } object? Value { get; } long CreatedTimeUtcTicks { get; } } [Obsolete("Required to be compatible with legacy NLog versions, when using remoting. Marked obsolete on NLog 5.0")] private sealed class NestedContext : INestedContext, IDisposable { private int _disposed; public INestedContext Parent { get; } public T Value { get; } public long CreatedTimeUtcTicks { get; } public int FrameLevel { get; } object? INestedContext.Value => Value; public NestedContext(INestedContext parent, T value) { Parent = parent; Value = value; CreatedTimeUtcTicks = DateTime.UtcNow.Ticks; FrameLevel = ((parent == null) ? 1 : (parent.FrameLevel + 1)); } void IDisposable.Dispose() { if (Interlocked.Exchange(ref _disposed, 1) != 1) { PopObject(); } } public override string ToString() { return ((object)Value)?.ToString() ?? "null"; } } [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static IDisposable Push(T value) { return ScopeContext.PushNestedState(value); } [Obsolete("Replaced by ScopeContext.PushNestedState or Logger.PushScopeNested using ${scopenested}. Marked obsolete on NLog 5.0")] public static IDisposable PushObject(object value) { return Push(value); } [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static object? Pop() { return PopObject(); } [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static string Pop(IFormatProvider formatProvider) { return FormatHelper.ConvertToString(PopObject() ?? string.Empty, formatProvider); } [Obsolete("Replaced by dispose of return value from ScopeContext.PushNestedState or Logger.PushScopeNested. Marked obsolete on NLog 5.0")] public static object? PopObject() { return ScopeContext.PopNestedContextLegacy(); } [Obsolete("Replaced by ScopeContext.PeekNestedState. Marked obsolete on NLog 5.0")] public static object? PeekObject() { return ScopeContext.PeekNestedState(); } [Obsolete("Replaced by ScopeContext.Clear. Marked obsolete on NLog 5.0")] public static void Clear() { ScopeContext.ClearNestedContextLegacy(); } [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static string[] GetAllMessages() { return GetAllMessages(null); } [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static string[] GetAllMessages(IFormatProvider? formatProvider) { IFormatProvider formatProvider2 = formatProvider; return (from o in GetAllObjects() select FormatHelper.ConvertToString(o, formatProvider2)).ToArray(); } [Obsolete("Replaced by ScopeContext.GetAllNestedStates. Marked obsolete on NLog 5.0")] public static object[] GetAllObjects() { return ScopeContext.GetAllNestedStates(); } } public class NLogConfigurationException : Exception { public NLogConfigurationException() { } public NLogConfigurationException(string message) : base(message) { } [Obsolete("Instead use string interpolation. Marked obsolete with NLog 5.0")] [StringFormatMethod("message")] [EditorBrowsable(EditorBrowsableState.Never)] public NLogConfigurationException(string message, params object?[] messageParameters) : base(string.Format(message, messageParameters)) { } [Obsolete("Instead use string interpolation. Marked obsolete with NLog 5.0")] [StringFormatMethod("message")] [EditorBrowsable(EditorBrowsableState.Never)] public NLogConfigurationException(Exception? innerException, string message, params object?[] messageParameters) : base(string.Format(message, messageParameters), innerException) { } public NLogConfigurationException(string message, Exception? innerException) : base(message, innerException) { } } public class NLogRuntimeException : Exception { public NLogRuntimeException() { } public NLogRuntimeException(string message) : base(message) { } [Obsolete("Instead use string interpolation. Marked obsolete with NLog 5.0")] [StringFormatMethod("message")] [EditorBrowsable(EditorBrowsableState.Never)] public NLogRuntimeException(string message, params object?[] messageParameters) : base(string.Format(message, messageParameters)) { } public NLogRuntimeException(string message, Exception? innerException) : base(message, innerException) { } } public sealed class NullLogger : Logger { public NullLogger(LogFactory factory) { Guard.ThrowIfNull(factory, "factory"); string empty = string.Empty; ITargetWithFilterChain[] noTargetsByLevel = TargetWithFilterChain.NoTargetsByLevel; Initialize(empty, noTargetsByLevel, factory); } } public static class ScopeContext { private sealed class ScopeContextPropertiesCollapsed : IDisposable { private readonly IScopeContextAsyncState? _parent; private readonly IScopeContextPropertiesAsyncState _collapsed; private bool _disposed; public ScopeContextPropertiesCollapsed(IScopeContextAsyncState? parent, IScopeContextPropertiesAsyncState collapsed) { _parent = parent; _collapsed = collapsed; } public static Dictionary? BuildCollapsedDictionary(IScopeContextAsyncState? parent, int initialCapacity) { if (parent is IScopeContextPropertiesAsyncState scopeContextPropertiesAsyncState && scopeContextPropertiesAsyncState.Parent is IScopeContextPropertiesAsyncState scopeContextPropertiesAsyncState2 && scopeContextPropertiesAsyncState.NestedState == null && scopeContextPropertiesAsyncState2.NestedState == null) { List> list = new List>(); IReadOnlyCollection> readOnlyCollection = new ScopeContextPropertyCollector(list).StartCaptureProperties(parent); if (list.Count > 0 && readOnlyCollection is Dictionary result) { return result; } Dictionary dictionary = new Dictionary(readOnlyCollection.Count + initialCapacity, DefaultComparer); ScopeContextPropertyEnumerator.CopyScopePropertiesToDictionary(readOnlyCollection, dictionary); return dictionary; } return null; } public void Dispose() { if (!_disposed) { _disposed = true; SetAsyncLocalContext(_parent); } } public override string ToString() { return _collapsed.ToString() ?? GetType().ToString(); } } internal static readonly IEqualityComparer DefaultComparer = StringComparer.OrdinalIgnoreCase; private static readonly AsyncLocal AsyncNestedDiagnosticsContext = new AsyncLocal(); public static IDisposable PushNestedStateProperties(object? nestedState, IReadOnlyCollection>? properties) { properties = (IReadOnlyCollection>?)(((object)properties) ?? ((object)ArrayHelper.Empty>())); if (properties.Count > 0 || nestedState == null) { IScopeContextAsyncState asyncLocalContext = GetAsyncLocalContext(); if (nestedState == null) { Dictionary dictionary = ScopeContextPropertiesCollapsed.BuildCollapsedDictionary(asyncLocalContext, properties.Count); if (dictionary != null) { ScopeContextPropertyEnumerator.CopyScopePropertiesToDictionary(properties, dictionary); ScopeContextPropertiesAsyncState scopeContextPropertiesAsyncState = new ScopeContextPropertiesAsyncState(asyncLocalContext?.Parent?.Parent, dictionary, nestedState); SetAsyncLocalContext(scopeContextPropertiesAsyncState); return new ScopeContextPropertiesCollapsed(asyncLocalContext, scopeContextPropertiesAsyncState); } } ScopeContextPropertiesAsyncState scopeContextPropertiesAsyncState2 = new ScopeContextPropertiesAsyncState(asyncLocalContext, properties, nestedState); SetAsyncLocalContext(scopeContextPropertiesAsyncState2); return scopeContextPropertiesAsyncState2; } return PushNestedState(nestedState); } public static IDisposable PushProperties(IReadOnlyCollection> properties) { return ScopeContext.PushProperties(properties); } public static IDisposable PushProperties(IReadOnlyCollection> properties) { IScopeContextAsyncState asyncLocalContext = GetAsyncLocalContext(); Dictionary dictionary = ScopeContextPropertiesCollapsed.BuildCollapsedDictionary(asyncLocalContext, properties.Count); if (dictionary != null) { ScopeContextPropertyEnumerator.CopyScopePropertiesToDictionary(properties, dictionary); ScopeContextPropertiesAsyncState scopeContextPropertiesAsyncState = new ScopeContextPropertiesAsyncState(asyncLocalContext?.Parent?.Parent, dictionary); SetAsyncLocalContext(scopeContextPropertiesAsyncState); return new ScopeContextPropertiesCollapsed(asyncLocalContext, scopeContextPropertiesAsyncState); } ScopeContextPropertiesAsyncState scopeContextPropertiesAsyncState2 = new ScopeContextPropertiesAsyncState(asyncLocalContext, properties); SetAsyncLocalContext(scopeContextPropertiesAsyncState2); return scopeContextPropertiesAsyncState2; } public static IDisposable PushProperty(string key, TValue? value) { Guard.ThrowIfNull(key, "key"); IScopeContextAsyncState asyncLocalContext = GetAsyncLocalContext(); Dictionary dictionary = ScopeContextPropertiesCollapsed.BuildCollapsedDictionary(asyncLocalContext, 1); if (dictionary != null) { dictionary[key] = value; ScopeContextPropertiesAsyncState scopeContextPropertiesAsyncState = new ScopeContextPropertiesAsyncState(asyncLocalContext?.Parent?.Parent, dictionary); SetAsyncLocalContext(scopeContextPropertiesAsyncState); return new ScopeContextPropertiesCollapsed(asyncLocalContext, scopeContextPropertiesAsyncState); } ScopeContextPropertyAsyncState scopeContextPropertyAsyncState = new ScopeContextPropertyAsyncState(asyncLocalContext, key, value); SetAsyncLocalContext(scopeContextPropertyAsyncState); return scopeContextPropertyAsyncState; } public static IDisposable PushProperty(string key, object? value) { return ScopeContext.PushProperty(key, value); } public static IDisposable PushNestedState(T nestedState) { ScopedContextNestedAsyncState scopedContextNestedAsyncState = new ScopedContextNestedAsyncState(GetAsyncLocalContext(), nestedState); SetAsyncLocalContext(scopedContextNestedAsyncState); return scopedContextNestedAsyncState; } public static IDisposable PushNestedState(object nestedState) { return ScopeContext.PushNestedState(nestedState); } public static void Clear() { SetAsyncLocalContext(null); } public static IEnumerable> GetAllProperties() { IScopeContextAsyncState? asyncLocalContext = GetAsyncLocalContext(); ScopeContextPropertyCollector contextCollector = default(ScopeContextPropertyCollector); return (IEnumerable>)(((object)asyncLocalContext?.CaptureContextProperties(ref contextCollector)) ?? ((object)ArrayHelper.Empty>())); } internal static ScopeContextPropertyEnumerator GetAllPropertiesEnumerator() { return new ScopeContextPropertyEnumerator(GetAllProperties()); } public static bool TryGetProperty(string key, out object? value) { IScopeContextAsyncState asyncLocalContext = GetAsyncLocalContext(); if (asyncLocalContext != null) { ScopeContextPropertyCollector contextCollector = default(ScopeContextPropertyCollector); IReadOnlyCollection> readOnlyCollection = asyncLocalContext.CaptureContextProperties(ref contextCollector); if (readOnlyCollection != null && readOnlyCollection.Count > 0) { return TryLookupProperty(readOnlyCollection, key, out value); } } value = null; return false; } public static object[] GetAllNestedStates() { IList allNestedStateList = GetAllNestedStateList(); if (allNestedStateList != null && allNestedStateList.Count > 0) { if (allNestedStateList is object[] result) { return result; } return allNestedStateList.ToArray(); } return ArrayHelper.Empty(); } internal static IList GetAllNestedStateList() { IScopeContextAsyncState? asyncLocalContext = GetAsyncLocalContext(); ScopeContextNestedStateCollector contextCollector = default(ScopeContextNestedStateCollector); return asyncLocalContext?.CaptureNestedContext(ref contextCollector) ?? ArrayHelper.Empty(); } public static object? PeekNestedState() { for (IScopeContextAsyncState scopeContextAsyncState = GetAsyncLocalContext(); scopeContextAsyncState != null; scopeContextAsyncState = scopeContextAsyncState.Parent) { object nestedState = scopeContextAsyncState.NestedState; if (nestedState != null) { return nestedState; } } return null; } internal static TimeSpan? PeekInnerNestedDuration() { long nestedContextTimestampNow = GetNestedContextTimestampNow(); for (IScopeContextAsyncState scopeContextAsyncState = GetAsyncLocalContext(); scopeContextAsyncState != null; scopeContextAsyncState = scopeContextAsyncState.Parent) { long nestedStateTimestamp = scopeContextAsyncState.NestedStateTimestamp; if (nestedStateTimestamp != 0L) { return GetNestedStateDuration(nestedStateTimestamp, nestedContextTimestampNow); } } return null; } internal static TimeSpan? PeekOuterNestedDuration() { long nestedContextTimestampNow = GetNestedContextTimestampNow(); IScopeContextAsyncState scopeContextAsyncState = GetAsyncLocalContext(); long num = 0L; while (scopeContextAsyncState != null) { if (scopeContextAsyncState.NestedStateTimestamp != 0L) { num = scopeContextAsyncState.NestedStateTimestamp; } scopeContextAsyncState = scopeContextAsyncState.Parent; } if (num != 0L) { return GetNestedStateDuration(num, nestedContextTimestampNow); } return null; } private static bool TryLookupProperty(IReadOnlyCollection> scopeProperties, string key, out object? value) { if (scopeProperties is Dictionary dictionary && dictionary.Comparer == DefaultComparer) { return dictionary.TryGetValue(key, out value); } using (ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = new ScopeContextPropertyEnumerator(scopeProperties)) { while (scopeContextPropertyEnumerator.MoveNext()) { KeyValuePair current = scopeContextPropertyEnumerator.Current; if (DefaultComparer.Equals(current.Key, key)) { value = current.Value; return true; } } } value = null; return false; } internal static long GetNestedContextTimestampNow() { if (Stopwatch.IsHighResolution) { return Stopwatch.GetTimestamp(); } return Environment.TickCount; } private static TimeSpan GetNestedStateDuration(long scopeTimestamp, long currentTimestamp) { if (Stopwatch.IsHighResolution) { return TimeSpan.FromTicks((currentTimestamp - scopeTimestamp) * 10000000 / Stopwatch.Frequency); } return TimeSpan.FromMilliseconds((int)currentTimestamp - (int)scopeTimestamp); } internal static void SetAsyncLocalContext(IScopeContextAsyncState? newValue) { AsyncNestedDiagnosticsContext.Value = newValue; } private static IScopeContextAsyncState? GetAsyncLocalContext() { return AsyncNestedDiagnosticsContext.Value; } [Obsolete("Replaced by ScopeContext.PushProperty. Marked obsolete on NLog 5.0")] internal static void SetMappedContextLegacy(string key, TValue? value) { PushProperty(key, value); } internal static ICollection GetKeysMappedContextLegacy() { IScopeContextAsyncState? asyncLocalContext = GetAsyncLocalContext(); ScopeContextPropertyCollector contextCollector = default(ScopeContextPropertyCollector); IReadOnlyCollection> readOnlyCollection = asyncLocalContext?.CaptureContextProperties(ref contextCollector); if (readOnlyCollection != null && readOnlyCollection.Count > 0) { if (readOnlyCollection.Count == 1) { return new string[1] { readOnlyCollection.First().Key }; } if (readOnlyCollection is IDictionary dictionary) { return dictionary.Keys; } return readOnlyCollection.Select((KeyValuePair prop) => prop.Key).ToList(); } return ArrayHelper.Empty(); } [Obsolete("Replaced by disposing return value from ScopeContext.PushProperty. Marked obsolete on NLog 5.0")] internal static void RemoveMappedContextLegacy(string key) { if (TryGetProperty(key, out object _)) { ScopeContextLegacyAsyncState.CaptureLegacyContext(GetAsyncLocalContext(), out Dictionary allProperties, out object[] nestedContext, out long nestedContextTimestamp); allProperties.Remove(key); SetAsyncLocalContext(new ScopeContextLegacyAsyncState(allProperties, nestedContext, nestedContextTimestamp)); } } [Obsolete("Replaced by disposing return value from ScopeContext.PushNestedState. Marked obsolete on NLog 5.0")] internal static object? PopNestedContextLegacy() { IScopeContextAsyncState asyncLocalContext = GetAsyncLocalContext(); if (asyncLocalContext != null) { if ((asyncLocalContext.Parent == null && asyncLocalContext is ScopeContextLegacyAsyncState) || asyncLocalContext.NestedState == null) { ScopeContextNestedStateCollector contextCollector = default(ScopeContextNestedStateCollector); IList list = asyncLocalContext.CaptureNestedContext(ref contextCollector) ?? ArrayHelper.Empty(); if (list.Count == 0) { return null; } ScopeContextPropertyCollector contextCollector2 = default(ScopeContextPropertyCollector); object result = list[0]; IReadOnlyCollection> allProperties = (IReadOnlyCollection>)(((object)asyncLocalContext.CaptureContextProperties(ref contextCollector2)) ?? ((object)ArrayHelper.Empty>())); object[] array = ArrayHelper.Empty(); if (list.Count > 1) { array = new object[list.Count - 1]; for (int i = 0; i < array.Length; i++) { array[i] = list[i + 1]; } } SetAsyncLocalContext(new ScopeContextLegacyAsyncState(allProperties, array, (array.Length != 0) ? GetNestedContextTimestampNow() : 0)); return result; } SetAsyncLocalContext(asyncLocalContext.Parent); return asyncLocalContext.NestedState; } return null; } [Obsolete("Replaced by ScopeContext.Clear. Marked obsolete on NLog 5.0")] internal static void ClearMappedContextLegacy() { IScopeContextAsyncState asyncLocalContext = GetAsyncLocalContext(); if (asyncLocalContext == null) { return; } ScopeContextLegacyAsyncState.CaptureLegacyContext(asyncLocalContext, out Dictionary allProperties, out object[] nestedContext, out long nestedContextTimestamp); if (nestedContext != null && nestedContext.Length != 0) { if (allProperties != null && allProperties.Count > 0) { SetAsyncLocalContext(new ScopeContextLegacyAsyncState(null, nestedContext, nestedContextTimestamp)); } } else { SetAsyncLocalContext(null); } } [Obsolete("Replaced by ScopeContext.Clear. Marked obsolete on NLog 5.0")] internal static void ClearNestedContextLegacy() { IScopeContextAsyncState asyncLocalContext = GetAsyncLocalContext(); if (asyncLocalContext == null) { return; } ScopeContextLegacyAsyncState.CaptureLegacyContext(asyncLocalContext, out Dictionary allProperties, out object[] nestedContext, out long _); if (allProperties != null && allProperties.Count > 0) { if (nestedContext != null && nestedContext.Length != 0) { SetAsyncLocalContext(new ScopeContextLegacyAsyncState(allProperties, ArrayHelper.Empty(), 0L)); } } else { SetAsyncLocalContext(null); } } } public static class SetupBuilderExtensions { [MethodImpl(MethodImplOptions.NoInlining)] public static Logger GetCurrentClassLogger(this ISetupBuilder setupBuilder) { string classFullName = StackTraceUsageUtils.GetClassFullName(new StackFrame(1, needFileInfo: false)); return setupBuilder.LogFactory.GetLogger(classFullName); } public static Logger GetLogger(this ISetupBuilder setupBuilder, string name) { return setupBuilder.LogFactory.GetLogger(name); } public static ISetupBuilder SetupLogFactory(this ISetupBuilder setupBuilder, Action logfactoryBuilder) { logfactoryBuilder(new SetupLogFactoryBuilder(setupBuilder.LogFactory)); return setupBuilder; } public static ISetupBuilder SetupExtensions(this ISetupBuilder setupBuilder, Action extensionsBuilder) { extensionsBuilder(new SetupExtensionsBuilder(setupBuilder.LogFactory)); return setupBuilder; } public static ISetupBuilder SetupInternalLogger(this ISetupBuilder setupBuilder, Action internalLoggerBuilder) { internalLoggerBuilder(new SetupInternalLoggerBuilder(setupBuilder.LogFactory)); return setupBuilder; } public static ISetupBuilder SetupSerialization(this ISetupBuilder setupBuilder, Action serializationBuilder) { serializationBuilder(new SetupSerializationBuilder(setupBuilder.LogFactory)); return setupBuilder; } public static ISetupBuilder LoadConfiguration(this ISetupBuilder setupBuilder, Action configBuilder) { LoggingConfiguration config = setupBuilder.LogFactory._config; SetupLoadConfigurationBuilder setupLoadConfigurationBuilder = new SetupLoadConfigurationBuilder(setupBuilder.LogFactory, config); configBuilder(setupLoadConfigurationBuilder); LoggingConfiguration configuration = setupLoadConfigurationBuilder._configuration; bool flag = config != setupBuilder.LogFactory._config; if (configuration == setupBuilder.LogFactory._config) { if (config != configuration || configuration != null) { setupBuilder.LogFactory.ReconfigExistingLoggers(); } } else if (!flag || config != configuration) { setupBuilder.LogFactory.Configuration = configuration; } return setupBuilder; } public static ISetupBuilder LoadConfiguration(this ISetupBuilder setupBuilder, LoggingConfiguration loggingConfiguration) { setupBuilder.LogFactory.Configuration = loggingConfiguration; return setupBuilder; } public static ISetupBuilder LoadConfigurationFromFile(this ISetupBuilder setupBuilder, string? configFile = null, bool optional = true) { setupBuilder.LogFactory.LoadConfiguration(configFile, optional); return setupBuilder; } public static ISetupBuilder LoadConfigurationFromFile(this ISetupBuilder setupBuilder, IEnumerable candidateFilePaths, bool optional = true) { if (candidateFilePaths == null) { setupBuilder.LogFactory.ResetCandidateConfigFilePath(); } else if (optional) { IEnumerable candidateConfigFilePaths = setupBuilder.LogFactory.GetCandidateConfigFilePaths(); List list = new List(candidateFilePaths); HashSet hashSet = new HashSet(list, StringComparer.OrdinalIgnoreCase); foreach (string item in candidateConfigFilePaths) { if (hashSet.Add(item)) { list.Add(item); } } setupBuilder.LogFactory.SetCandidateConfigFilePaths(list); } else { setupBuilder.LogFactory.SetCandidateConfigFilePaths(candidateFilePaths); } return setupBuilder.LoadConfigurationFromFile((string?)null, optional); } public static ISetupBuilder LoadConfigurationFromXml(this ISetupBuilder setupBuilder, string configXml) { setupBuilder.LogFactory.Configuration = XmlLoggingConfiguration.CreateFromXmlString(configXml, setupBuilder.LogFactory); return setupBuilder; } public static ISetupBuilder LoadConfigurationFromAssemblyResource(this ISetupBuilder setupBuilder, Assembly applicationAssembly, string resourceName = "NLog.config") { string resourceName2 = resourceName; Guard.ThrowIfNull(applicationAssembly, "applicationAssembly"); Guard.ThrowIfNullOrEmpty(resourceName2, "resourceName"); List list = (from x in applicationAssembly.GetManifestResourceNames() where x.EndsWith(resourceName2, StringComparison.OrdinalIgnoreCase) select x).ToList(); if (list.Count == 1) { Stream manifestResourceStream = applicationAssembly.GetManifestResourceStream(list[0]); if (manifestResourceStream != null && manifestResourceStream.Length > 0) { InternalLogger.Info("Loading NLog XML config from assembly embedded resource '{0}'", resourceName2); using StreamReader xmlSource = new StreamReader(manifestResourceStream); setupBuilder.LoadConfiguration(new XmlLoggingConfiguration(xmlSource, null, setupBuilder.LogFactory)); } else { InternalLogger.Debug("No NLog config loaded. Empty Embedded resource '{0}' found in assembly: {1}", resourceName2, applicationAssembly.FullName); } } else if (list.Count == 0) { InternalLogger.Debug("No NLog config loaded. No matching embedded resource '{0}' found in assembly: {1}", resourceName2, applicationAssembly.FullName); } else { InternalLogger.Error("No NLog config loaded. Multiple matching embedded resource '{0}' found in assembly: {1}", resourceName2, applicationAssembly.FullName); } return setupBuilder; } public static ISetupBuilder ReloadConfiguration(this ISetupBuilder setupBuilder) { try { InternalLogger.Debug("Reloading NLog LoggingConfiguration"); LoggingConfiguration loggingConfiguration = setupBuilder.LogFactory._config?.Reload(); if (loggingConfiguration == null) { return setupBuilder; } setupBuilder.LogFactory.Configuration = loggingConfiguration; return setupBuilder; } catch (NLogConfigurationException ex) { InternalLogger.Error(ex, "Failed to reload NLog LoggingConfiguration"); if (ex.MustBeRethrown() || (setupBuilder.LogFactory.ThrowConfigExceptions ?? setupBuilder.LogFactory.ThrowExceptions)) { throw; } return setupBuilder; } catch (Exception ex2) { InternalLogger.Error(ex2, "Failed to reload NLog LoggingConfiguration"); if (ex2.MustBeRethrownImmediately()) { throw; } return setupBuilder; } } } public static class SetupExtensionsBuilderExtensions { [Obsolete("AutoLoadAssemblies(true) has been replaced by AutoLoadExtensions(), that matches the name of nlog-attribute in NLog.config. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static ISetupExtensionsBuilder AutoLoadAssemblies(this ISetupExtensionsBuilder setupBuilder, bool enable) { if (enable) { setupBuilder.AutoLoadExtensions(); } return setupBuilder; } public static ISetupExtensionsBuilder AutoLoadExtensions(this ISetupExtensionsBuilder setupBuilder) { ConfigurationItemFactory.Default.AssemblyLoader.ScanForAutoLoadExtensions(ConfigurationItemFactory.Default); return setupBuilder; } public static ISetupExtensionsBuilder RegisterAssembly(this ISetupExtensionsBuilder setupBuilder, Assembly assembly) { ConfigurationItemFactory.Default.AssemblyLoader.LoadAssembly(ConfigurationItemFactory.Default, assembly, string.Empty); return setupBuilder; } public static ISetupExtensionsBuilder RegisterAssembly(this ISetupExtensionsBuilder setupBuilder, string assemblyName) { ConfigurationItemFactory.Default.AssemblyLoader.LoadAssemblyFromName(ConfigurationItemFactory.Default, assemblyName, string.Empty); return setupBuilder; } public static ISetupExtensionsBuilder RegisterType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder) where T : class, new() { ConfigurationItemFactory.Default.RegisterType(); return setupBuilder; } public static ISetupExtensionsBuilder RegisterTarget<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, string? name = null) where T : Target, new() { return setupBuilder.RegisterTarget(() => new T(), name); } public static ISetupExtensionsBuilder RegisterTarget<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, Func factory, string? typeAlias = null) where T : Target { typeAlias = ((!string.IsNullOrEmpty(typeAlias)) ? typeAlias : typeof(T).GetFirstCustomAttribute()?.Name); if (typeAlias == null || string.IsNullOrEmpty(typeAlias)) { typeAlias = ResolveTypeAlias(new string[2] { "TargetWrapper", "Target" }); if (typeof(WrapperTargetBase).IsAssignableFrom(typeof(T)) && !typeAlias.EndsWith("Wrapper", StringComparison.OrdinalIgnoreCase)) { typeAlias += "Wrapper"; } } ConfigurationItemFactory.Default.GetTargetFactory().RegisterType(typeAlias, factory); return setupBuilder; } public static ISetupExtensionsBuilder RegisterTarget(this ISetupExtensionsBuilder setupBuilder, string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type targetType) { Type targetType2 = targetType; if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Missing NLog Target type-alias", "name"); } if (!typeof(Target).IsAssignableFrom(targetType2)) { throw new ArgumentException("Not of type NLog Target", "targetType"); } ConfigurationItemFactory.Default.GetTargetFactory().RegisterType(name, () => (Target)Activator.CreateInstance(targetType2)); return setupBuilder; } public static ISetupExtensionsBuilder RegisterLayout<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, string? typeAlias = null) where T : Layout, new() { return setupBuilder.RegisterLayout(() => new T(), typeAlias); } public static ISetupExtensionsBuilder RegisterLayout<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, Func factory, string? typeAlias = null) where T : Layout { typeAlias = ((typeAlias == null || string.IsNullOrEmpty(typeAlias)) ? ResolveTypeAlias(ArrayHelper.Empty()) : typeAlias); ConfigurationItemFactory.Default.GetLayoutFactory().RegisterType(typeAlias, factory); return setupBuilder; } public static ISetupExtensionsBuilder RegisterLayout(this ISetupExtensionsBuilder setupBuilder, string typeAlias, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type layoutType) { Type layoutType2 = layoutType; if (string.IsNullOrEmpty(typeAlias)) { throw new ArgumentException("Missing NLog Layout type-alias", "typeAlias"); } if (!typeof(Layout).IsAssignableFrom(layoutType2)) { throw new ArgumentException("Not of type NLog Layout", "layoutType"); } ConfigurationItemFactory.Default.GetLayoutFactory().RegisterType(typeAlias, () => (Layout)Activator.CreateInstance(layoutType2)); return setupBuilder; } public static ISetupExtensionsBuilder RegisterLayoutRenderer<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, string? name = null) where T : LayoutRenderer, new() { return setupBuilder.RegisterLayoutRenderer(() => new T(), name); } public static ISetupExtensionsBuilder RegisterLayoutRenderer<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupExtensionsBuilder setupBuilder, Func factory, string? typeAlias = null) where T : LayoutRenderer { typeAlias = ((typeAlias == null || string.IsNullOrEmpty(typeAlias)) ? ResolveTypeAlias(new string[2] { "LayoutRendererWrapper", "LayoutRenderer" }) : typeAlias); ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterType(typeAlias, factory); return setupBuilder; } private static string ResolveTypeAlias(params string[] trimEndings) where TNameAttribute : NameBaseAttribute { string text = typeof(T).GetFirstCustomAttribute()?.Name; if (text == null || string.IsNullOrEmpty(text)) { return ResolveTypeAlias(trimEndings); } return text; } private static string ResolveTypeAlias(params string[] trimEndings) { string name = typeof(T).Name; foreach (string value in trimEndings) { int num = name.IndexOf(value, StringComparison.OrdinalIgnoreCase); if (num > 0) { return name.Substring(0, num); } } return name; } public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type layoutRendererType) { Type layoutRendererType2 = layoutRendererType; if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Missing NLog LayoutRenderer type-alias", "name"); } if (!typeof(LayoutRenderer).IsAssignableFrom(layoutRendererType2)) { throw new ArgumentException("Not of type NLog LayoutRenderer", "layoutRendererType"); } ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterType(name, () => (LayoutRenderer)Activator.CreateInstance(layoutRendererType2)); return setupBuilder; } public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, Func layoutMethod) { Func layoutMethod2 = layoutMethod; return setupBuilder.RegisterLayoutRenderer(name, (LogEventInfo info, LoggingConfiguration? configuration) => layoutMethod2(info)); } public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, Func layoutMethod) { return setupBuilder.RegisterLayoutRenderer(name, layoutMethod, LayoutRenderOptions.None); } public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, Func layoutMethod, LayoutRenderOptions options) { Func layoutMethod2 = layoutMethod; return setupBuilder.RegisterLayoutRenderer(name, (LogEventInfo info, LoggingConfiguration? configuration) => layoutMethod2(info), options); } public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, string name, Func layoutMethod, LayoutRenderOptions options) { FuncLayoutRenderer layoutRenderer = Layout.CreateFuncLayoutRenderer(layoutMethod, options, name); return setupBuilder.RegisterLayoutRenderer(layoutRenderer); } public static ISetupExtensionsBuilder RegisterLayoutRenderer(this ISetupExtensionsBuilder setupBuilder, FuncLayoutRenderer layoutRenderer) { ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterFuncLayout(layoutRenderer.LayoutRendererName, layoutRenderer); return setupBuilder; } [Obsolete("Instead use RegisterConditionMethod with delegate, as type reflection will be moved out. Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static ISetupExtensionsBuilder RegisterConditionMethod(this ISetupExtensionsBuilder setupBuilder, string name, MethodInfo conditionMethod) { Guard.ThrowIfNull(conditionMethod, "conditionMethod"); if (!conditionMethod.IsStatic) { throw new ArgumentException(conditionMethod.Name + " must be static", "conditionMethod"); } ConfigurationItemFactory.Default.GetConditionMethodFactory().RegisterDefinition(name, conditionMethod); return setupBuilder; } public static ISetupExtensionsBuilder RegisterConditionMethod(this ISetupExtensionsBuilder setupBuilder, string name, Func conditionMethod) { Func conditionMethod2 = conditionMethod; Guard.ThrowIfNull(conditionMethod2, "conditionMethod"); ConfigurationItemFactory.Default.GetConditionMethodFactory().RegisterNoParameters(name, (LogEventInfo logEvent) => conditionMethod2(logEvent)); return setupBuilder; } public static ISetupExtensionsBuilder RegisterConditionMethod(this ISetupExtensionsBuilder setupBuilder, string name, Func conditionMethod) { Func conditionMethod2 = conditionMethod; Guard.ThrowIfNull(conditionMethod2, "conditionMethod"); ConfigurationItemFactory.Default.GetConditionMethodFactory().RegisterNoParameters(name, (LogEventInfo logEvent) => conditionMethod2()); return setupBuilder; } public static ISetupExtensionsBuilder RegisterSingletonService(this ISetupExtensionsBuilder setupBuilder, T singletonService) where T : class { Guard.ThrowIfNull(singletonService, "singletonService"); setupBuilder.LogFactory.ServiceRepository.RegisterSingleton(singletonService); return setupBuilder; } public static ISetupExtensionsBuilder RegisterSingletonService(this ISetupExtensionsBuilder setupBuilder, Type interfaceType, object singletonService) { Guard.ThrowIfNull(interfaceType, "interfaceType"); Guard.ThrowIfNull(singletonService, "singletonService"); if (!interfaceType.IsAssignableFrom(singletonService.GetType())) { throw new ArgumentException("Service instance not matching type", "singletonService"); } setupBuilder.LogFactory.ServiceRepository.RegisterService(interfaceType, singletonService); return setupBuilder; } public static ISetupExtensionsBuilder RegisterServiceProvider(this ISetupExtensionsBuilder setupBuilder, IServiceProvider serviceProvider) { Guard.ThrowIfNull(serviceProvider, "serviceProvider"); setupBuilder.LogFactory.ServiceRepository.RegisterSingleton(serviceProvider); return setupBuilder; } } public static class SetupInternalLoggerBuilderExtensions { public static ISetupInternalLoggerBuilder SetMinimumLogLevel(this ISetupInternalLoggerBuilder setupBuilder, LogLevel logLevel) { LogLevel logLevel2 = InternalLogger.LogLevel; InternalLogger.LogLevel = logLevel; if (InternalLogger.LogLevel != LogLevel.Off && logLevel2 == LogLevel.Off) { string logFile = InternalLogger.LogFile; if (!string.IsNullOrEmpty(logFile)) { InternalLogger.LogFile = logFile; } } return setupBuilder; } public static ISetupInternalLoggerBuilder LogToFile(this ISetupInternalLoggerBuilder setupBuilder, string fileName) { InternalLogger.LogFile = fileName; return setupBuilder; } public static ISetupInternalLoggerBuilder LogToConsole(this ISetupInternalLoggerBuilder setupBuilder, bool enabled) { InternalLogger.LogToConsole = enabled; return setupBuilder; } public static ISetupInternalLoggerBuilder LogToWriter(this ISetupInternalLoggerBuilder setupBuilder, TextWriter writer) { InternalLogger.LogWriter = writer; return setupBuilder; } public static ISetupInternalLoggerBuilder AddEventSubscription(this ISetupInternalLoggerBuilder setupBuilder, InternalEventOccurredHandler eventSubscriber) { InternalLogger.InternalEventOccurred += eventSubscriber; return setupBuilder; } public static ISetupInternalLoggerBuilder RemoveEventSubscription(this ISetupInternalLoggerBuilder setupBuilder, InternalEventOccurredHandler eventSubscriber) { InternalLogger.InternalEventOccurred -= eventSubscriber; return setupBuilder; } public static ISetupInternalLoggerBuilder ResetConfig(this ISetupInternalLoggerBuilder setupBuilder) { InternalLogger.Reset(); return setupBuilder; } public static ISetupInternalLoggerBuilder SetupFromEnvironmentVariables(this ISetupInternalLoggerBuilder setupBuilder) { InternalLogger.LogLevel = GetSetting("nlog.internalLogLevel", "NLOG_INTERNAL_LOG_LEVEL", LogLevel.Off); InternalLogger.IncludeTimestamp = GetSetting("nlog.internalLogIncludeTimestamp", "NLOG_INTERNAL_INCLUDE_TIMESTAMP", defaultValue: true); InternalLogger.LogToConsole = GetSetting("nlog.internalLogToConsole", "NLOG_INTERNAL_LOG_TO_CONSOLE", defaultValue: false); InternalLogger.LogToConsoleError = GetSetting("nlog.internalLogToConsoleError", "NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR", defaultValue: false); InternalLogger.LogFile = GetSetting("nlog.internalLogFile", "NLOG_INTERNAL_LOG_FILE", string.Empty); return setupBuilder; } private static string? GetAppSettings(string configName) { return null; } private static string? GetSettingString(string configName, string envName) { try { string appSettings = GetAppSettings(configName); if (appSettings != null) { return appSettings; } } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } } try { string safeEnvironmentVariable = EnvironmentHelper.GetSafeEnvironmentVariable(envName); if (!string.IsNullOrEmpty(safeEnvironmentVariable)) { return safeEnvironmentVariable; } } catch (Exception exception2) { if (exception2.MustBeRethrownImmediately()) { throw; } } return null; } private static LogLevel GetSetting(string configName, string envName, LogLevel defaultValue) { string settingString = GetSettingString(configName, envName); if (settingString == null) { return defaultValue; } try { return LogLevel.FromString(settingString); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } return defaultValue; } } private static T GetSetting(string configName, string envName, T defaultValue) { string settingString = GetSettingString(configName, envName); if (settingString == null) { return defaultValue; } try { return (T)Convert.ChangeType(settingString, typeof(T), CultureInfo.InvariantCulture); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) { throw; } return defaultValue; } } } public static class SetupLoadConfigurationExtensions { [CompilerGenerated] private sealed class d__20 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private Target <>2__current; private int <>l__initialThreadId; private Target target; public Target <>3__target; private IEnumerator <>7__wrap1; private IEnumerator <>7__wrap2; Target IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__20(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; switch (num) { case -3: case 2: try { } finally { <>m__Finally1(); } break; case -5: case -4: case 3: try { if (num == -5 || num == 3) { try { } finally { <>m__Finally3(); } } } finally { <>m__Finally2(); } break; } <>7__wrap1 = null; <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; if (target != null) { <>2__current = target; <>1__state = 1; return true; } goto IL_0054; case 1: <>1__state = -1; goto IL_0054; case 2: <>1__state = -3; goto IL_00ac; case 3: { <>1__state = -5; goto IL_014c; } IL_0054: if (target is WrapperTargetBase wrapperTargetBase) { <>7__wrap1 = YieldAllTargets(wrapperTargetBase.WrappedTarget).GetEnumerator(); <>1__state = -3; goto IL_00ac; } if (!(target is CompoundTargetBase compoundTargetBase)) { break; } <>7__wrap1 = compoundTargetBase.Targets.GetEnumerator(); <>1__state = -4; goto IL_0166; IL_0166: if (<>7__wrap1.MoveNext()) { Target current = <>7__wrap1.Current; <>7__wrap2 = YieldAllTargets(current).GetEnumerator(); <>1__state = -5; goto IL_014c; } <>m__Finally2(); <>7__wrap1 = null; break; IL_00ac: if (<>7__wrap1.MoveNext()) { Target current2 = <>7__wrap1.Current; <>2__current = current2; <>1__state = 2; return true; } <>m__Finally1(); <>7__wrap1 = null; break; IL_014c: if (<>7__wrap2.MoveNext()) { Target current3 = <>7__wrap2.Current; <>2__current = current3; <>1__state = 3; return true; } <>m__Finally3(); <>7__wrap2 = null; goto IL_0166; } return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } private void <>m__Finally2() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } private void <>m__Finally3() { <>1__state = -4; if (<>7__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { d__20 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__20(0); } d__.target = <>3__target; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } public static ISetupLoadConfigurationBuilder SetTimeSource(this ISetupLoadConfigurationBuilder configBuilder, TimeSource timeSource) { TimeSource.Current = timeSource; return configBuilder; } public static ISetupLoadConfigurationBuilder SetGlobalContextProperty(this ISetupLoadConfigurationBuilder configBuilder, string name, string value) { GlobalDiagnosticsContext.Set(name, value); return configBuilder; } public static ISetupConfigurationLoggingRuleBuilder ForLogger(this ISetupLoadConfigurationBuilder configBuilder, string loggerNamePattern = "*", string? ruleName = null) { SetupConfigurationLoggingRuleBuilder setupConfigurationLoggingRuleBuilder = new SetupConfigurationLoggingRuleBuilder(configBuilder.LogFactory, configBuilder.Configuration, loggerNamePattern, ruleName); setupConfigurationLoggingRuleBuilder.LoggingRule.EnableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); return setupConfigurationLoggingRuleBuilder; } public static ISetupConfigurationLoggingRuleBuilder ForLogger(this ISetupLoadConfigurationBuilder configBuilder, LogLevel minLevel, string loggerNamePattern = "*", string? ruleName = null) { SetupConfigurationLoggingRuleBuilder setupConfigurationLoggingRuleBuilder = new SetupConfigurationLoggingRuleBuilder(configBuilder.LogFactory, configBuilder.Configuration, loggerNamePattern, ruleName); setupConfigurationLoggingRuleBuilder.LoggingRule.EnableLoggingForLevels(minLevel ?? LogLevel.MinLevel, LogLevel.MaxLevel); return setupConfigurationLoggingRuleBuilder; } public static ISetupConfigurationTargetBuilder ForTarget(this ISetupLoadConfigurationBuilder configBuilder, string? targetName = null) { return new SetupConfigurationTargetBuilder(configBuilder.LogFactory, configBuilder.Configuration, targetName); } public static ISetupConfigurationLoggingRuleBuilder FilterMinLevel(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel minLevel) { Guard.ThrowIfNull(minLevel, "minLevel"); configBuilder.LoggingRule.DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); configBuilder.LoggingRule.EnableLoggingForLevels(minLevel, LogLevel.MaxLevel); return configBuilder; } public static ISetupConfigurationLoggingRuleBuilder FilterMaxLevel(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel maxLevel) { Guard.ThrowIfNull(maxLevel, "maxLevel"); configBuilder.LoggingRule.DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); configBuilder.LoggingRule.EnableLoggingForLevels(LogLevel.MinLevel, maxLevel); return configBuilder; } public static ISetupConfigurationLoggingRuleBuilder FilterLevel(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel logLevel) { Guard.ThrowIfNull(logLevel, "logLevel"); if (configBuilder.LoggingRule.IsLoggingEnabledForLevel(logLevel)) { configBuilder.LoggingRule.DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); } configBuilder.LoggingRule.EnableLoggingForLevel(logLevel); return configBuilder; } public static ISetupConfigurationLoggingRuleBuilder FilterLevels(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel minLevel, LogLevel maxLevel) { configBuilder.LoggingRule.DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); configBuilder.LoggingRule.EnableLoggingForLevels(minLevel ?? LogLevel.MinLevel, maxLevel ?? LogLevel.MaxLevel); return configBuilder; } public static ISetupConfigurationLoggingRuleBuilder FilterDynamic(this ISetupConfigurationLoggingRuleBuilder configBuilder, Filter filter, FilterResult? filterDefaultAction = null) { Guard.ThrowIfNull(filter, "filter"); configBuilder.LoggingRule.Filters.Add(filter); if (filterDefaultAction.HasValue) { configBuilder.LoggingRule.FilterDefaultAction = filterDefaultAction.Value; } return configBuilder; } public static ISetupConfigurationLoggingRuleBuilder FilterDynamic(this ISetupConfigurationLoggingRuleBuilder configBuilder, Func filterMethod, FilterResult? filterDefaultAction = null) { Guard.ThrowIfNull(filterMethod, "filterMethod"); return configBuilder.FilterDynamic(new WhenMethodFilter(filterMethod), filterDefaultAction); } public static ISetupConfigurationLoggingRuleBuilder FilterDynamicIgnore(this ISetupConfigurationLoggingRuleBuilder configBuilder, Func filterMethod, bool final = false) { Func filterMethod2 = filterMethod; FilterResult matchResult = (final ? FilterResult.IgnoreFinal : FilterResult.Ignore); WhenMethodFilter filter = new WhenMethodFilter((LogEventInfo evt) => filterMethod2(evt) ? matchResult : FilterResult.Neutral) { Action = matchResult }; return configBuilder.FilterDynamic(filter, FilterResult.Neutral); } public static ISetupConfigurationLoggingRuleBuilder FilterDynamicLog(this ISetupConfigurationLoggingRuleBuilder configBuilder, Func filterMethod, bool final = false) { Func filterMethod2 = filterMethod; FilterResult matchResult = ((!final) ? FilterResult.Log : FilterResult.LogFinal); WhenMethodFilter filter = new WhenMethodFilter((LogEventInfo evt) => filterMethod2(evt) ? matchResult : FilterResult.Neutral) { Action = matchResult }; return configBuilder.FilterDynamic(filter, final ? FilterResult.IgnoreFinal : FilterResult.Ignore); } public static ISetupConfigurationLoggingRuleBuilder TopRule(this ISetupConfigurationLoggingRuleBuilder configBuilder, bool insertFirst = true) { LoggingRule loggingRule = configBuilder.LoggingRule; if (configBuilder.Configuration.LoggingRules.Contains(loggingRule)) { if (!insertFirst) { return configBuilder; } configBuilder.Configuration.LoggingRules.Remove(loggingRule); } if (insertFirst) { configBuilder.Configuration.LoggingRules.Insert(0, loggingRule); } else { configBuilder.Configuration.LoggingRules.Add(loggingRule); } return configBuilder; } public static ISetupConfigurationTargetBuilder WriteTo(this ISetupConfigurationTargetBuilder configBuilder, Target target) { if (target != null) { if (string.IsNullOrEmpty(target.Name)) { target.Name = EnsureUniqueTargetName(configBuilder.Configuration, target); } configBuilder.Targets.Add(target); configBuilder.Configuration.AddTarget(target); } return configBuilder; } public static ISetupConfigurationTargetBuilder WriteTo(this ISetupConfigurationTargetBuilder configBuilder, params Target[] targets) { if (targets != null && targets.Length != 0) { for (int i = 0; i < targets.Length; i++) { configBuilder.WriteTo(targets[i]); } } return configBuilder; } public static ISetupConfigurationTargetBuilder WriteTo(this ISetupConfigurationTargetBuilder configBuilder, ISetupConfigurationTargetBuilder targetBuilder) { if (configBuilder == targetBuilder) { throw new ArgumentException("ConfigBuilder and TargetBuilder cannot be the same object", "targetBuilder"); } IList targets = targetBuilder.Targets; if (targets != null && targets.Count > 0) { for (int i = 0; i < targetBuilder.Targets.Count; i++) { configBuilder.WriteTo(targetBuilder.Targets[i]); } } return configBuilder; } public static void WriteToNil(this ISetupConfigurationLoggingRuleBuilder configBuilder, LogLevel? finalMinLevel = null) { LoggingRule loggingRule = configBuilder.LoggingRule; if (finalMinLevel != null) { if (loggingRule.Targets.Count == 0) { loggingRule = configBuilder.FilterMinLevel(finalMinLevel).LoggingRule; } loggingRule.FinalMinLevel = finalMinLevel; } else { if (loggingRule.Targets.Count == 0) { loggingRule = configBuilder.FilterMaxLevel(LogLevel.MaxLevel).LoggingRule; } if (loggingRule.Filters.Count == 0) { loggingRule.Final = true; } } if (loggingRule.Filters.Count > 0) { if (loggingRule.FilterDefaultAction == FilterResult.Ignore) { loggingRule.FilterDefaultAction = FilterResult.IgnoreFinal; } for (int i = 0; i < loggingRule.Filters.Count; i++) { if (loggingRule.Filters[i].Action == FilterResult.Ignore) { loggingRule.Filters[i].Action = FilterResult.IgnoreFinal; } } if (loggingRule.Targets.Count == 0) { loggingRule.Targets.Add(new NullTarget()); } } if (!configBuilder.Configuration.LoggingRules.Contains(loggingRule)) { configBuilder.Configuration.LoggingRules.Add(loggingRule); } } public static Target FirstTarget(this ISetupConfigurationTargetBuilder configBuilder) { return configBuilder.Targets.First(); } public static T FirstTarget(this ISetupConfigurationTargetBuilder configBuilder) where T : Target { Target target = configBuilder.Targets.First(); for (int i = 0; i < configBuilder.Targets.Count; i++) { foreach (Target item in YieldAllTargets(configBuilder.Targets[i])) { if (item is T result) { return result; } } } throw new InvalidCastException($"Unable to cast object of type '{target.GetType()}' to type '{typeof(T)}'"); } [IteratorStateMachine(typeof(d__20))] internal static IEnumerable YieldAllTargets(Target? target) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__20(-2) { <>3__target = target }; } public static ISetupConfigurationTargetBuilder WriteToMethodCall(this ISetupConfigurationTargetBuilder configBuilder, Action logEventAction, Layout[]? layouts = null) { Guard.ThrowIfNull(logEventAction, "logEventAction"); MethodCallTarget methodCallTarget = new MethodCallTarget(string.Empty, logEventAction); if (layouts != null && layouts.Length != 0) { foreach (Layout layout in layouts) { methodCallTarget.Parameters.Add(new MethodCallParameter(layout)); } } return configBuilder.WriteTo(methodCallTarget); } public static ISetupConfigurationTargetBuilder WriteToConsole(this ISetupConfigurationTargetBuilder configBuilder, Layout? layout = null, Encoding? encoding = null, bool stderr = false, bool detectConsoleAvailable = false, bool forceWriteLine = false) { ConsoleTarget consoleTarget = new ConsoleTarget(); if (layout != null) { consoleTarget.Layout = layout; } if (encoding != null) { consoleTarget.Encoding = encoding; } if (stderr) { consoleTarget.StdErr = stderr; } consoleTarget.DetectConsoleAvailable = detectConsoleAvailable; consoleTarget.ForceWriteLine = forceWriteLine; return configBuilder.WriteTo(consoleTarget); } public static ISetupConfigurationTargetBuilder WriteToColoredConsole(this ISetupConfigurationTargetBuilder configBuilder, Layout? layout = null, bool highlightWordLevel = false, Encoding? encoding = null, bool stderr = false, bool detectConsoleAvailable = false, bool enableAnsiOutput = false) { ColoredConsoleTarget coloredConsoleTarget = new ColoredConsoleTarget(); if (layout != null) { coloredConsoleTarget.Layout = layout; } if (encoding != null) { coloredConsoleTarget.Encoding = encoding; } coloredConsoleTarget.StdErr = stderr; coloredConsoleTarget.DetectConsoleAvailable = detectConsoleAvailable; coloredConsoleTarget.EnableAnsiOutput = enableAnsiOutput; coloredConsoleTarget.UseDefaultRowHighlightingRules = false; ConditionMethodExpression condition = ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Fatal", (LogEventInfo evt) => evt.Level == LogLevel.Fatal); ConditionMethodExpression condition2 = ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Error", (LogEventInfo evt) => evt.Level == LogLevel.Error); ConditionMethodExpression condition3 = ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Warn", (LogEventInfo evt) => evt.Level == LogLevel.Warn); if (enableAnsiOutput) { if (highlightWordLevel) { coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("Fatal", ConsoleOutputColor.DarkRed, ConsoleOutputColor.NoChange) { Condition = condition, IgnoreCase = true, WholeWords = true }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("Error", ConsoleOutputColor.DarkRed, ConsoleOutputColor.NoChange) { Condition = condition2, IgnoreCase = true, WholeWords = true }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("Warn", ConsoleOutputColor.DarkYellow, ConsoleOutputColor.NoChange) { Condition = condition3, IgnoreCase = true, WholeWords = true }); } else { foreach (ConsoleRowHighlightingRule defaultConsoleRowHighlightingRule in new ColoredConsoleAnsiPrinter().DefaultConsoleRowHighlightingRules) { coloredConsoleTarget.RowHighlightingRules.Add(defaultConsoleRowHighlightingRule); } } } else if (highlightWordLevel) { coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("Fatal", ConsoleOutputColor.White, ConsoleOutputColor.DarkRed) { Condition = condition, IgnoreCase = true, WholeWords = true }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("Error", ConsoleOutputColor.White, ConsoleOutputColor.DarkRed) { Condition = condition2, IgnoreCase = true, WholeWords = true }); coloredConsoleTarget.WordHighlightingRules.Add(new ConsoleWordHighlightingRule("Warn", ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange) { Condition = condition3, IgnoreCase = true, WholeWords = true }); } else { foreach (ConsoleRowHighlightingRule defaultConsoleRowHighlightingRule2 in new ColoredConsoleSystemPrinter().DefaultConsoleRowHighlightingRules) { coloredConsoleTarget.RowHighlightingRules.Add(defaultConsoleRowHighlightingRule2); } } return configBuilder.WriteTo(coloredConsoleTarget); } public static ISetupConfigurationTargetBuilder WriteToDebug(this ISetupConfigurationTargetBuilder configBuilder, Layout? layout = null) { DebugSystemTarget debugSystemTarget = new DebugSystemTarget(); if (layout != null) { debugSystemTarget.Layout = layout; } return configBuilder.WriteTo(debugSystemTarget); } [Conditional("DEBUG")] public static void WriteToDebugConditional(this ISetupConfigurationTargetBuilder configBuilder, Layout? layout = null) { configBuilder.WriteToDebug(layout); } public static ISetupConfigurationTargetBuilder WriteToFile(this ISetupConfigurationTargetBuilder configBuilder, Layout fileName, Layout? layout = null, Encoding? encoding = null, LineEndingMode? lineEnding = null, bool keepFileOpen = true, long archiveAboveSize = -1L, int maxArchiveFiles = -1, int maxArchiveDays = -1) { Guard.ThrowIfNull(fileName, "fileName"); FileTarget fileTarget = new FileTarget(); fileTarget.FileName = fileName; fileTarget.KeepFileOpen = keepFileOpen; if (layout != null) { fileTarget.Layout = layout; } if (encoding != null) { fileTarget.Encoding = encoding; } if ((object)lineEnding != null) { fileTarget.LineEnding = lineEnding; } if (archiveAboveSize > 0) { fileTarget.ArchiveAboveSize = archiveAboveSize; } if (maxArchiveFiles >= 0) { fileTarget.MaxArchiveFiles = maxArchiveFiles; } if (maxArchiveDays > 0) { fileTarget.MaxArchiveDays = maxArchiveDays; } return configBuilder.WriteTo(fileTarget); } public static ISetupConfigurationTargetBuilder WithWrapper(this ISetupConfigurationTargetBuilder configBuilder, Func wrapperFactory) { Guard.ThrowIfNull(wrapperFactory, "wrapperFactory"); IList targets = configBuilder.Targets; if (targets != null && targets.Count > 0) { for (int i = 0; i < targets.Count; i++) { Target target = targets[i]; Target target2 = wrapperFactory(target); if (target2 != null && target2 != target) { if (string.IsNullOrEmpty(target2.Name)) { target2.Name = EnsureUniqueTargetName(configBuilder.Configuration, target2, target.Name); } targets[i] = target2; configBuilder.Configuration.AddTarget(target2); } } return configBuilder; } throw new ArgumentException("Must call WriteTo(...) before applying target wrapper"); } public static ISetupConfigurationTargetBuilder WithAsync(this ISetupConfigurationTargetBuilder configBuilder, AsyncTargetWrapperOverflowAction overflowAction = AsyncTargetWrapperOverflowAction.Discard, int queueLimit = 10000, int batchSize = 200) { return configBuilder.WithWrapper(delegate(Target t) { if (t is AsyncTargetWrapper) { return null; } return (t is AsyncTaskTarget) ? null : new AsyncTargetWrapper { WrappedTarget = t, OverflowAction = overflowAction, QueueLimit = queueLimit, BatchSize = batchSize }; }); } public static ISetupConfigurationTargetBuilder WithBuffering(this ISetupConfigurationTargetBuilder configBuilder, int? bufferSize = null, TimeSpan? flushTimeout = null, bool? slidingTimeout = null, BufferingTargetWrapperOverflowAction? overflowAction = null) { return configBuilder.WithWrapper(delegate(Target t) { BufferingTargetWrapper bufferingTargetWrapper = new BufferingTargetWrapper { WrappedTarget = t }; if (bufferSize.HasValue) { bufferingTargetWrapper.BufferSize = bufferSize.Value; } if (flushTimeout.HasValue) { bufferingTargetWrapper.FlushTimeout = (int)flushTimeout.Value.TotalMilliseconds; } if (slidingTimeout.HasValue) { bufferingTargetWrapper.SlidingTimeout = slidingTimeout.Value; } if (overflowAction.HasValue) { bufferingTargetWrapper.OverflowAction = overflowAction.Value; } return bufferingTargetWrapper; }); } public static ISetupConfigurationTargetBuilder WithAutoFlush(this ISetupConfigurationTargetBuilder configBuilder, Func conditionMethod, bool? flushOnConditionOnly = null) { Func conditionMethod2 = conditionMethod; return configBuilder.WithWrapper(delegate(Target t) { AutoFlushTargetWrapper autoFlushTargetWrapper = new AutoFlushTargetWrapper { WrappedTarget = t }; ConditionMethodExpression condition = ConditionMethodExpression.CreateMethodNoParameters("AutoFlush", conditionMethod2); autoFlushTargetWrapper.Condition = condition; if (flushOnConditionOnly.HasValue) { autoFlushTargetWrapper.FlushOnConditionOnly = flushOnConditionOnly.Value; } return autoFlushTargetWrapper; }); } public static ISetupConfigurationTargetBuilder WithRetry(this ISetupConfigurationTargetBuilder configBuilder, int? retryCount = null, TimeSpan? retryDelay = null) { return configBuilder.WithWrapper(delegate(Target t) { RetryingTargetWrapper retryingTargetWrapper = new RetryingTargetWrapper { WrappedTarget = t }; if (retryCount.HasValue) { retryingTargetWrapper.RetryCount = retryCount.Value; } if (retryDelay.HasValue) { retryingTargetWrapper.RetryDelayMilliseconds = (int)retryDelay.Value.TotalMilliseconds; } return retryingTargetWrapper; }); } public static ISetupConfigurationTargetBuilder WithFallback(this ISetupConfigurationTargetBuilder configBuilder, Target fallbackTarget, bool returnToFirstOnSuccess = true) { Target fallbackTarget2 = fallbackTarget; ISetupConfigurationTargetBuilder configBuilder2 = configBuilder; Guard.ThrowIfNull(fallbackTarget2, "fallbackTarget"); if (string.IsNullOrEmpty(fallbackTarget2.Name)) { fallbackTarget2.Name = EnsureUniqueTargetName(configBuilder2.Configuration, fallbackTarget2, "_Fallback"); } return configBuilder2.WithWrapper(delegate(Target t) { FallbackGroupTarget result = new FallbackGroupTarget { ReturnToFirstOnSuccess = returnToFirstOnSuccess, Targets = { t, fallbackTarget2 } }; configBuilder2.Configuration.AddTarget(fallbackTarget2); return result; }); } private static string EnsureUniqueTargetName(LoggingConfiguration configuration, Target target, string suffix = "") { ReadOnlyCollection allTargets = configuration.AllTargets; string text = target.Name; if (string.IsNullOrEmpty(text)) { text = GenerateTargetName(target.GetType()); } if (!string.IsNullOrEmpty(suffix)) { text = text + "_" + suffix; } int num = 0; string text2 = text; while (!IsTargetNameUnique(allTargets, target, text2)) { string text3 = text; int num2 = ++num; text2 = text3 + "_" + num2.ToString(CultureInfo.InvariantCulture); } return text2; } private static bool IsTargetNameUnique(IList allTargets, Target target, string targetName) { for (int i = 0; i < allTargets.Count; i++) { Target target2 = allTargets[i]; if (target == target2) { return true; } if (string.CompareOrdinal(target2.Name, targetName) == 0) { return false; } } return true; } private static string GenerateTargetName(Type targetType) { string text = targetType.GetFirstCustomAttribute()?.Name ?? targetType.Name; if (string.IsNullOrEmpty(text)) { text = targetType.ToString(); } if (text.EndsWith("TargetWrapper", StringComparison.Ordinal)) { text = text.Substring(0, text.Length - 13); } if (text.EndsWith("Wrapper", StringComparison.Ordinal)) { text = text.Substring(0, text.Length - 7); } if (text.EndsWith("GroupTarget", StringComparison.Ordinal)) { text = text.Substring(0, text.Length - 12); } if (text.EndsWith("Group", StringComparison.Ordinal)) { text = text.Substring(0, text.Length - 5); } if (text.EndsWith("Target", StringComparison.Ordinal)) { text = text.Substring(0, text.Length - 6); } if (string.IsNullOrEmpty(text)) { text = "Unknown"; } return text; } } public static class SetupLogFactoryBuilderExtensions { public static ISetupLogFactoryBuilder SetTimeSource(this ISetupLogFactoryBuilder configBuilder, TimeSource timeSource) { TimeSource.Current = timeSource; return configBuilder; } public static ISetupLogFactoryBuilder SetTimeSourcAccurateUtc(this ISetupLogFactoryBuilder configBuilder) { return configBuilder.SetTimeSource(TimeSource.Current); } public static ISetupLogFactoryBuilder SetTimeSourcAccurateLocal(this ISetupLogFactoryBuilder configBuilder) { return configBuilder.SetTimeSource(TimeSource.Current); } public static ISetupLogFactoryBuilder SetGlobalContextProperty(this ISetupLogFactoryBuilder configBuilder, string name, object value) { GlobalDiagnosticsContext.Set(name, value); return configBuilder; } public static ISetupLogFactoryBuilder SetAutoShutdown(this ISetupLogFactoryBuilder configBuilder, bool enabled) { configBuilder.LogFactory.AutoShutdown = enabled; return configBuilder; } public static ISetupLogFactoryBuilder SetDefaultCultureInfo(this ISetupLogFactoryBuilder configBuilder, CultureInfo cultureInfo) { configBuilder.LogFactory.DefaultCultureInfo = cultureInfo; return configBuilder; } public static ISetupLogFactoryBuilder SetGlobalThreshold(this ISetupLogFactoryBuilder configBuilder, LogLevel logLevel) { configBuilder.LogFactory.GlobalThreshold = logLevel; return configBuilder; } public static ISetupLogFactoryBuilder SetThrowConfigExceptions(this ISetupLogFactoryBuilder configBuilder, bool enabled) { configBuilder.LogFactory.ThrowConfigExceptions = enabled; return configBuilder; } public static ISetupLogFactoryBuilder AddCallSiteHiddenAssembly(this ISetupLogFactoryBuilder configBuilder, Assembly assembly) { CallSiteInformation.AddCallSiteHiddenAssembly(assembly); return configBuilder; } public static ISetupLogFactoryBuilder AddCallSiteHiddenClassType(this ISetupLogFactoryBuilder configBuilder, Type type) { CallSiteInformation.AddCallSiteHiddenClassType(type); return configBuilder; } } public static class SetupSerializationBuilderExtensions { private sealed class ObjectTypeTransformation : IObjectTypeTransformer { private readonly IObjectTypeTransformer _original; private readonly Func _transformer; public ObjectTypeTransformation(Func transformer, IObjectTypeTransformer original) { _original = original; _transformer = transformer; } public object? TryTransformObject(object obj) { if (obj is T arg) { object obj2 = _transformer(arg); if (obj2 != null) { return obj2; } } return _original?.TryTransformObject(obj); } } private sealed class ObjectTypeTransformation : IObjectTypeTransformer { private readonly IObjectTypeTransformer _original; private readonly Func _transformer; private readonly Type _objectType; public ObjectTypeTransformation(Type objecType, Func transformer, IObjectTypeTransformer original) { _original = original; _transformer = transformer; _objectType = objecType; } public object? TryTransformObject(object obj) { if (_objectType.IsAssignableFrom(obj.GetType())) { return _transformer(obj); } return _original?.TryTransformObject(obj); } } public static ISetupSerializationBuilder ParseMessageTemplates(this ISetupSerializationBuilder setupBuilder, bool? enable) { setupBuilder.LogFactory.ServiceRepository.ParseMessageTemplates(setupBuilder.LogFactory, enable); return setupBuilder; } public static ISetupSerializationBuilder RegisterJsonConverter(this ISetupSerializationBuilder setupBuilder, IJsonConverter jsonConverter) { setupBuilder.LogFactory.ServiceRepository.RegisterJsonConverter(jsonConverter ?? new DefaultJsonSerializer(setupBuilder.LogFactory.ServiceRepository)); return setupBuilder; } public static ISetupSerializationBuilder RegisterValueFormatter(this ISetupSerializationBuilder setupBuilder, IValueFormatter valueFormatter) { setupBuilder.LogFactory.ServiceRepository.RegisterValueFormatter(valueFormatter ?? new ValueFormatter(setupBuilder.LogFactory.ServiceRepository, legacyStringQuotes: false)); return setupBuilder; } public static ISetupSerializationBuilder RegisterValueFormatterWithStringQuotes(this ISetupSerializationBuilder setupBuilder) { setupBuilder.LogFactory.ServiceRepository.RegisterValueFormatter(new ValueFormatter(setupBuilder.LogFactory.ServiceRepository, legacyStringQuotes: true)); return setupBuilder; } public static ISetupSerializationBuilder RegisterObjectTransformation<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(this ISetupSerializationBuilder setupBuilder) { Guard.ThrowIfNull(setupBuilder, "setupBuilder"); InternalLogger.Debug("RegisterObjectTransformation for {0} to keep public properties", typeof(T)); return setupBuilder; } public static ISetupSerializationBuilder RegisterObjectTransformation(this ISetupSerializationBuilder setupBuilder, Func transformer) { Guard.ThrowIfNull(transformer, "transformer"); InternalLogger.Debug("RegisterObjectTransformation for {0} to convert safely", typeof(T)); IObjectTypeTransformer service = setupBuilder.LogFactory.ServiceRepository.GetService(); setupBuilder.LogFactory.ServiceRepository.RegisterObjectTypeTransformer(new ObjectTypeTransformation(transformer, service)); return setupBuilder; } public static ISetupSerializationBuilder RegisterObjectTransformation(this ISetupSerializationBuilder setupBuilder, Type objectType, Func transformer) { Guard.ThrowIfNull(objectType, "objectType"); Guard.ThrowIfNull(transformer, "transformer"); IObjectTypeTransformer service = setupBuilder.LogFactory.ServiceRepository.GetService(); setupBuilder.LogFactory.ServiceRepository.RegisterObjectTypeTransformer(new ObjectTypeTransformation(objectType, transformer, service)); return setupBuilder; } } } namespace NLog.Time { [TimeSource("AccurateLocal")] public sealed class AccurateLocalTimeSource : TimeSource { public override DateTime Time => DateTime.Now; public override DateTime FromSystemTime(DateTime systemTime) { return systemTime.ToLocalTime(); } } [TimeSource("AccurateUTC")] public sealed class AccurateUtcTimeSource : TimeSource { public override DateTime Time => DateTime.UtcNow; public override DateTime FromSystemTime(DateTime systemTime) { return systemTime.ToUniversalTime(); } } public abstract class CachedTimeSource : TimeSource { private int _lastTicks = -1; private DateTime _lastTime = DateTime.MinValue; protected abstract DateTime FreshTime { get; } public override DateTime Time { get { int tickCount = Environment.TickCount; if (tickCount != _lastTicks) { return RetrieveFreshTime(tickCount); } return _lastTime; } } private DateTime RetrieveFreshTime(int tickCount) { DateTime result = (_lastTime = FreshTime); Thread.MemoryBarrier(); _lastTicks = tickCount; return result; } } [TimeSource("FastLocal")] public sealed class FastLocalTimeSource : CachedTimeSource { protected override DateTime FreshTime => DateTime.Now; public override DateTime FromSystemTime(DateTime systemTime) { return systemTime.ToLocalTime(); } } [TimeSource("FastUTC")] public sealed class FastUtcTimeSource : CachedTimeSource { protected override DateTime FreshTime => DateTime.UtcNow; public override DateTime FromSystemTime(DateTime systemTime) { return systemTime.ToUniversalTime(); } } [NLogConfigurationItem] public abstract class TimeSource { public abstract DateTime Time { get; } public static TimeSource Current { get; set; } = new FastLocalTimeSource(); public override string ToString() { TimeSourceAttribute firstCustomAttribute = GetType().GetFirstCustomAttribute(); if (firstCustomAttribute != null) { return firstCustomAttribute.Name + " (time source)"; } return GetType().Name; } public abstract DateTime FromSystemTime(DateTime systemTime); } [AttributeUsage(AttributeTargets.Class)] public sealed class TimeSourceAttribute : NameBaseAttribute { public TimeSourceAttribute(string name) : base(name) { } } } namespace NLog.Targets { public abstract class AsyncTaskTarget : TargetWithContext { private readonly Timer _taskTimeoutTimer; private CancellationTokenSource _cancelTokenSource; private AsyncRequestQueueBase _requestQueue; private readonly Action _taskCancelledTokenReInit; private readonly Action _taskCompletion; private Task? _previousTask; private readonly Timer _lazyWriterTimer; private readonly LogEventInfo _flushEvent = LogEventInfo.Create(LogLevel.Off, null, "NLog Async Task Flush Event"); private readonly ReusableAsyncLogEventList _reusableAsyncLogEventList = new ReusableAsyncLogEventList(200); private Tuple, List>? _reusableLogEvents; private WaitCallback? _flushEventsInQueueDelegate; private bool _missingServiceTypes; private int? _retryDelayMilliseconds; private bool? _forceLockingQueue; public int TaskDelayMilliseconds { get; set; } = 1; public int TaskTimeoutSeconds { get; set; } = 150; public int RetryCount { get; set; } public int RetryDelayMilliseconds { get { int? retryDelayMilliseconds = _retryDelayMilliseconds; if (!retryDelayMilliseconds.HasValue) { if (RetryCount <= 0 && OverflowAction == AsyncTargetWrapperOverflowAction.Discard) { return 50; } return 500; } return retryDelayMilliseconds.GetValueOrDefault(); } set { _retryDelayMilliseconds = value; } } public bool ForceLockingQueue { get { return _forceLockingQueue.GetValueOrDefault(); } set { _forceLockingQueue = value; } } public AsyncTargetWrapperOverflowAction OverflowAction { get { return _requestQueue.OnOverflow; } set { _requestQueue.OnOverflow = value; } } public int QueueLimit { get { return _requestQueue.QueueLimit; } set { _requestQueue.QueueLimit = value; } } public int BatchSize { get; set; } = 1; protected virtual TaskScheduler TaskScheduler => System.Threading.Tasks.TaskScheduler.Default; protected AsyncTaskTarget() { _taskCompletion = TaskCompletion; _taskCancelledTokenReInit = delegate { TaskCancelledTokenReInit(out CancellationTokenSource _); }; _taskTimeoutTimer = new Timer(TaskTimeout, null, -1, -1); _requestQueue = new ConcurrentRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); _lazyWriterTimer = new Timer(delegate { TaskStartNext(null, fullBatchCompleted: false); }, null, -1, -1); TaskCancelledTokenReInit(out _cancelTokenSource); } protected override void InitializeTarget() { _missingServiceTypes = false; TaskCancelledTokenReInit(out CancellationTokenSource _); base.InitializeTarget(); if (BatchSize <= 0) { BatchSize = 1; } if (!ForceLockingQueue && OverflowAction == AsyncTargetWrapperOverflowAction.Block && (decimal)BatchSize * 1.5m > (decimal)QueueLimit) { ForceLockingQueue = true; } if (_forceLockingQueue.HasValue && _forceLockingQueue.Value != _requestQueue is AsyncRequestQueue) { _requestQueue = (ForceLockingQueue ? ((AsyncRequestQueueBase)new AsyncRequestQueue(QueueLimit, OverflowAction)) : ((AsyncRequestQueueBase)new ConcurrentRequestQueue(QueueLimit, OverflowAction))); } if (BatchSize > QueueLimit) { BatchSize = QueueLimit; } } protected abstract Task WriteAsyncTask(LogEventInfo logEvent, CancellationToken cancellationToken); protected virtual Task WriteAsyncTask(IList logEvents, CancellationToken cancellationToken) { if (logEvents.Count == 1) { return WriteAsyncTask(logEvents[0], cancellationToken); } Task task = null; for (int i = 0; i < logEvents.Count; i++) { LogEventInfo logEvent = logEvents[i]; task = ((task != null) ? task.ContinueWith((Task t) => WriteAsyncTask(logEvent, cancellationToken), cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler).Unwrap() : WriteAsyncTask(logEvent, cancellationToken)); } return task ?? Task.CompletedTask; } protected virtual bool RetryFailedAsyncTask(Exception exception, CancellationToken cancellationToken, int retryCountRemaining, out TimeSpan retryDelay) { if (cancellationToken.IsCancellationRequested || retryCountRemaining < 0) { retryDelay = TimeSpan.Zero; return false; } retryDelay = TimeSpan.FromMilliseconds((double)RetryDelayMilliseconds * Math.Pow(2.0, RetryCount - (1 + retryCountRemaining))); return true; } protected sealed override void Write(LogEventInfo logEvent) { base.Write(logEvent); } protected sealed override void Write(IList logEvents) { base.Write(logEvents); } protected sealed override void Write(AsyncLogEventInfo logEvent) { if (_cancelTokenSource.IsCancellationRequested) { logEvent.Continuation(null); return; } PrecalculateVolatileLayouts(logEvent.LogEvent); if (!_requestQueue.Enqueue(logEvent)) { return; } bool lockTaken = false; try { if (_previousTask == null) { Monitor.Enter(base.SyncRoot, ref lockTaken); } else { Monitor.TryEnter(base.SyncRoot, 50, ref lockTaken); } if (_previousTask == null) { _lazyWriterTimer.Change(TaskDelayMilliseconds, -1); } } finally { if (lockTaken) { Monitor.Exit(base.SyncRoot); } } } protected sealed override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { try { Write(logEvent); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "WriteAsyncThreadSafe")) { throw; } logEvent.Continuation(exception); } } protected sealed override void WriteAsyncThreadSafe(IList logEvents) { base.WriteAsyncThreadSafe(logEvents); } protected override void WriteFailedNotInitialized(AsyncLogEventInfo logEvent, Exception initializeException) { if (initializeException is NLogDependencyResolveException && OverflowAction == AsyncTargetWrapperOverflowAction.Discard) { _missingServiceTypes = true; Write(logEvent); } else { base.WriteFailedNotInitialized(logEvent, initializeException); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { Task? previousTask = _previousTask; if ((previousTask != null && !previousTask.IsCompleted) || !_requestQueue.IsEmpty) { InternalLogger.Debug("{0}: Flushing {1}", this, _requestQueue.IsEmpty ? "empty queue" : "pending queue items"); if (_requestQueue.OnOverflow != AsyncTargetWrapperOverflowAction.Block) { _requestQueue.Enqueue(new AsyncLogEventInfo(_flushEvent, asyncContinuation)); _lazyWriterTimer.Change(0, -1); return; } if (_flushEventsInQueueDelegate == null) { _flushEventsInQueueDelegate = delegate(object cont) { _requestQueue.Enqueue(new AsyncLogEventInfo(_flushEvent, (AsyncContinuation)cont)); lock (base.SyncRoot) { _lazyWriterTimer.Change(0, -1); } }; } AsyncHelpers.StartAsyncTask(_flushEventsInQueueDelegate, asyncContinuation); _lazyWriterTimer.Change(0, -1); } else { InternalLogger.Debug("{0}: Flushing Nothing", this); asyncContinuation(null); } } protected override void CloseTarget() { _taskTimeoutTimer.Change(-1, -1); _cancelTokenSource.Cancel(); _requestQueue.Clear(); _previousTask = null; base.CloseTarget(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _cancelTokenSource.Dispose(); _taskTimeoutTimer.WaitForDispose(TimeSpan.Zero); _lazyWriterTimer.WaitForDispose(TimeSpan.Zero); } } private void TaskStartNext(object? previousTask, bool fullBatchCompleted) { do { lock (base.SyncRoot) { if (CheckOtherTask(previousTask)) { break; } if (_missingServiceTypes) { _previousTask = null; _lazyWriterTimer.Change(50, -1); break; } if (!base.IsInitialized) { _previousTask = null; break; } if (previousTask != null && !fullBatchCompleted && TaskDelayMilliseconds >= 50 && !_requestQueue.IsEmpty) { InternalLogger.Trace("{0}: Throttle to optimize batching", this); _previousTask = null; _lazyWriterTimer.Change(TaskDelayMilliseconds, -1); break; } ReusableObjectCreator>.LockOject lockOject = _reusableAsyncLogEventList.Allocate(); try { IList result = lockOject.Result; _requestQueue.DequeueBatch(BatchSize, result); if (result.Count > 0) { if (TaskCreation(result)) { break; } continue; } _previousTask = null; break; } finally { ((IDisposable)lockOject).Dispose(); } } } while (!_requestQueue.IsEmpty || previousTask != null); } private bool CheckOtherTask(object? previousTask) { if (previousTask == null) { Task? previousTask2 = _previousTask; if (previousTask2 != null && !previousTask2.IsCompleted) { return true; } } else if (_previousTask != null && previousTask != _previousTask) { return true; } return false; } internal Task WriteAsyncTaskWithRetry(Task firstTask, IList logEvents, CancellationToken cancellationToken, int retryCount) { IList logEvents2 = logEvents; TaskCompletionSource tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); return firstTask.ContinueWith(delegate(Task t) { if (t.IsFaulted || t.IsCanceled) { if (t.Exception != null) { tcs.TrySetException(t.Exception); } Exception ex = ExtractActualException(t.Exception) ?? new TaskCanceledException("Task failed without exception"); if (RetryFailedAsyncTask(ex, cancellationToken, retryCount - 1, out var retryDelay)) { InternalLogger.Warn(ex, "{0}: Write operation failed. {1} attempts left. Sleep {2} ms", new ReadOnlySpan(new object[3] { this, retryCount, retryDelay.TotalMilliseconds })); AsyncHelpers.WaitForDelay(retryDelay); if (!cancellationToken.IsCancellationRequested) { Task task; lock (base.SyncRoot) { task = StartWriteAsyncTask(logEvents2, cancellationToken); } if (task != null) { return WriteAsyncTaskWithRetry(task, logEvents2, cancellationToken, retryCount - 1); } } } InternalLogger.Warn(ex, "{0}: Write operation failed after {1} retries", new ReadOnlySpan(new object[2] { this, RetryCount - retryCount })); } else { tcs.SetResult(null); } return tcs.Task; }, cancellationToken, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler).Unwrap(); } private bool TaskCreation(IList logEvents) { Tuple, List> tuple = null; try { if (_cancelTokenSource.IsCancellationRequested) { for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(null); } return false; } tuple = Interlocked.CompareExchange(ref _reusableLogEvents, null, _reusableLogEvents) ?? Tuple.Create(new List(), new List()); for (int j = 0; j < logEvents.Count; j++) { if (logEvents[j].LogEvent == _flushEvent) { tuple.Item2.Add(logEvents[j].Continuation); continue; } tuple.Item1.Add(logEvents[j].LogEvent); tuple.Item2.Add(logEvents[j].Continuation); } if (tuple.Item1.Count == 0) { NotifyTaskCompletion(tuple.Item2, null); tuple.Item2.Clear(); Interlocked.CompareExchange(ref _reusableLogEvents, tuple, null); InternalLogger.Debug("{0}: Flush Completed", this); return false; } Task task = StartWriteAsyncTask(tuple.Item1, _cancelTokenSource.Token); if (task == null) { InternalLogger.Debug("{0}: WriteAsyncTask returned null", this); NotifyTaskCompletion(tuple.Item2, null); return false; } if (RetryCount > 0) { task = WriteAsyncTaskWithRetry(task, tuple.Item1, _cancelTokenSource.Token, RetryCount); } _previousTask = task; if (TaskTimeoutSeconds > 0) { _taskTimeoutTimer.Change(TaskTimeoutSeconds * 1000, -1); } task.ContinueWith(_taskCompletion, tuple, TaskScheduler); return true; } catch (Exception ex) { _previousTask = null; InternalLogger.Error(ex, "{0}: WriteAsyncTask failed on creation", new ReadOnlySpan(new object[1] { this })); IList list = tuple?.Item2; NotifyTaskCompletion(list ?? ArrayHelper.Empty(), ex); } return false; } private Task StartWriteAsyncTask(IList logEvents, CancellationToken cancellationToken) { try { InternalLogger.Trace("{0}: Writing {1} events", this, logEvents.Count); Task task = WriteAsyncTask(logEvents, cancellationToken); if (task == null) { return Task.CompletedTask; } if (task.Status == TaskStatus.Created) { task.Start(TaskScheduler); } return task; } catch (Exception ex) { InternalLogger.Error(ex, "{0}: WriteAsyncTask failed on creation", new ReadOnlySpan(new object[1] { this })); return Task.FromException(ex); } } private static void NotifyTaskCompletion(IList reusableContinuations, Exception? ex) { try { for (int i = 0; i < reusableContinuations.Count; i++) { reusableContinuations[i](ex); } } catch { } } private void TaskCompletion(Task completedTask, object? continuation) { bool flag = true; bool fullBatchCompleted = true; TimeSpan retryDelay = TimeSpan.Zero; try { if (completedTask == _previousTask) { if (TaskTimeoutSeconds > 0) { _taskTimeoutTimer.Change(-1, -1); } } else { flag = false; if (!base.IsInitialized) { return; } } Exception ex = ExtractActualException(completedTask.Exception); if (completedTask.IsCanceled) { flag = false; if (completedTask.Exception != null) { InternalLogger.Warn(completedTask.Exception, "{0}: WriteAsyncTask was cancelled", new ReadOnlySpan(new object[1] { this })); } else { InternalLogger.Info("{0}: WriteAsyncTask was cancelled", this); } } else if (ex != null) { flag = false; if (RetryCount <= 0) { if (RetryFailedAsyncTask(ex, CancellationToken.None, 0, out retryDelay)) { InternalLogger.Warn(ex, "{0}: WriteAsyncTask failed on completion. Delay {1} ms", new ReadOnlySpan(new object[2] { this, retryDelay.TotalMilliseconds })); } } else { InternalLogger.Warn(ex, "{0}: WriteAsyncTask failed on completion", new ReadOnlySpan(new object[1] { this })); } } Tuple, List> tuple = continuation as Tuple, List>; if (tuple != null) { NotifyTaskCompletion(tuple.Item2, ex); } else { flag = false; } if (flag && tuple != null) { fullBatchCompleted = tuple.Item2.Count * 2 > BatchSize; tuple.Item1.Clear(); tuple.Item2.Clear(); Interlocked.CompareExchange(ref _reusableLogEvents, tuple, null); } } finally { if (retryDelay > TimeSpan.Zero) { _lazyWriterTimer.Change((int)retryDelay.TotalMilliseconds, -1); } else { TaskStartNext(completedTask, fullBatchCompleted); } } } private void TaskTimeout(object? state) { try { if (!base.IsInitialized) { return; } InternalLogger.Warn("{0}: WriteAsyncTask had timeout. Task will be cancelled.", this); Task task = _previousTask; try { lock (base.SyncRoot) { if (task != null && task == _previousTask) { _previousTask = null; _cancelTokenSource.Cancel(); } else { task = null; } } if (task != null) { if (!WaitTaskIsCompleted(task, TimeSpan.FromSeconds((double)TaskTimeoutSeconds / 10.0))) { InternalLogger.Debug("{0}: WriteAsyncTask had timeout. Task did not cancel properly: {1}.", this, task.Status); } Exception ex = ExtractActualException(task.Exception); RetryFailedAsyncTask(ex ?? new TimeoutException("WriteAsyncTask had timeout"), CancellationToken.None, 0, out var _); } } catch (Exception ex2) { InternalLogger.Debug(ex2, "{0}: WriteAsyncTask had timeout. Task failed to cancel properly.", new ReadOnlySpan(new object[1] { this })); } TaskStartNext(null, fullBatchCompleted: false); } catch (Exception ex3) { InternalLogger.Error(ex3, "{0}: WriteAsyncTask failed on timeout", new ReadOnlySpan(new object[1] { this })); } } private static bool WaitTaskIsCompleted(Task task, TimeSpan timeout) { while (!task.IsCompleted && timeout > TimeSpan.Zero) { timeout -= TimeSpan.FromMilliseconds(10.0); AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(10.0)); } return task.IsCompleted; } private static Exception? ExtractActualException(AggregateException? taskException) { if (taskException != null && (taskException.InnerExceptions?.Count).GetValueOrDefault() == 1 && !(taskException.InnerExceptions[0] is AggregateException)) { return taskException.InnerExceptions[0]; } ReadOnlyCollection readOnlyCollection = taskException?.Flatten()?.InnerExceptions; if (readOnlyCollection == null || readOnlyCollection.Count != 1) { return taskException; } return readOnlyCollection[0]; } private void TaskCancelledTokenReInit(out CancellationTokenSource cancelTokenSource) { _cancelTokenSource = (cancelTokenSource = new CancellationTokenSource()); _cancelTokenSource.Token.Register(_taskCancelledTokenReInit); } } internal sealed class ColoredConsoleAnsiPrinter : IColoredConsolePrinter { private static string TerminalDefaultForegroundColorEscapeCode => "\u001b[39m\u001b[22m"; private static string TerminalDefaultBackgroundColorEscapeCode => "\u001b[49m"; private static string TerminalDefaultColorEscapeCode => "\u001b[0m"; public IList DefaultConsoleRowHighlightingRules { get; } = new List { new ConsoleRowHighlightingRule(ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Fatal", (LogEventInfo evt) => evt.Level == LogLevel.Fatal), ConsoleOutputColor.DarkRed, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule(ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Error", (LogEventInfo evt) => evt.Level == LogLevel.Error), ConsoleOutputColor.DarkRed, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule(ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Warn", (LogEventInfo evt) => evt.Level == LogLevel.Warn), ConsoleOutputColor.DarkYellow, ConsoleOutputColor.NoChange) }; public TextWriter AcquireTextWriter(TextWriter consoleStream, StringBuilder reusableBuilder) { return new StringWriter(reusableBuilder ?? new StringBuilder(50), consoleStream.FormatProvider); } public void ReleaseTextWriter(TextWriter consoleWriter, TextWriter consoleStream, ConsoleColor? oldForegroundColor, ConsoleColor? oldBackgroundColor, bool flush) { StringBuilder stringBuilder = (consoleWriter as StringWriter)?.GetStringBuilder(); if (stringBuilder != null) { stringBuilder.Append(TerminalDefaultColorEscapeCode); ConsoleTargetHelper.WriteLineThreadSafe(consoleStream, stringBuilder.ToString(), flush); } } public ConsoleColor? ChangeForegroundColor(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? oldForegroundColor = null) { if (foregroundColor.HasValue) { consoleWriter.Write(GetForegroundColorEscapeCode(foregroundColor.Value)); } return null; } public ConsoleColor? ChangeBackgroundColor(TextWriter consoleWriter, ConsoleColor? backgroundColor, ConsoleColor? oldBackgroundColor = null) { if (backgroundColor.HasValue) { consoleWriter.Write(GetBackgroundColorEscapeCode(backgroundColor.Value)); } return null; } public void ResetDefaultColors(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? backgroundColor) { consoleWriter.Write(TerminalDefaultColorEscapeCode); } public void WriteSubString(TextWriter consoleWriter, string text, int index, int endIndex) { consoleWriter.Write(text.AsSpan(index, endIndex - index)); } public void WriteChar(TextWriter consoleWriter, char text) { consoleWriter.Write(text); } public void WriteLine(TextWriter consoleWriter, string text) { consoleWriter.Write(text); } private static string GetForegroundColorEscapeCode(ConsoleColor color) { return color switch { ConsoleColor.Black => "\u001b[30m", ConsoleColor.Blue => "\u001b[94m", ConsoleColor.Cyan => "\u001b[96m", ConsoleColor.DarkBlue => "\u001b[34m", ConsoleColor.DarkCyan => "\u001b[36m", ConsoleColor.DarkGray => "\u001b[90m", ConsoleColor.DarkGreen => "\u001b[32m", ConsoleColor.DarkMagenta => "\u001b[35m", ConsoleColor.DarkRed => "\u001b[31m", ConsoleColor.DarkYellow => "\u001b[33m", ConsoleColor.Gray => "\u001b[37m", ConsoleColor.Green => "\u001b[92m", ConsoleColor.Magenta => "\u001b[95m", ConsoleColor.Red => "\u001b[91m", ConsoleColor.White => "\u001b[97m", ConsoleColor.Yellow => "\u001b[93m", _ => TerminalDefaultForegroundColorEscapeCode, }; } private static string GetBackgroundColorEscapeCode(ConsoleColor color) { return color switch { ConsoleColor.Black => "\u001b[40m", ConsoleColor.Blue => "\u001b[104m", ConsoleColor.Cyan => "\u001b[106m", ConsoleColor.DarkBlue => "\u001b[44m", ConsoleColor.DarkCyan => "\u001b[46m", ConsoleColor.DarkGray => "\u001b[100m", ConsoleColor.DarkGreen => "\u001b[42m", ConsoleColor.DarkMagenta => "\u001b[45m", ConsoleColor.DarkRed => "\u001b[41m", ConsoleColor.DarkYellow => "\u001b[43m", ConsoleColor.Gray => "\u001b[47m", ConsoleColor.Green => "\u001b[102m", ConsoleColor.Magenta => "\u001b[105m", ConsoleColor.Red => "\u001b[101m", ConsoleColor.White => "\u001b[107m", ConsoleColor.Yellow => "\u001b[103m", _ => TerminalDefaultBackgroundColorEscapeCode, }; } } internal sealed class ColoredConsoleSystemPrinter : IColoredConsolePrinter { public IList DefaultConsoleRowHighlightingRules { get; } = new List { new ConsoleRowHighlightingRule(ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Fatal", (LogEventInfo evt) => evt.Level == LogLevel.Fatal), ConsoleOutputColor.Red, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule(ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Error", (LogEventInfo evt) => evt.Level == LogLevel.Error), ConsoleOutputColor.Red, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule(ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Warn", (LogEventInfo evt) => evt.Level == LogLevel.Warn), ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule(ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Info", (LogEventInfo evt) => evt.Level == LogLevel.Info), ConsoleOutputColor.White, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule(ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Debug", (LogEventInfo evt) => evt.Level == LogLevel.Debug), ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange), new ConsoleRowHighlightingRule(ConditionMethodExpression.CreateMethodNoParameters("level == LogLevel.Trace", (LogEventInfo evt) => evt.Level == LogLevel.Trace), ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange) }; public TextWriter AcquireTextWriter(TextWriter consoleStream, StringBuilder reusableBuilder) { return consoleStream; } public void ReleaseTextWriter(TextWriter consoleWriter, TextWriter consoleStream, ConsoleColor? oldForegroundColor, ConsoleColor? oldBackgroundColor, bool flush) { ResetDefaultColors(consoleWriter, oldForegroundColor, oldBackgroundColor); if (flush) { consoleWriter.Flush(); } } public ConsoleColor? ChangeForegroundColor(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? oldForegroundColor = null) { ConsoleColor consoleColor = oldForegroundColor ?? Console.ForegroundColor; if (foregroundColor.HasValue && consoleColor != foregroundColor.Value) { Console.ForegroundColor = foregroundColor.Value; } return consoleColor; } public ConsoleColor? ChangeBackgroundColor(TextWriter consoleWriter, ConsoleColor? backgroundColor, ConsoleColor? oldBackgroundColor = null) { ConsoleColor consoleColor = oldBackgroundColor ?? Console.BackgroundColor; if (backgroundColor.HasValue && consoleColor != backgroundColor.Value) { Console.BackgroundColor = backgroundColor.Value; } return consoleColor; } public void ResetDefaultColors(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? backgroundColor) { if (foregroundColor.HasValue) { Console.ForegroundColor = foregroundColor.Value; } if (backgroundColor.HasValue) { Console.BackgroundColor = backgroundColor.Value; } } public void WriteSubString(TextWriter consoleWriter, string text, int index, int endIndex) { consoleWriter.Write(text.AsSpan(index, endIndex - index)); } public void WriteChar(TextWriter consoleWriter, char text) { consoleWriter.Write(text); } public void WriteLine(TextWriter consoleWriter, string text) { consoleWriter.WriteLine(text); } } [Target("ColoredConsole")] public sealed class ColoredConsoleTarget : TargetWithLayoutHeaderAndFooter { private readonly Func _resolveConsoleStream; private bool _pauseLogging; private bool _disableColors; private IColoredConsolePrinter _consolePrinter; private Encoding? _encoding; [Obsolete("Replaced by StdErr to align with ConsoleTarget. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool ErrorStream { get { Layout? stdErr = StdErr; if (stdErr != null && stdErr.IsFixed) { return StdErr.FixedValue; } return false; } set { StdErr = value; } } public Layout? StdErr { get; set; } public bool UseDefaultRowHighlightingRules { get; set; } = true; public Encoding Encoding { get { return ConsoleTargetHelper.GetConsoleOutputEncoding(_encoding, base.IsInitialized, _pauseLogging); } set { if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, base.IsInitialized, _pauseLogging)) { _encoding = value; } } } public bool DetectConsoleAvailable { get; set; } public bool DetectOutputRedirected { get; set; } public bool AutoFlush { get; set; } public bool EnableAnsiOutput { get; set; } public Layout NoColor { get; set; } = Layout.FromMethod((LogEventInfo evt) => new string[2] { "1", "TRUE" }.Contains(EnvironmentHelper.GetSafeEnvironmentVariable("NO_COLOR")?.Trim().ToUpper())); [ArrayParameter(typeof(ConsoleRowHighlightingRule), "highlight-row")] public IList RowHighlightingRules { get; } = new List(); [ArrayParameter(typeof(ConsoleWordHighlightingRule), "highlight-word")] public IList WordHighlightingRules { get; } = new List(); public ColoredConsoleTarget() { _consolePrinter = CreateConsolePrinter(EnableAnsiOutput); _resolveConsoleStream = GetOutputStream; } public ColoredConsoleTarget(string name) : this() { base.Name = name; } internal ColoredConsoleTarget(Func resolveConsoleStream) : this() { _resolveConsoleStream = Guard.ThrowIfNull(resolveConsoleStream, "resolveConsoleStream"); } protected override void InitializeTarget() { _pauseLogging = false; _disableColors = false; if (DetectConsoleAvailable) { _pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out string reason); if (_pauseLogging) { InternalLogger.Info("{0}: Console detected as turned off. Set DetectConsoleAvailable=false to skip detection. Reason: {1}", this, reason); } } if (_encoding != null) { ConsoleTargetHelper.SetConsoleOutputEncoding(_encoding, isInitialized: true, _pauseLogging); } if (DetectOutputRedirected) { try { bool flag = RenderLogEvent(StdErr, LogEventInfo.CreateNullEvent(), defaultValue: false); _disableColors = (flag ? Console.IsErrorRedirected : Console.IsOutputRedirected); if (_disableColors) { InternalLogger.Info("{0}: Console output is redirected so no colors. Set DetectOutputRedirected=false to skip detection.", this); if (!AutoFlush && _resolveConsoleStream(flag) is StreamWriter streamWriter && !streamWriter.AutoFlush) { AutoFlush = true; } } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed checking if Console Output Redirected.", new ReadOnlySpan(new object[1] { this })); } } if (!_disableColors) { Layout noColor = NoColor; if (noColor != null && noColor.RenderValue(LogEventInfo.CreateNullEvent(), defaultValue: false)) { _disableColors = true; InternalLogger.Info("{0}: Environment with NO_COLOR, so colors are disabled. Set NoColor=false to skip detection.", this); } } base.InitializeTarget(); if (base.Header != null) { LogEventInfo logEvent = LogEventInfo.CreateNullEvent(); WriteToOutput(logEvent, RenderLogEvent(base.Header, logEvent)); } _consolePrinter = CreateConsolePrinter(EnableAnsiOutput); } private static IColoredConsolePrinter CreateConsolePrinter(bool enableAnsiOutput) { if (!enableAnsiOutput) { return new ColoredConsoleSystemPrinter(); } return new ColoredConsoleAnsiPrinter(); } protected override void CloseTarget() { if (base.Footer != null) { LogEventInfo logEvent = LogEventInfo.CreateNullEvent(); WriteToOutput(logEvent, RenderLogEvent(base.Footer, logEvent)); } ExplicitConsoleFlush(); base.CloseTarget(); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { ExplicitConsoleFlush(); base.FlushAsync(asyncContinuation); } catch (Exception exception) { asyncContinuation(exception); } } private void ExplicitConsoleFlush() { if (!_pauseLogging && !AutoFlush) { Layout? stdErr = StdErr; if (stdErr == null || stdErr.IsFixed) { bool arg = StdErr?.FixedValue ?? false; _resolveConsoleStream(arg).Flush(); } else { _resolveConsoleStream(arg: false).Flush(); _resolveConsoleStream(arg: true).Flush(); } } } protected override void Write(LogEventInfo logEvent) { if (!_pauseLogging) { WriteToOutput(logEvent, RenderLogEvent(Layout, logEvent)); } } private void WriteToOutput(LogEventInfo logEvent, string message) { try { WriteToOutputWithColor(logEvent, message ?? string.Empty); } catch (Exception ex) when (ex is OverflowException || ex is IndexOutOfRangeException || ex is ArgumentOutOfRangeException) { _pauseLogging = true; InternalLogger.Warn(ex, "{0}: {1} has been thrown and this is probably due to a race condition.Logging to the console will be paused. Enable by reloading the config or re-initialize the targets", new ReadOnlySpan(new object[2] { this, ex.GetType() })); } } private void WriteToOutputWithColor(LogEventInfo logEvent, string message) { string text = message; ConsoleColor? newForegroundColor = null; ConsoleColor? newBackgroundColor = null; if (!_disableColors) { ConsoleRowHighlightingRule matchingRowHighlightingRule = GetMatchingRowHighlightingRule(logEvent); if (WordHighlightingRules.Count > 0) { text = GenerateColorEscapeSequences(logEvent, message); } newForegroundColor = ((matchingRowHighlightingRule.ForegroundColor != ConsoleOutputColor.NoChange) ? new ConsoleColor?((ConsoleColor)matchingRowHighlightingRule.ForegroundColor) : null); newBackgroundColor = ((matchingRowHighlightingRule.BackgroundColor != ConsoleOutputColor.NoChange) ? new ConsoleColor?((ConsoleColor)matchingRowHighlightingRule.BackgroundColor) : null); } bool arg = RenderLogEvent(StdErr, logEvent, defaultValue: false); TextWriter textWriter = _resolveConsoleStream(arg); if ((object)text == message && !newForegroundColor.HasValue && !newBackgroundColor.HasValue) { ConsoleTargetHelper.WriteLineThreadSafe(textWriter, message, AutoFlush); return; } bool flag = (object)text != message; if (!flag && message.IndexOf('\n') >= 0) { flag = true; text = EscapeColorCodes(message); } WriteToOutputWithPrinter(textWriter, text, newForegroundColor, newBackgroundColor, flag); } private void WriteToOutputWithPrinter(TextWriter consoleStream, string colorMessage, ConsoleColor? newForegroundColor, ConsoleColor? newBackgroundColor, bool wordHighlighting) { ReusableObjectCreator.LockOject lockOject = ReusableLayoutBuilder.Allocate(); try { TextWriter consoleWriter = _consolePrinter.AcquireTextWriter(consoleStream, lockOject.Result); ConsoleColor? consoleColor = null; ConsoleColor? consoleColor2 = null; try { if (wordHighlighting) { consoleColor = _consolePrinter.ChangeForegroundColor(consoleWriter, newForegroundColor); consoleColor2 = _consolePrinter.ChangeBackgroundColor(consoleWriter, newBackgroundColor); ConsoleColor? rowForegroundColor = newForegroundColor ?? consoleColor; ConsoleColor? rowBackgroundColor = newBackgroundColor ?? consoleColor2; ColorizeEscapeSequences(_consolePrinter, consoleWriter, colorMessage, consoleColor, consoleColor2, rowForegroundColor, rowBackgroundColor); _consolePrinter.WriteLine(consoleWriter, string.Empty); return; } if (newForegroundColor.HasValue) { consoleColor = _consolePrinter.ChangeForegroundColor(consoleWriter, newForegroundColor.Value); if (consoleColor == newForegroundColor) { consoleColor = null; } } if (newBackgroundColor.HasValue) { consoleColor2 = _consolePrinter.ChangeBackgroundColor(consoleWriter, newBackgroundColor.Value); if (consoleColor2 == newBackgroundColor) { consoleColor2 = null; } } _consolePrinter.WriteLine(consoleWriter, colorMessage); } finally { _consolePrinter.ReleaseTextWriter(consoleWriter, consoleStream, consoleColor, consoleColor2, AutoFlush); } } finally { ((IDisposable)lockOject).Dispose(); } } private ConsoleRowHighlightingRule GetMatchingRowHighlightingRule(LogEventInfo logEvent) { ConsoleRowHighlightingRule matchingRowHighlightingRule = GetMatchingRowHighlightingRule(RowHighlightingRules, logEvent); if (matchingRowHighlightingRule == null && UseDefaultRowHighlightingRules) { matchingRowHighlightingRule = GetMatchingRowHighlightingRule(_consolePrinter.DefaultConsoleRowHighlightingRules, logEvent); } return matchingRowHighlightingRule ?? ConsoleRowHighlightingRule.Default; } private static ConsoleRowHighlightingRule? GetMatchingRowHighlightingRule(IList rules, LogEventInfo logEvent) { for (int i = 0; i < rules.Count; i++) { ConsoleRowHighlightingRule consoleRowHighlightingRule = rules[i]; if (consoleRowHighlightingRule.CheckCondition(logEvent)) { return consoleRowHighlightingRule; } } return null; } private string GenerateColorEscapeSequences(LogEventInfo logEvent, string message) { if (string.IsNullOrEmpty(message)) { return message; } message = EscapeColorCodes(message); ReusableObjectCreator.LockOject lockOject = ReusableLayoutBuilder.Allocate(); try { StringBuilder stringBuilder = lockOject.Result; for (int i = 0; i < WordHighlightingRules.Count; i++) { ConsoleWordHighlightingRule consoleWordHighlightingRule = WordHighlightingRules[i]; if (!consoleWordHighlightingRule.CheckCondition(logEvent)) { continue; } IEnumerable> wordsForHighlighting = consoleWordHighlightingRule.GetWordsForHighlighting(message); if (wordsForHighlighting == null) { continue; } if (stringBuilder != null) { stringBuilder.Length = 0; } int num = 0; foreach (KeyValuePair item in wordsForHighlighting) { stringBuilder = stringBuilder ?? new StringBuilder(message.Length + 5); stringBuilder.Append(message, num, item.Key - num); stringBuilder.Append('\a'); stringBuilder.Append((char)(consoleWordHighlightingRule.ForegroundColor + 65)); stringBuilder.Append((char)(consoleWordHighlightingRule.BackgroundColor + 65)); for (int j = 0; j < item.Value; j++) { stringBuilder.Append(message[j + item.Key]); } stringBuilder.Append('\a'); stringBuilder.Append('X'); num = item.Key + item.Value; } if (stringBuilder != null && stringBuilder.Length > 0) { stringBuilder.Append(message, num, message.Length - num); message = stringBuilder.ToString(); } } return message; } finally { ((IDisposable)lockOject).Dispose(); } } private static string EscapeColorCodes(string message) { if (message.IndexOf('\a') >= 0) { message = message.Replace("\a", "\a\a"); } return message; } private static void ColorizeEscapeSequences(IColoredConsolePrinter consolePrinter, TextWriter consoleWriter, string message, ConsoleColor? defaultForegroundColor, ConsoleColor? defaultBackgroundColor, ConsoleColor? rowForegroundColor, ConsoleColor? rowBackgroundColor) { Stack> stack = new Stack>(); stack.Push(new KeyValuePair(rowForegroundColor, rowBackgroundColor)); int num = 0; while (num < message.Length) { int i; for (i = num; i < message.Length && message[i] >= ' '; i++) { } if (i != num) { consolePrinter.WriteSubString(consoleWriter, message, num, i); } if (i >= message.Length) { num = i; break; } char c = message[i]; switch (c) { case '\n': case '\r': { KeyValuePair keyValuePair3 = stack.Peek(); ConsoleColor? foregroundColor = ((keyValuePair3.Key != defaultForegroundColor) ? defaultForegroundColor : null); ConsoleColor? backgroundColor = ((keyValuePair3.Value != defaultBackgroundColor) ? defaultBackgroundColor : null); consolePrinter.ResetDefaultColors(consoleWriter, foregroundColor, backgroundColor); if (i + 1 < message.Length && message[i + 1] == '\n') { consolePrinter.WriteSubString(consoleWriter, message, i, i + 2); num = i + 2; } else { consolePrinter.WriteChar(consoleWriter, c); num = i + 1; } consolePrinter.ChangeForegroundColor(consoleWriter, keyValuePair3.Key, defaultForegroundColor); consolePrinter.ChangeBackgroundColor(consoleWriter, keyValuePair3.Value, defaultBackgroundColor); break; } case '\a': if (i + 1 < message.Length) { char c2 = message[i + 1]; switch (c2) { case '\a': consolePrinter.WriteChar(consoleWriter, '\a'); num = i + 2; break; case 'X': { KeyValuePair keyValuePair = stack.Pop(); KeyValuePair keyValuePair2 = stack.Peek(); if (keyValuePair2.Key != keyValuePair.Key || keyValuePair2.Value != keyValuePair.Value) { if ((keyValuePair.Key.HasValue && !keyValuePair2.Key.HasValue) || (keyValuePair.Value.HasValue && !keyValuePair2.Value.HasValue)) { consolePrinter.ResetDefaultColors(consoleWriter, defaultForegroundColor, defaultBackgroundColor); } consolePrinter.ChangeForegroundColor(consoleWriter, keyValuePair2.Key, keyValuePair.Key); consolePrinter.ChangeBackgroundColor(consoleWriter, keyValuePair2.Value, keyValuePair.Value); } num = i + 2; break; } default: { ConsoleColor? consoleColor = stack.Peek().Key; ConsoleColor? consoleColor2 = stack.Peek().Value; ConsoleOutputColor consoleOutputColor = (ConsoleOutputColor)(c2 - 65); ConsoleOutputColor consoleOutputColor2 = (ConsoleOutputColor)(message[i + 2] - 65); if (consoleOutputColor != ConsoleOutputColor.NoChange) { consoleColor = (ConsoleColor)consoleOutputColor; consolePrinter.ChangeForegroundColor(consoleWriter, consoleColor); } if (consoleOutputColor2 != ConsoleOutputColor.NoChange) { consoleColor2 = (ConsoleColor)consoleOutputColor2; consolePrinter.ChangeBackgroundColor(consoleWriter, consoleColor2); } stack.Push(new KeyValuePair(consoleColor, consoleColor2)); num = i + 3; break; } } break; } goto default; default: consolePrinter.WriteChar(consoleWriter, c); num = i + 1; break; } } if (num < message.Length) { consolePrinter.WriteSubString(consoleWriter, message, num, message.Length); } } private static TextWriter GetOutputStream(bool stdErr) { if (!stdErr) { return Console.Out; } return Console.Error; } } public enum ConsoleOutputColor { Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White, NoChange } [NLogConfigurationItem] public class ConsoleRowHighlightingRule { public static ConsoleRowHighlightingRule Default { get; } = new ConsoleRowHighlightingRule(null, ConsoleOutputColor.NoChange, ConsoleOutputColor.NoChange); public ConditionExpression? Condition { get; set; } public ConsoleOutputColor ForegroundColor { get; set; } = ConsoleOutputColor.NoChange; public ConsoleOutputColor BackgroundColor { get; set; } = ConsoleOutputColor.NoChange; public ConsoleRowHighlightingRule() { } public ConsoleRowHighlightingRule(ConditionExpression? condition, ConsoleOutputColor foregroundColor, ConsoleOutputColor backgroundColor) { Condition = condition; ForegroundColor = foregroundColor; BackgroundColor = backgroundColor; } public bool CheckCondition(LogEventInfo logEvent) { if (Condition != null) { return true.Equals(Condition.Evaluate(logEvent)); } return true; } } [Target("Console")] public sealed class ConsoleTarget : TargetWithLayoutHeaderAndFooter { private bool _pauseLogging; private readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(16384); private Encoding? _encoding; [Obsolete("Replaced by StdErr to align with ColoredConsoleTarget. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool Error { get { Layout? stdErr = StdErr; if (stdErr != null && stdErr.IsFixed) { return StdErr.FixedValue; } return false; } set { StdErr = value; } } public Layout? StdErr { get; set; } public Encoding Encoding { get { return ConsoleTargetHelper.GetConsoleOutputEncoding(_encoding, base.IsInitialized, _pauseLogging); } set { if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, base.IsInitialized, _pauseLogging)) { _encoding = value; } } } public bool DetectConsoleAvailable { get; set; } public bool AutoFlush { get; set; } public bool ForceWriteLine { get; set; } [Obsolete("Replaced by ForceWriteLine (but inverted value). Marked obsolete with NLog v6.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool WriteBuffer { get { return !ForceWriteLine; } set { ForceWriteLine = !value; } } public ConsoleTarget() { } public ConsoleTarget(string name) : this() { base.Name = name; } protected override void InitializeTarget() { _pauseLogging = false; if (DetectConsoleAvailable) { _pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out string reason); if (_pauseLogging) { InternalLogger.Info("{0}: Console detected as turned off. Set DetectConsoleAvailable=false to skip detection. Reason: {1}", this, reason); } } if (_encoding != null) { ConsoleTargetHelper.SetConsoleOutputEncoding(_encoding, isInitialized: true, _pauseLogging); } base.InitializeTarget(); if (base.Header != null) { RenderToOutput(base.Header, LogEventInfo.CreateNullEvent()); } } protected override void CloseTarget() { if (base.Footer != null) { RenderToOutput(base.Footer, LogEventInfo.CreateNullEvent()); } ExplicitConsoleFlush(); base.CloseTarget(); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { ExplicitConsoleFlush(); base.FlushAsync(asyncContinuation); } catch (Exception exception) { asyncContinuation(exception); } } private void ExplicitConsoleFlush() { if (!_pauseLogging && !AutoFlush) { Layout? stdErr = StdErr; if (stdErr == null || stdErr.IsFixed) { GetOutput(StdErr?.FixedValue ?? false).Flush(); return; } GetOutput(stdErr: false).Flush(); GetOutput(stdErr: true).Flush(); } } protected override void Write(LogEventInfo logEvent) { if (!_pauseLogging) { RenderToOutput(Layout, logEvent); } } protected override void Write(IList logEvents) { if (!_pauseLogging) { if (ForceWriteLine) { base.Write(logEvents); } else { WriteBufferToOutput(logEvents); } } } private void RenderToOutput(Layout layout, LogEventInfo logEvent) { if (!_pauseLogging) { TextWriter output = GetOutput(RenderLogEvent(StdErr, logEvent, defaultValue: false)); if (ForceWriteLine) { WriteLineToOutput(output, RenderLogEvent(layout, logEvent)); } else { WriteBufferToOutput(output, layout, logEvent); } } } private void WriteBufferToOutput(TextWriter output, Layout layout, LogEventInfo logEvent) { int targetBufferPosition = 0; ReusableObjectCreator.LockOject lockOject = _reusableEncodingBuffer.Allocate(); try { ReusableObjectCreator.LockOject lockOject2 = ReusableLayoutBuilder.Allocate(); try { RenderLogEventToWriteBuffer(output, layout, logEvent, lockOject2.Result, lockOject.Result, ref targetBufferPosition); if (targetBufferPosition > 0) { WriteBufferToOutput(output, lockOject.Result, targetBufferPosition); } } finally { ((IDisposable)lockOject2).Dispose(); } } finally { ((IDisposable)lockOject).Dispose(); } } private void WriteBufferToOutput(IList logEvents) { ReusableObjectCreator.LockOject lockOject = _reusableEncodingBuffer.Allocate(); try { ReusableObjectCreator.LockOject lockOject2 = ReusableLayoutBuilder.Allocate(); try { int targetBufferPosition = 0; bool flag = false; TextWriter output = GetOutput(flag); try { for (int i = 0; i < logEvents.Count; i++) { LogEventInfo logEvent = logEvents[i].LogEvent; if (flag != RenderLogEvent(StdErr, logEvent, defaultValue: false)) { if (targetBufferPosition > 0) { WriteBufferToOutput(output, lockOject.Result, targetBufferPosition); } flag = !flag; output = GetOutput(flag); } lockOject2.Result.ClearBuilder(); RenderLogEventToWriteBuffer(output, Layout, logEvent, lockOject2.Result, lockOject.Result, ref targetBufferPosition); logEvents[i].Continuation(null); } } finally { if (targetBufferPosition > 0) { WriteBufferToOutput(output, lockOject.Result, targetBufferPosition); } } } finally { ((IDisposable)lockOject2).Dispose(); } } finally { ((IDisposable)lockOject).Dispose(); } } private void RenderLogEventToWriteBuffer(TextWriter output, Layout layout, LogEventInfo logEvent, StringBuilder targetBuilder, char[] targetBuffer, ref int targetBufferPosition) { int length = Environment.NewLine.Length; layout.Render(logEvent, targetBuilder); if (targetBuilder.Length > targetBuffer.Length - targetBufferPosition - length) { if (targetBufferPosition > 0) { WriteBufferToOutput(output, targetBuffer, targetBufferPosition); targetBufferPosition = 0; } if (targetBuilder.Length > targetBuffer.Length - length) { WriteLineToOutput(output, targetBuilder.ToString()); return; } } targetBuilder.Append(Environment.NewLine); targetBuilder.CopyToBuffer(targetBuffer, targetBufferPosition); targetBufferPosition += targetBuilder.Length; } private void WriteLineToOutput(TextWriter output, string message) { try { ConsoleTargetHelper.WriteLineThreadSafe(output, message, AutoFlush); } catch (Exception ex) when (ex is OverflowException || ex is IndexOutOfRangeException || ex is ArgumentOutOfRangeException) { _pauseLogging = true; InternalLogger.Warn(ex, "{0}: {1} has been thrown and this is probably due to a race condition.Logging to the console will be paused. Enable by reloading the config or re-initialize the targets", new ReadOnlySpan(new object[2] { this, ex.GetType() })); } } private void WriteBufferToOutput(TextWriter output, char[] buffer, int length) { try { ConsoleTargetHelper.WriteBufferThreadSafe(output, buffer, length, AutoFlush); } catch (Exception ex) when (ex is OverflowException || ex is IndexOutOfRangeException || ex is ArgumentOutOfRangeException) { _pauseLogging = true; InternalLogger.Warn(ex, "{0}: {1} has been thrown and this is probably due to a race condition.Logging to the console will be paused. Enable by reloading the config or re-initialize the targets", new ReadOnlySpan(new object[2] { this, ex.GetType() })); } } private static TextWriter GetOutput(bool stdErr) { if (!stdErr) { return Console.Out; } return Console.Error; } } internal static class ConsoleTargetHelper { private static readonly object _lockObject = new object(); public static bool IsConsoleAvailable(out string reason) { reason = string.Empty; try { if (!Environment.UserInteractive) { reason = "Environment.UserInteractive = False"; return false; } if (Console.OpenStandardInput(1) == Stream.Null) { reason = "Console.OpenStandardInput = Null"; return false; } } catch (Exception ex) { reason = "Unexpected exception: " + ex.GetType().Name + ":" + ex.Message; InternalLogger.Warn(ex, "Failed to detect whether console is available."); return false; } return true; } public static Encoding GetConsoleOutputEncoding(Encoding? currentEncoding, bool isInitialized, bool pauseLogging) { if (currentEncoding != null) { return currentEncoding; } if ((isInitialized && !pauseLogging) || IsConsoleAvailable(out string _)) { return Console.OutputEncoding; } return Encoding.Default; } public static bool SetConsoleOutputEncoding(Encoding newEncoding, bool isInitialized, bool pauseLogging) { if (!isInitialized) { return true; } if (!pauseLogging) { try { Console.OutputEncoding = newEncoding; return true; } catch (Exception ex) { InternalLogger.Warn(ex, "Failed changing Console.OutputEncoding to {0}", new ReadOnlySpan(new object[1] { newEncoding })); } } return false; } public static void WriteLineThreadSafe(TextWriter console, string message, bool flush = false) { lock (_lockObject) { console.WriteLine(message); if (flush) { console.Flush(); } } } public static void WriteBufferThreadSafe(TextWriter console, char[] buffer, int length, bool flush = false) { lock (_lockObject) { console.Write(buffer, 0, length); if (flush) { console.Flush(); } } } } [NLogConfigurationItem] public class ConsoleWordHighlightingRule { [CompilerGenerated] private sealed class d__39 : IEnumerable>, IEnumerable, IEnumerator>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair <>2__current; private int <>l__initialThreadId; public ConsoleWordHighlightingRule <>4__this; private string needle; public string <>3__needle; private int firstIndex; public int <>3__firstIndex; private int nextIndex; public int <>3__nextIndex; private string haystack; public string <>3__haystack; private int 5__2; KeyValuePair IEnumerator>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__39(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { int num = <>1__state; ConsoleWordHighlightingRule consoleWordHighlightingRule = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>2__current = consoleWordHighlightingRule.GenerateMatch(needle, firstIndex); <>1__state = 1; return true; case 1: <>1__state = -1; <>2__current = consoleWordHighlightingRule.GenerateMatch(needle, nextIndex); <>1__state = 2; return true; case 2: <>1__state = -1; 5__2 = nextIndex; break; case 3: <>1__state = -1; break; } while (5__2 >= 0) { 5__2 = consoleWordHighlightingRule.FindNextWordForHighlighting(needle, haystack, 5__2); if (5__2 >= 0) { <>2__current = consoleWordHighlightingRule.GenerateMatch(needle, 5__2); <>1__state = 3; return true; } } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator> IEnumerable>.GetEnumerator() { d__39 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__39(0) { <>4__this = <>4__this }; } d__.needle = <>3__needle; d__.haystack = <>3__haystack; d__.firstIndex = <>3__firstIndex; d__.nextIndex = <>3__nextIndex; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable>)this).GetEnumerator(); } } private string _text = string.Empty; public ConditionExpression? Condition { get; set; } public string Text { get { return _text; } set { _text = (string.IsNullOrEmpty(value) ? string.Empty : value); } } public List? Words { get; set; } public bool WholeWords { get; set; } public bool IgnoreCase { get; set; } public ConsoleOutputColor ForegroundColor { get; set; } = ConsoleOutputColor.NoChange; public ConsoleOutputColor BackgroundColor { get; set; } = ConsoleOutputColor.NoChange; public ConsoleWordHighlightingRule() { } public ConsoleWordHighlightingRule(string text, ConsoleOutputColor foregroundColor, ConsoleOutputColor backgroundColor) { Text = text; ForegroundColor = foregroundColor; BackgroundColor = backgroundColor; } protected internal virtual IEnumerable>? GetWordsForHighlighting(string haystack) { if ((object)_text == string.Empty) { List? words = Words; if (words != null && words.Count > 0) { return YieldWordMatchesForHighlighting(haystack, Words); } return null; } return YieldMatchesForHighlighting(_text, haystack); } private IEnumerable>? YieldWordMatchesForHighlighting(string haystack, List words) { IEnumerable> enumerable = null; foreach (string word in words) { if (!string.IsNullOrEmpty(word)) { IEnumerable> enumerable2 = YieldMatchesForHighlighting(word, haystack); if (enumerable2 != null) { enumerable = ((enumerable == null) ? enumerable2 : MergeWordMatches(enumerable, enumerable2)); } } } return enumerable; } private static IEnumerable> MergeWordMatches(IEnumerable> allMatches, IEnumerable> needleMatch) { if (needleMatch is IList> list && list.Count == 1) { KeyValuePair newMatch = list[0]; IList> list2 = PrepareAllMatchesList(allMatches, 1); MergeAllNeedleMatches(list2, newMatch); return list2; } IList> list3 = PrepareAllMatchesList(allMatches, 3); int startIndex = 0; foreach (KeyValuePair item in needleMatch) { startIndex = MergeAllNeedleMatches(list3, item, startIndex); } return list3; } private static int MergeAllNeedleMatches(IList> allMatchesList, KeyValuePair newMatch, int startIndex = 0) { for (int i = startIndex; i < allMatchesList.Count; i++) { KeyValuePair second = allMatchesList[i]; if (NeedleMatchOverlaps(newMatch, second)) { newMatch = MergeNeedleMatch(newMatch, second); allMatchesList[i] = newMatch; while (i < allMatchesList.Count - 1 && NeedleMatchOverlaps(newMatch, allMatchesList[i + 1])) { newMatch = MergeNeedleMatch(newMatch, allMatchesList[i + 1]); allMatchesList[i] = newMatch; allMatchesList.RemoveAt(i + 1); } return i; } if (newMatch.Key < second.Key) { allMatchesList.Insert(i, newMatch); return i + 1; } } allMatchesList.Add(newMatch); return allMatchesList.Count; } private static bool NeedleMatchOverlaps(KeyValuePair first, KeyValuePair second) { if (first.Key < second.Key) { return first.Key + first.Value > second.Key; } return second.Key + second.Value > first.Key; } private static KeyValuePair MergeNeedleMatch(KeyValuePair first, KeyValuePair second) { if (first.Key < second.Key) { return new KeyValuePair(first.Key, Math.Max(first.Key + first.Value, second.Key + second.Value) - first.Key); } return new KeyValuePair(second.Key, Math.Max(first.Key + first.Value, second.Key + second.Value) - second.Key); } private static IList> PrepareAllMatchesList(IEnumerable> allMatches, int extraCapacity) { int num = 3; if (allMatches is IList> list) { if (!list.IsReadOnly) { return list; } num = Math.Max(list.Count, num); } IList> list2 = new List>(num + extraCapacity); foreach (KeyValuePair allMatch in allMatches) { list2.Add(allMatch); } return list2; } private IEnumerable>? YieldMatchesForHighlighting(string needle, string haystack) { int num = FindNextWordForHighlighting(needle, haystack, null); if (num < 0) { return null; } int num2 = FindNextWordForHighlighting(needle, haystack, num); if (num2 < 0) { return new KeyValuePair[1] { GenerateMatch(needle, num) }; } return YieldWordsForHighlighting(needle, haystack, num, num2); } private KeyValuePair GenerateMatch(string needle, int startIndex) { int num = needle.Length; if (WholeWords) { for (int i = 0; i < needle.Length && !char.IsLetterOrDigit(needle[i]); i++) { num--; startIndex++; } if (num <= 0) { return new KeyValuePair(startIndex - needle.Length, needle.Length); } int num2 = needle.Length - 1; while (num2 >= 0 && !char.IsLetterOrDigit(needle[num2])) { num--; num2--; } } return new KeyValuePair(startIndex, num); } [IteratorStateMachine(typeof(d__39))] private IEnumerable> YieldWordsForHighlighting(string needle, string haystack, int firstIndex, int nextIndex) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__39(-2) { <>4__this = this, <>3__needle = needle, <>3__haystack = haystack, <>3__firstIndex = firstIndex, <>3__nextIndex = nextIndex }; } private int FindNextWordForHighlighting(string needle, string haystack, int? prevIndex) { int num; for (num = (prevIndex.HasValue ? (prevIndex.Value + needle.Length) : 0); num >= 0; num += needle.Length) { num = (IgnoreCase ? haystack.IndexOf(needle, num, StringComparison.CurrentCultureIgnoreCase) : haystack.IndexOf(needle, num, StringComparison.Ordinal)); if (num < 0 || !WholeWords) { return num; } if (StringHelpers.IsWholeWord(haystack, needle, num) || ((num == 0 || !char.IsLetterOrDigit(needle[0])) && !char.IsLetterOrDigit(needle[needle.Length - 1]))) { return num; } } return num; } internal bool CheckCondition(LogEventInfo logEvent) { if (Condition != null) { return true.Equals(Condition.Evaluate(logEvent)); } return true; } } [Target("Debugger")] public sealed class DebuggerTarget : TargetWithLayoutHeaderAndFooter { public Layout Category { get; set; } = NLog.Layouts.Layout.FromMethod((LogEventInfo l) => l.LoggerName, LayoutRenderOptions.ThreadAgnostic); public int MaxMessageSize { get; set; } public DebuggerTargetOverflowAction OnOverflow { get; set; } = DebuggerTargetOverflowAction.Split; public DebuggerTarget() { } public DebuggerTarget(string name) : this() { base.Name = name; } protected override void InitializeTarget() { base.InitializeTarget(); if (!Debugger.IsLogging()) { InternalLogger.Debug("{0}: System.Diagnostics.Debugger.IsLogging()==false. Output has been disabled.", this); } if (base.Header != null) { DebuggerLogMessageLayout(base.Header); } } protected override void CloseTarget() { if (base.Footer != null) { DebuggerLogMessageLayout(base.Footer); } base.CloseTarget(); } protected override void Write(LogEventInfo logEvent) { if (!Debugger.IsLogging()) { return; } string category = RenderLogEvent(Category, logEvent); ReusableObjectCreator.LockOject lockOject = ReusableLayoutBuilder.Allocate(); string message; try { Layout.Render(logEvent, lockOject.Result); if (MaxMessageSize > 0 && lockOject.Result.Length > MaxMessageSize) { switch (OnOverflow) { case DebuggerTargetOverflowAction.None: InternalLogger.Debug("{0}: Notice log message has length {1} > MaxMessageSize={2}", this, lockOject.Result.Length, MaxMessageSize); break; case DebuggerTargetOverflowAction.Truncate: InternalLogger.Debug("{0}: Truncates log message because length {1} > MaxMessageSize={2}", this, lockOject.Result.Length, MaxMessageSize); lockOject.Result.Length = MaxMessageSize; break; case DebuggerTargetOverflowAction.Split: { InternalLogger.Debug("{0}: Splits log message because length {1} > MaxMessageSize={2}", this, lockOject.Result.Length, MaxMessageSize); for (int i = 0; i < lockOject.Result.Length; i += MaxMessageSize) { int num = Math.Min(MaxMessageSize, lockOject.Result.Length - i); string text = lockOject.Result.ToString(i, num); Debugger.Log(logEvent.Level.Ordinal, category, text + "\n"); } return; } case DebuggerTargetOverflowAction.Discard: InternalLogger.Debug("{0}: Discards log message because length {1} > MaxMessageSize={2}", this, lockOject.Result.Length, MaxMessageSize); return; } } lockOject.Result.Append('\n'); message = lockOject.Result.ToString(); } finally { ((IDisposable)lockOject).Dispose(); } Debugger.Log(logEvent.Level.Ordinal, category, message); } private void DebuggerLogMessageLayout(Layout layout) { LogEventInfo logEvent = LogEventInfo.CreateNullEvent(); string category = Category?.Render(logEvent) ?? string.Empty; string text = layout?.Render(logEvent) ?? string.Empty; Debugger.Log(LogLevel.Info.Ordinal, category, text + "\n"); } } public enum DebuggerTargetOverflowAction { None, Truncate, Split, Discard } [Target("DebugSystem")] public sealed class DebugSystemTarget : TargetWithLayoutHeaderAndFooter { public DebugSystemTarget() { } public DebugSystemTarget(string name) : this() { base.Name = name; } protected override void InitializeTarget() { base.InitializeTarget(); if (base.Header != null) { DebugWriteLine(RenderLogEvent(base.Header, LogEventInfo.CreateNullEvent())); } } protected override void CloseTarget() { if (base.Footer != null) { DebugWriteLine(RenderLogEvent(base.Footer, LogEventInfo.CreateNullEvent())); } base.CloseTarget(); } protected override void Write(LogEventInfo logEvent) { DebugWriteLine(RenderLogEvent(Layout, logEvent)); } private static void DebugWriteLine(string message) { Debug.WriteLine(message); } } [Target("Debug")] public sealed class DebugTarget : TargetWithLayout { public int Counter { get; private set; } public string LastMessage { get; private set; } public DebugTarget() { LastMessage = string.Empty; Counter = 0; } public DebugTarget(string name) : this() { base.Name = name; } protected override void Write(LogEventInfo logEvent) { Counter++; LastMessage = RenderLogEvent(Layout, logEvent); } } public class DefaultJsonSerializer : IJsonConverter { private readonly ObjectReflectionCache _objectReflectionCache; private readonly MruCache _enumCache = new MruCache(2000); private const int MaxJsonLength = 524288; private static JsonSerializeOptions DefaultSerializerOptions = new JsonSerializeOptions(); private static JsonSerializeOptions DefaultExceptionSerializerOptions = new JsonSerializeOptions { SanitizeDictionaryKeys = true }; private static DefaultJsonSerializer? _instance; [Obsolete("Instead use ResolveService() in Layout / Target. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static DefaultJsonSerializer Instance => _instance ?? (_instance = new DefaultJsonSerializer(LogManager.LogFactory.ServiceRepository)); internal DefaultJsonSerializer(IServiceProvider serviceProvider) { _objectReflectionCache = new ObjectReflectionCache(serviceProvider); } public string SerializeObject(object value) { return SerializeObject(value, DefaultSerializerOptions); } public string SerializeObject(object value, JsonSerializeOptions options) { if (value == null) { return "null"; } if (value is string text) { bool escapeUnicode = options.EscapeUnicode; string text2 = text; for (int i = 0; i < text2.Length; i++) { if (RequiresJsonEscape(text2[i], escapeUnicode)) { StringBuilder stringBuilder = new StringBuilder(text.Length + 4); stringBuilder.Append('"'); AppendStringEscape(stringBuilder, text, options); stringBuilder.Append('"'); return stringBuilder.ToString(); } } return QuoteValue(text); } if (value is IConvertible convertible) { TypeCode typeCode = convertible.GetTypeCode(); if (typeCode != TypeCode.Object) { if (!options.EnumAsInteger && IsNumericTypeCode(typeCode, includeDecimals: false) && convertible is Enum value2) { return QuoteValue(EnumAsString(value2)); } string text3 = XmlHelper.XmlConvertToString(convertible, typeCode); if (SkipQuotes(convertible, typeCode)) { return text3; } return QuoteValue(text3); } } StringBuilder stringBuilder2 = new StringBuilder(); if (!SerializeObject(value, stringBuilder2, options)) { return string.Empty; } return stringBuilder2.ToString(); } public bool SerializeObject(object? value, StringBuilder destination) { return SerializeObject(value, destination, DefaultSerializerOptions); } public bool SerializeObject(object? value, StringBuilder destination, JsonSerializeOptions options) { return SerializeObject(value, destination, options, default(SingleItemOptimizedHashSet), 0); } private bool SerializeObject(object? value, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet objectsInPath, int depth) { int length = destination.Length; try { if (SerializeSimpleObjectValue(value, destination, options)) { return true; } return SerializeObjectWithReflection(value, destination, options, ref objectsInPath, depth); } catch { destination.Length = length; return false; } } private bool SerializeObjectWithReflection(object? value, StringBuilder destination, JsonSerializeOptions options, ref SingleItemOptimizedHashSet objectsInPath, int depth) { if (destination.Length > 524288) { return false; } if (value == null || objectsInPath.Contains(value)) { return false; } if (value is IDictionary dictionary) { using (StartCollectionScope(ref objectsInPath, dictionary)) { SerializeDictionaryObject(dictionary, destination, options, objectsInPath, depth); return true; } } if (value is IEnumerable value2) { if (_objectReflectionCache.TryLookupExpandoObject(value, out var objectPropertyList)) { return SerializeObjectPropertyList(value, ref objectPropertyList, destination, options, ref objectsInPath, depth); } using (StartCollectionScope(ref objectsInPath, value)) { SerializeCollectionObject(value2, destination, options, objectsInPath, depth); return true; } } ObjectReflectionCache.ObjectPropertyList objectPropertyList2 = _objectReflectionCache.LookupObjectProperties(value); return SerializeObjectPropertyList(value, ref objectPropertyList2, destination, options, ref objectsInPath, depth); } private bool SerializeSimpleObjectValue(object? value, StringBuilder destination, JsonSerializeOptions options, bool forceToString = false) { if (value is IConvertible convertible) { TypeCode typeCode = convertible.GetTypeCode(); if (typeCode != TypeCode.Object) { SerializeSimpleTypeCodeValue(convertible, typeCode, destination, options, forceToString); return true; } } if (value is IFormattable arg) { if (value is DateTimeOffset dateTimeOffset) { QuoteValue(destination, dateTimeOffset.ToString("yyyy-MM-dd HH:mm:ss zzz", CultureInfo.InvariantCulture)); return true; } destination.Append('"'); int length = destination.Length; destination.AppendFormat(CultureInfo.InvariantCulture, "{0}", arg); PerformJsonEscapeWhenNeeded(destination, length, options.EscapeUnicode); destination.Append('"'); return true; } if (value == null) { SerializeSimpleTypeCodeValue(null, TypeCode.Empty, destination, options, forceToString); return true; } return false; } private static SingleItemOptimizedHashSet.SingleItemScopedInsert StartCollectionScope(ref SingleItemOptimizedHashSet objectsInPath, object value) { return new SingleItemOptimizedHashSet.SingleItemScopedInsert(value, ref objectsInPath, forceHashSet: true); } private void SerializeDictionaryObject(IDictionary dictionary, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet objectsInPath, int depth) { bool flag = true; int num = ((objectsInPath.Count <= 1) ? depth : (depth + 1)); if (num > options.MaxRecursionLimit) { destination.Append("{}"); return; } destination.Append('{'); foreach (DictionaryEntry item in new DictionaryEntryEnumerable(dictionary)) { int length = destination.Length; if (length > 524288) { break; } if (!flag) { destination.Append(','); } object key = item.Key; if (!SerializeObjectAsString(key, destination, options)) { destination.Length = length; continue; } if (options.SanitizeDictionaryKeys) { int num2 = destination.Length - 1; int num3 = length + ((!flag) ? 1 : 0) + 1; if (!SanitizeDictionaryKey(destination, num3, num2 - num3)) { destination.Length = length; continue; } } destination.Append(':'); object value = item.Value; if (!SerializeObject(value, destination, options, objectsInPath, num)) { destination.Length = length; } else { flag = false; } } destination.Append('}'); } private static bool SanitizeDictionaryKey(StringBuilder destination, int keyStartIndex, int keyLength) { if (keyLength == 0) { return false; } int num = keyStartIndex + keyLength; for (int i = keyStartIndex; i < num; i++) { char c = destination[i]; if (c != '_' && !char.IsLetterOrDigit(c)) { destination[i] = '_'; } } return true; } private void SerializeCollectionObject(IEnumerable value, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet objectsInPath, int depth) { bool flag = true; int num = ((objectsInPath.Count <= 1) ? depth : (depth + 1)); if (num > options.MaxRecursionLimit) { destination.Append("[]"); return; } destination.Append('['); foreach (object item in value) { int length = destination.Length; if (length > 524288) { break; } if (!flag) { destination.Append(','); } if (!SerializeObject(item, destination, options, objectsInPath, num)) { destination.Length = length; } else { flag = false; } } destination.Append(']'); } private bool SerializeObjectPropertyList(object value, ref ObjectReflectionCache.ObjectPropertyList objectPropertyList, StringBuilder destination, JsonSerializeOptions options, ref SingleItemOptimizedHashSet objectsInPath, int depth) { if (objectPropertyList.IsSimpleValue) { value = objectPropertyList.ObjectValue; if (SerializeSimpleObjectValue(value, destination, options)) { return true; } } else if (depth < options.MaxRecursionLimit) { if (options == DefaultSerializerOptions && value is Exception) { options = DefaultExceptionSerializerOptions; } using (new SingleItemOptimizedHashSet.SingleItemScopedInsert(value, ref objectsInPath, forceHashSet: false)) { return SerializeObjectProperties(objectPropertyList, destination, options, objectsInPath, depth); } } return SerializeObjectAsString(value, destination, options); } private void SerializeSimpleTypeCodeValue(IConvertible? value, TypeCode objTypeCode, StringBuilder destination, JsonSerializeOptions options, bool forceToString = false) { if (objTypeCode == TypeCode.Empty || value == null) { destination.Append(forceToString ? "\"\"" : "null"); } else if (objTypeCode == TypeCode.String || objTypeCode == TypeCode.Char) { destination.Append('"'); AppendStringEscape(destination, value.ToString() ?? string.Empty, options); destination.Append('"'); } else { SerializeSimpleTypeCodeValueNoEscape(value, objTypeCode, destination, options, forceToString); } } private void SerializeSimpleTypeCodeValueNoEscape(IConvertible value, TypeCode objTypeCode, StringBuilder destination, JsonSerializeOptions options, bool forceToString) { if (IsNumericTypeCode(objTypeCode, includeDecimals: false)) { if (!options.EnumAsInteger && value is Enum value2) { QuoteValue(destination, EnumAsString(value2)); } else { SerializeNumericValue(value, objTypeCode, destination, forceToString); } return; } if (objTypeCode == TypeCode.DateTime) { destination.Append('"'); destination.AppendXmlDateTimeUtcRoundTrip(value.ToDateTime(CultureInfo.InvariantCulture)); destination.Append('"'); return; } if (IsNumericTypeCode(objTypeCode, includeDecimals: true) && SkipQuotes(value, objTypeCode)) { SerializeNumericValue(value, objTypeCode, destination, forceToString); return; } string value3 = XmlHelper.XmlConvertToString(value, objTypeCode); if (!forceToString && !string.IsNullOrEmpty(value3) && SkipQuotes(value, objTypeCode)) { destination.Append(value3); } else { QuoteValue(destination, value3); } } private static void SerializeNumericValue(IConvertible value, TypeCode objTypeCode, StringBuilder destination, bool forceToString) { if (forceToString) { destination.Append('"'); } destination.AppendNumericInvariant(value, objTypeCode); if (forceToString) { destination.Append('"'); } } private static string QuoteValue(string value) { return "\"" + value + "\""; } private static void QuoteValue(StringBuilder destination, string value) { destination.Append('"'); destination.Append(value); destination.Append('"'); } private string EnumAsString(Enum value) { if (!_enumCache.TryGetValue(value, out string value2)) { value2 = Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty; _enumCache.TryAddValue(value, value2); } return value2 ?? string.Empty; } private static bool SkipQuotes(IConvertible value, TypeCode objTypeCode) { switch (objTypeCode) { case TypeCode.String: return false; case TypeCode.Char: return false; case TypeCode.DateTime: return false; case TypeCode.Empty: return true; case TypeCode.Boolean: return true; case TypeCode.Decimal: return true; case TypeCode.Double: { double d = value.ToDouble(CultureInfo.InvariantCulture); if (!double.IsNaN(d)) { return !double.IsInfinity(d); } return false; } case TypeCode.Single: { float f = value.ToSingle(CultureInfo.InvariantCulture); if (!float.IsNaN(f)) { return !float.IsInfinity(f); } return false; } default: return IsNumericTypeCode(objTypeCode, includeDecimals: false); } } private static bool IsNumericTypeCode(TypeCode objTypeCode, bool includeDecimals) { switch (objTypeCode) { case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return true; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return includeDecimals; default: return false; } } private static void AppendStringEscape(StringBuilder destination, string text, JsonSerializeOptions options) { AppendStringEscape(destination, text, options.EscapeUnicode); } internal static void AppendStringEscape(StringBuilder destination, string text, bool escapeUnicode) { int num = 0; for (int i = 0; i < text.Length; i++) { if (RequiresJsonEscape(text[i], escapeUnicode)) { AppendStringEscape(destination, text, escapeUnicode, num); return; } num++; } destination.Append(text); } private static void AppendStringEscape(StringBuilder destination, string text, bool escapeUnicode, int startIndex) { destination.Append(text, 0, startIndex); for (int i = startIndex; i < text.Length; i++) { char c = text[i]; if (!RequiresJsonEscape(c, escapeUnicode)) { destination.Append(c); continue; } switch (c) { case '"': destination.Append("\\\""); break; case '\\': destination.Append("\\\\"); break; case '\b': destination.Append("\\b"); break; case '\r': destination.Append("\\r"); break; case '\n': destination.Append("\\n"); break; case '\f': destination.Append("\\f"); break; case '\t': destination.Append("\\t"); break; default: destination.AppendFormat(CultureInfo.InvariantCulture, "\\u{0:x4}", (int)c); break; } } } internal static void PerformJsonEscapeWhenNeeded(StringBuilder builder, int startPos, bool escapeUnicode) { int length = builder.Length; for (int i = startPos; i < length; i++) { if (RequiresJsonEscape(builder[i], escapeUnicode)) { string text = builder.ToString(i, length - i); builder.Length = i; AppendStringEscape(builder, text, escapeUnicode, 0); break; } } } private static bool RequiresJsonEscape(char ch, bool escapeUnicode) { if (ch < ' ') { return true; } if (ch > '\u007f') { return escapeUnicode; } if (ch != '"') { return ch == '\\'; } return true; } private bool SerializeObjectProperties(ObjectReflectionCache.ObjectPropertyList objectPropertyList, StringBuilder destination, JsonSerializeOptions options, SingleItemOptimizedHashSet objectsInPath, int depth) { destination.Append('{'); string text = null; foreach (ObjectReflectionCache.ObjectPropertyList.PropertyValue item in objectPropertyList) { int length = destination.Length; try { if (item.HasNameAndValue) { destination.Append(text); QuoteValue(destination, item.Name); destination.Append(':'); TypeCode typeCode = item.TypeCode; if (typeCode != TypeCode.Object) { SerializeSimpleTypeCodeValue((IConvertible)item.Value, typeCode, destination, options); goto IL_0097; } if (SerializeObject(item.Value, destination, options, objectsInPath, depth + 1)) { goto IL_0097; } destination.Length = length; } goto end_IL_0027; IL_0097: if (text == null) { text = (options.SuppressSpaces ? "," : ", "); } end_IL_0027:; } catch { destination.Length = length; } } destination.Append('}'); return true; } private bool SerializeObjectAsString(object value, StringBuilder destination, JsonSerializeOptions options) { int length = destination.Length; try { if (SerializeSimpleObjectValue(value, destination, options, forceToString: true)) { return true; } string text = Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty; destination.Append('"'); AppendStringEscape(destination, text, options); destination.Append('"'); return true; } catch { destination.Length = length; return false; } } } public enum FileArchivePeriod { None, Year, Month, Day, Hour, Minute, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } [Target("File")] public class FileTarget : TargetWithLayoutHeaderAndFooter { private readonly struct OpenFileAppender { public IFileAppender FileAppender { get; } public int SequenceNumber { get; } public OpenFileAppender(IFileAppender fileAppender, int sequenceNumber) { FileAppender = fileAppender; SequenceNumber = sequenceNumber; } } private Layout _fileName = NLog.Layouts.Layout.Empty; private string? _fixedFileName; private Encoding _encoding = System.Text.Encoding.UTF8; private bool? _writeBom; private string? _archiveDateFormat; private long _archiveAboveSize; private FileArchivePeriod _archiveEvery; private Layout? _archiveFileName; private static readonly string _legacyDateArchiveSuffixFormat = "_{1:yyyyMMdd}_{0:00}"; private static readonly string _legacySequenceArchiveSuffixFormat = "_{0:00}"; private int _maxArchiveFiles = -1; private int _maxArchiveDays; private string? _archiveNumbering; private string? _archiveSuffixFormat; private bool _archiveSuffixFormatLegacy; private IFileArchiveHandler? _fileArchiveHandler; private readonly Dictionary _openFileCache = new Dictionary(StringComparer.OrdinalIgnoreCase); private readonly ReusableStreamCreator _reusableFileWriteStream = new ReusableStreamCreator(); private readonly ReusableStreamCreator _reusableBatchFileWriteStream = new ReusableStreamCreator(batchStream: true); private readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(1024); private readonly SortHelpers.KeySelector _getFileNameFromLayout; private Timer? _openFileMonitorTimer; private string _lastFileNameFromLayout = string.Empty; private static readonly char[] DirectorySeparatorChars = new char[2] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; private static readonly HashSet InvalidFileNameChars = new HashSet(Path.GetInvalidFileNameChars()); public Layout FileName { get { return _fileName; } set { _fileName = value; _fixedFileName = ((value is SimpleLayout simpleLayout && simpleLayout.IsFixedText) ? simpleLayout.FixedText : null); } } public bool CreateDirs { get; set; } = true; public bool DeleteOldFileOnStartup { get; set; } public bool ReplaceFileContentsOnEachWrite { get; set; } public bool KeepFileOpen { get; set; } = true; public bool EnableFileDelete { get; set; } = true; public LineEndingMode LineEnding { get; set; } = LineEndingMode.Default; public bool AutoFlush { get; set; } = true; public int OpenFileCacheSize { get; set; } = 5; public int OpenFileCacheTimeout { get; set; } public int OpenFileFlushTimeout { get; set; } public int BufferSize { get; set; } = 32768; public Encoding Encoding { get { return _encoding; } set { _encoding = value; if (!_writeBom.HasValue && InitialValueBom(value)) { _writeBom = true; } } } public bool DiscardAll { get; set; } public bool WriteBom { get { return _writeBom.GetValueOrDefault(); } set { _writeBom = value; } } public bool ArchiveOldFileOnStartup { get; set; } public bool WriteHeaderWhenInitialFileNotEmpty { get; set; } [Obsolete("Instead use ArchiveSuffixFormat. Marked obsolete with NLog 6.0")] [EditorBrowsable(EditorBrowsableState.Never)] public string? ArchiveDateFormat { get { return _archiveDateFormat; } set { if (!string.Equals(value, _archiveDateFormat)) { if (!string.IsNullOrEmpty(value)) { ArchiveSuffixFormat = "_{1:" + value + "}_{0:00}"; } _archiveDateFormat = value; } } } public long ArchiveAboveSize { get { return _archiveAboveSize; } set { _archiveAboveSize = ((value > 0) ? value : 0); _fileArchiveHandler = null; } } public FileArchivePeriod ArchiveEvery { get { return _archiveEvery; } set { _archiveEvery = value; _fileArchiveHandler = null; } } public Layout? ArchiveFileName { get { Layout layout = _archiveFileName; if (layout == null) { if (!_archiveSuffixFormatLegacy) { return null; } layout = FileName; } return layout; } set { string text = _archiveSuffixFormat; if (value is SimpleLayout simpleLayout) { if ((simpleLayout.OriginalText.IndexOf("${date", StringComparison.OrdinalIgnoreCase) >= 0 || simpleLayout.OriginalText.IndexOf("${shortdate", StringComparison.OrdinalIgnoreCase) >= 0) && (_archiveSuffixFormat == null || (object)_legacySequenceArchiveSuffixFormat == _archiveSuffixFormat || (object)_legacyDateArchiveSuffixFormat == _archiveSuffixFormat)) { text = "_{0}"; } if (simpleLayout.OriginalText.Contains('#')) { string txt = simpleLayout.OriginalText.Replace(".{#}", string.Empty).Replace("_{#}", "").Replace("-{#}", "") .Replace("{#}", "") .Replace(".{#", "") .Replace("_{#", "") .Replace("-{#", "") .Replace("{#", "") .Replace("#}", "") .Replace("#", ""); text = _archiveSuffixFormat ?? _legacySequenceArchiveSuffixFormat; value = new SimpleLayout(txt); } } _archiveFileName = value; if ((object)_archiveSuffixFormat != text && text != null) { ArchiveSuffixFormat = text; } _fileArchiveHandler = null; } } public int MaxArchiveFiles { get { return _maxArchiveFiles; } set { _maxArchiveFiles = value; _fileArchiveHandler = null; } } public int MaxArchiveDays { get { return _maxArchiveDays; } set { _maxArchiveDays = ((value > 0) ? value : 0); _fileArchiveHandler = null; } } [Obsolete("Instead use ArchiveSuffixFormat. Marked obsolete with NLog 6.0")] [EditorBrowsable(EditorBrowsableState.Never)] public string ArchiveNumbering { get { return _archiveNumbering ?? "Sequence"; } set { string text = value?.Trim() ?? string.Empty; if (!string.IsNullOrEmpty(text) && !string.Equals(_archiveNumbering, text, StringComparison.OrdinalIgnoreCase)) { _archiveNumbering = text; if (_archiveSuffixFormat == null || (object)_archiveSuffixFormat == _legacyDateArchiveSuffixFormat || (object)_archiveSuffixFormat == _legacySequenceArchiveSuffixFormat) { ArchiveSuffixFormat = ((text.IndexOf("date", StringComparison.OrdinalIgnoreCase) >= 0) ? _legacyDateArchiveSuffixFormat : _legacySequenceArchiveSuffixFormat); } } } } public string ArchiveSuffixFormat { get { if (ArchiveEvery != 0 && (_archiveSuffixFormat == null || (object)_legacyDateArchiveSuffixFormat == _archiveSuffixFormat || (object)_legacySequenceArchiveSuffixFormat == _archiveSuffixFormat) && ArchiveFileName != null) { return ArchiveEvery switch { FileArchivePeriod.Year => "_{1:yyyy}_{0:00}", FileArchivePeriod.Month => "_{1:yyyyMM}_{0:00}", FileArchivePeriod.Hour => "_{1:yyyyMMddHH}_{0:00}", FileArchivePeriod.Minute => "_{1:yyyyMMddHHmm}_{0:00}", _ => _legacyDateArchiveSuffixFormat, }; } return _archiveSuffixFormat ?? _legacySequenceArchiveSuffixFormat; } set { if (!string.IsNullOrEmpty(value) && ArchiveFileName is SimpleLayout simpleLayout && !string.IsNullOrEmpty(simpleLayout.OriginalText) && StringHelpers.IsNullOrWhiteSpace(Path.GetFileNameWithoutExtension(simpleLayout.OriginalText)) && value.IndexOf('_') == 0) { value = value.Substring(1); } _archiveSuffixFormat = value; string? archiveSuffixFormat = _archiveSuffixFormat; _archiveSuffixFormatLegacy = archiveSuffixFormat != null && archiveSuffixFormat.IndexOf("{1", StringComparison.Ordinal) >= 0; _fileArchiveHandler = null; } } public bool WriteFooterOnArchivingOnly { get; set; } private int OpenFileMonitorTimerInterval { get { if (OpenFileFlushTimeout <= 0 || AutoFlush || !KeepFileOpen) { if (OpenFileCacheTimeout <= 500 || OpenFileCacheTimeout >= 3600) { return OpenFileCacheTimeout; } return 300; } if (OpenFileCacheTimeout <= 0) { return OpenFileFlushTimeout; } return Math.Min(OpenFileFlushTimeout, OpenFileCacheTimeout); } } private IFileArchiveHandler FileAchiveHandler => _fileArchiveHandler ?? (_fileArchiveHandler = CreateFileArchiveHandler()); public FileTarget() { _getFileNameFromLayout = (AsyncLogEventInfo l) => GetFileNameFromLayout(l.LogEvent); } public FileTarget(string name) : this() { base.Name = name; } protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { InternalLogger.Trace("{0}: FlushAsync", this); if (_openFileCache.Count > 0) { foreach (KeyValuePair item in _openFileCache) { item.Value.FileAppender.Flush(); } } asyncContinuation(null); InternalLogger.Trace("{0}: FlushAsync Done", this); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "FlushAsync")) { throw; } asyncContinuation(exception); } } protected override void InitializeTarget() { if (FileName == null || FileName == NLog.Layouts.Layout.Empty) { throw new NLogConfigurationException("FileTarget FileName-property must be assigned. FileName is needed for file writing."); } if (OpenFileMonitorTimerInterval > 0) { _openFileMonitorTimer = new Timer(OpenFileMonitorTimer); } base.InitializeTarget(); } protected override void CloseTarget() { Timer? openFileMonitorTimer = _openFileMonitorTimer; _openFileMonitorTimer = null; openFileMonitorTimer?.Change(-1, -1); openFileMonitorTimer?.Dispose(); if (_openFileCache.Count > 0) { foreach (KeyValuePair item in _openFileCache.ToList()) { CloseFileWithFooter(item.Key, item.Value, archiveFile: false); } _openFileCache.Clear(); } base.CloseTarget(); } protected override void Write(LogEventInfo logEvent) { string fileNameFromLayout = GetFileNameFromLayout(logEvent); if (string.IsNullOrEmpty(fileNameFromLayout)) { throw new ArgumentException("The path is not of a legal form."); } try { ReusableObjectCreator.LockOject lockOject = _reusableBatchFileWriteStream.Allocate(); try { ReusableObjectCreator.LockOject lockOject2 = ReusableLayoutBuilder.Allocate(); try { ReusableObjectCreator.LockOject lockOject3 = _reusableEncodingBuffer.Allocate(); try { RenderFormattedMessageToStream(logEvent, lockOject2.Result, lockOject3.Result, lockOject.Result); } finally { ((IDisposable)lockOject3).Dispose(); } } finally { ((IDisposable)lockOject2).Dispose(); } WriteBytesToFile(fileNameFromLayout, logEvent, lockOject.Result); } finally { ((IDisposable)lockOject).Dispose(); } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed writing to FileName: '{1}'", new ReadOnlySpan(new object[2] { this, fileNameFromLayout })); throw; } } protected override void Write(IList logEvents) { foreach (KeyValuePair> item in logEvents.BucketSort(_getFileNameFromLayout)) { if (string.IsNullOrEmpty(item.Key)) { InternalLogger.Warn("{0}: FileName Layout returned empty string. The path is not of a legal form.", this); ArgumentException exception = new ArgumentException("The path is not of a legal form."); for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(exception); } continue; } try { WriteLogEventsToFile(item.Key, item.Value); } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed writing to FileName: '{1}'", new ReadOnlySpan(new object[2] { this, item.Key })); if (ExceptionMustBeRethrown(ex, "Write")) { throw; } for (int j = 0; j < item.Value.Count; j++) { item.Value[j].Continuation(ex); } } } } private void WriteLogEventsToFile(string filename, IList logEvents) { ReusableObjectCreator.LockOject lockOject = _reusableBatchFileWriteStream.Allocate(); try { MemoryStream memoryStream = lockOject.Result ?? new MemoryStream(); int num = 0; while (num < logEvents.Count) { memoryStream.Position = 0L; memoryStream.SetLength(0L); int num2 = WriteToMemoryStream(logEvents, num, memoryStream); WriteBytesToFile(filename, logEvents[num].LogEvent, memoryStream); for (int i = 0; i < num2; i++) { logEvents[num++].Continuation(null); } } } finally { ((IDisposable)lockOject).Dispose(); } } private string GetFileNameFromLayout(LogEventInfo logEvent) { if (_fixedFileName != null) { return _fixedFileName; } string text = _lastFileNameFromLayout; ReusableObjectCreator.LockOject lockOject = ReusableLayoutBuilder.Allocate(); try { FileName.Render(logEvent, lockOject.Result); if (lockOject.Result.EqualTo(text)) { return _lastFileNameFromLayout; } text = lockOject.Result.ToString(); } finally { ((IDisposable)lockOject).Dispose(); } _lastFileNameFromLayout = text; return text; } private int WriteToMemoryStream(IList logEvents, int startIndex, MemoryStream ms) { long num = BufferSize * 100; ReusableObjectCreator.LockOject lockOject = _reusableFileWriteStream.Allocate(); try { ReusableObjectCreator.LockOject lockOject2 = ReusableLayoutBuilder.Allocate(); try { ReusableObjectCreator.LockOject lockOject3 = _reusableEncodingBuffer.Allocate(); try { StringBuilder result = lockOject2.Result; char[] result2 = lockOject3.Result; MemoryStream result3 = lockOject.Result; for (int i = startIndex; i < logEvents.Count; i++) { result3.Position = 0L; result3.SetLength(0L); result.ClearBuilder(); RenderFormattedMessageToStream(logEvents[i].LogEvent, result, result2, result3); ms.Write(result3.GetBuffer(), 0, (int)result3.Length); if (ms.Length > num && !ReplaceFileContentsOnEachWrite) { return i - startIndex + 1; } } } finally { ((IDisposable)lockOject3).Dispose(); } } finally { ((IDisposable)lockOject2).Dispose(); } } finally { ((IDisposable)lockOject).Dispose(); } return logEvents.Count - startIndex; } private void RenderFormattedMessageToStream(LogEventInfo logEvent, StringBuilder formatBuilder, char[] transformBuffer, MemoryStream streamTarget) { RenderFormattedMessage(logEvent, formatBuilder); formatBuilder.Append(LineEnding.NewLineCharacters); formatBuilder.CopyToStream(streamTarget, Encoding, transformBuffer); } protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { Layout.Render(logEvent, target); } private void WriteBytesToFile(string filename, LogEventInfo firstLogEvent, MemoryStream ms) { bool hasWritten = true; if (!_openFileCache.TryGetValue(filename, out var value)) { hasWritten = false; value = OpenFile(filename, firstLogEvent, null); } try { if (ArchiveAboveSize > 0 || ArchiveEvery != 0) { value = RollArchiveFile(filename, value, firstLogEvent, hasWritten); } value.FileAppender.Write(firstLogEvent.TimeStamp, ms.GetBuffer(), 0, (int)ms.Length); if (AutoFlush) { value.FileAppender.Flush(); } } catch { _openFileCache.Remove(filename); value.FileAppender.Dispose(); throw; } } private OpenFileAppender RollArchiveFile(string filename, OpenFileAppender openFile, LogEventInfo firstLogEvent, bool hasWritten) { int num = -1; bool flag = ArchiveFileName == null; while (num != openFile.SequenceNumber && MustArchiveFile(openFile.FileAppender, firstLogEvent)) { num = openFile.SequenceNumber; DateTime? dateTime = (flag ? null : new DateTime?(openFile.FileAppender.FileLastModified)); if (dateTime > openFile.FileAppender.LastWriteTime) { if (!(dateTime == openFile.FileAppender.OpenStreamTime)) { DateTime date = firstLogEvent.TimeStamp.Date; DateTime? obj = dateTime?.Date; if (!(date == obj)) { goto IL_00ff; } } dateTime = openFile.FileAppender.LastWriteTime; } goto IL_00ff; IL_00ff: if (hasWritten) { CloseFileWithFooter(filename, openFile, archiveFile: true); } else { CloseFile(filename, openFile); } hasWritten = false; openFile = OpenFile(filename, firstLogEvent, dateTime, openFile.SequenceNumber + 1); } return openFile; } private bool MustArchiveFile(IFileAppender fileAppender, LogEventInfo firstLogEvent) { if (ArchiveAboveSize > 0 && MustArchiveBySize(fileAppender)) { return true; } if (ArchiveEvery != 0 && MustArchiveEveryTimePeriod(fileAppender, firstLogEvent)) { return true; } return false; } private bool MustArchiveBySize(IFileAppender fileAppender) { long fileSize = fileAppender.FileSize; if (fileSize == 0L || fileSize + 1 < ArchiveAboveSize) { return false; } InternalLogger.Debug("{0}: Archive because of rolling filesize={1} for file: {2}", this, fileSize, fileAppender.FilePath); return true; } private bool MustArchiveEveryTimePeriod(IFileAppender fileAppender, LogEventInfo firstLogEvent) { DateTime nextArchiveTime = fileAppender.NextArchiveTime; if (nextArchiveTime >= firstLogEvent.TimeStamp) { return false; } InternalLogger.Debug("{0}: Archive because of rolling filetime={1} for file: {2}", this, nextArchiveTime, fileAppender.FilePath); return true; } internal static DateTime CalculateNextArchiveEventTime(FileArchivePeriod archiveEvery, DateTime fileBirthTime) { return archiveEvery switch { FileArchivePeriod.Year => new DateTime(fileBirthTime.Year, 1, 1, 0, 0, 0, fileBirthTime.Kind).AddYears(1), FileArchivePeriod.Month => new DateTime(fileBirthTime.Year, fileBirthTime.Month, 1, 0, 0, 0, fileBirthTime.Kind).AddMonths(1), FileArchivePeriod.Day => new DateTime(fileBirthTime.Year, fileBirthTime.Month, fileBirthTime.Day, 0, 0, 0, fileBirthTime.Kind).AddDays(1.0), FileArchivePeriod.Hour => new DateTime(fileBirthTime.Year, fileBirthTime.Month, fileBirthTime.Day, fileBirthTime.Hour, 0, 0, fileBirthTime.Kind).AddHours(1.0), FileArchivePeriod.Minute => new DateTime(fileBirthTime.Year, fileBirthTime.Month, fileBirthTime.Day, fileBirthTime.Hour, fileBirthTime.Minute, 0, fileBirthTime.Kind).AddMinutes(1.0), FileArchivePeriod.Monday => CalculateNextWeekday(fileBirthTime, DayOfWeek.Monday), FileArchivePeriod.Tuesday => CalculateNextWeekday(fileBirthTime, DayOfWeek.Tuesday), FileArchivePeriod.Wednesday => CalculateNextWeekday(fileBirthTime, DayOfWeek.Wednesday), FileArchivePeriod.Thursday => CalculateNextWeekday(fileBirthTime, DayOfWeek.Thursday), FileArchivePeriod.Friday => CalculateNextWeekday(fileBirthTime, DayOfWeek.Friday), FileArchivePeriod.Saturday => CalculateNextWeekday(fileBirthTime, DayOfWeek.Saturday), FileArchivePeriod.Sunday => CalculateNextWeekday(fileBirthTime, DayOfWeek.Sunday), _ => DateTime.MaxValue, }; } public static DateTime CalculateNextWeekday(DateTime previousLogEventTimestamp, DayOfWeek dayOfWeek) { int dayOfWeek2 = (int)previousLogEventTimestamp.DayOfWeek; int num = (int)dayOfWeek; if (num <= dayOfWeek2) { num += 7; } return previousLogEventTimestamp.Date.AddDays(num - dayOfWeek2); } private OpenFileAppender OpenFile(string filename, LogEventInfo firstLogEvent, DateTime? previousFileLastModified, int sequenceNumber = 0) { bool num = sequenceNumber == 0 && CreateDirs && _openFileCache.Count == 0; PruneOpenFileCache(); sequenceNumber = FileAchiveHandler.ArchiveBeforeOpenFile(filename, firstLogEvent, previousFileLastModified, sequenceNumber); string text = BuildFullFilePath(filename, sequenceNumber); if (num) { InternalLogger.Debug("{0}: Verify directory and creating writer to file: {1}", this, text); string directoryName = Path.GetDirectoryName(text); if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } } else { InternalLogger.Debug("{0}: Creating writer to file: {1}", this, text); } IFileAppender fileAppender = CreateFileAppender(text); OpenFileAppender openFileAppender = new OpenFileAppender(fileAppender, sequenceNumber); _openFileCache[filename] = openFileAppender; if (_openFileCache.Count == 1) { _openFileMonitorTimer?.Change(OpenFileMonitorTimerInterval * 1000, -1); } return openFileAppender; } private void PruneOpenFileCache() { while (_openFileCache.Count > 0) { KeyValuePair keyValuePair = default(KeyValuePair); foreach (KeyValuePair item in _openFileCache) { if (!item.Value.FileAppender.VerifyFileExists()) { keyValuePair = item; break; } } if (string.IsNullOrEmpty(keyValuePair.Key)) { break; } CloseFile(keyValuePair.Key, keyValuePair.Value); } while (_openFileCache.Count >= OpenFileCacheSize) { DateTime maxValue = DateTime.MaxValue; KeyValuePair keyValuePair2 = default(KeyValuePair); foreach (KeyValuePair item2 in _openFileCache) { if (item2.Value.FileAppender.LastWriteTime < maxValue) { keyValuePair2 = item2; } } if (!string.IsNullOrEmpty(keyValuePair2.Key)) { CloseFileWithFooter(keyValuePair2.Key, keyValuePair2.Value, archiveFile: false); continue; } break; } } internal void CloseOpenFileBeforeArchiveCleanup(string filepath) { string a = ((_openFileCache.Count > 0) ? Path.GetFileName(filepath) : string.Empty); KeyValuePair keyValuePair; do { keyValuePair = default(KeyValuePair); foreach (KeyValuePair item in _openFileCache) { string fileName = Path.GetFileName(item.Value.FileAppender.FilePath); if (string.Equals(a, fileName, StringComparison.OrdinalIgnoreCase)) { keyValuePair = item; break; } } if (keyValuePair.Key != null) { InternalLogger.Debug("{0}: Archive cleanup closing file: {1}", this, filepath); CloseFile(keyValuePair.Key, keyValuePair.Value); } } while (keyValuePair.Key != null); } private void CloseFile(string filename, OpenFileAppender openFile) { try { _openFileCache.Remove(filename); if (_openFileCache.Count == 0) { _openFileMonitorTimer?.Change(-1, -1); } } finally { openFile.FileAppender.Dispose(); } } private void CloseFileWithFooter(string filename, OpenFileAppender openFile, bool archiveFile) { try { if (!ReplaceFileContentsOnEachWrite && (!WriteFooterOnArchivingOnly || archiveFile)) { byte[] footerLayoutBytes = GetFooterLayoutBytes(); if (footerLayoutBytes != null && footerLayoutBytes.Length != 0) { openFile.FileAppender.Write(openFile.FileAppender.FileLastModified, footerLayoutBytes, 0, footerLayoutBytes.Length); } } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed closing file: '{1}'", new ReadOnlySpan(new object[2] { this, filename })); if (ex.MustBeRethrownImmediately()) { throw; } } finally { CloseFile(filename, openFile); } } private void OpenFileMonitorTimer(object? state) { bool flag = _openFileMonitorTimer != null; try { lock (base.SyncRoot) { flag = _openFileCache.Count != 0 && _openFileMonitorTimer != null; if (OpenFileCacheTimeout > 0) { PruneOpenFileCacheUsingTimeout(); } if (OpenFileFlushTimeout > 0 && !AutoFlush) { DateTime dateTime = TimeSource.Current.Time.AddSeconds((double)(-(OpenFileFlushTimeout + 1)) * 1.5); foreach (KeyValuePair item in _openFileCache) { if (item.Value.FileAppender.LastWriteTime > dateTime) { item.Value.FileAppender.Flush(); } } } flag = flag && _openFileCache.Count != 0; } } catch (Exception ex) { InternalLogger.Warn(ex, "{0}: Exception in OpenFileMonitorTimer", new ReadOnlySpan(new object[1] { this })); } finally { if (flag) { _openFileMonitorTimer?.Change(OpenFileMonitorTimerInterval * 1000, -1); } } } private void PruneOpenFileCacheUsingTimeout() { DateTime dateTime = TimeSource.Current.Time.AddSeconds(-OpenFileCacheTimeout); bool flag = false; foreach (KeyValuePair item in _openFileCache) { if (item.Value.FileAppender.LastWriteTime < dateTime) { flag = true; break; } } if (!flag) { return; } foreach (KeyValuePair item2 in _openFileCache.ToList()) { if (item2.Value.FileAppender.LastWriteTime < dateTime) { CloseFile(item2.Key, item2.Value); } } } internal string BuildFullFilePath(string newFileName, int sequenceNumber, DateTime fileLastModified = default(DateTime)) { if (sequenceNumber > 0 || fileLastModified != default(DateTime)) { string text = Path.GetFileName(newFileName) ?? string.Empty; string text2 = Path.GetExtension(text) ?? string.Empty; newFileName = newFileName.Substring(0, newFileName.Length - text.Length); if (!string.IsNullOrEmpty(text2)) { text = text.Substring(0, text.Length - text2.Length); } object arg = ((fileLastModified == default(DateTime)) ? string.Empty : ((object)fileLastModified)); CultureInfo provider = base.LoggingConfiguration?.LogFactory?.DefaultCultureInfo ?? LogManager.LogFactory.DefaultCultureInfo; try { newFileName = newFileName + text + string.Format(provider, ArchiveSuffixFormat, sequenceNumber, arg) + text2; } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to apply ArchiveSuffixFormat={1} using SequenceNumber={2} for file: '{3}'", new ReadOnlySpan(new object[4] { this, ArchiveSuffixFormat, sequenceNumber, newFileName })); if (ExceptionMustBeRethrown(ex, "BuildFullFilePath")) { throw; } newFileName = newFileName + text + string.Format(provider, _legacySequenceArchiveSuffixFormat, sequenceNumber) + text2; } } return CleanFullFilePath(newFileName); } internal static string CleanFullFilePath(string filename) { int num = filename.LastIndexOfAny(DirectorySeparatorChars); char[] array = null; for (int i = num + 1; i < filename.Length; i++) { if (InvalidFileNameChars.Contains(filename[i])) { if (array == null) { array = filename.Substring(num + 1).ToCharArray(); } array[i - (num + 1)] = '_'; } } if (array != null) { filename = Path.Combine((num > 0) ? filename.Substring(0, num + 1) : string.Empty, new string(array)); } return Path.GetFullPath(FileInfoHelper.IsRelativeFilePath(filename) ? Path.Combine(AppEnvironmentWrapper.FixFilePathWithLongUNC(LogManager.LogFactory.CurrentAppEnvironment.AppDomainBaseDirectory), filename) : filename); } private static bool InitialValueBom(Encoding encoding) { int num = encoding?.CodePage ?? 0; if (num != 1200 && num != 1201 && num != 12000) { return num == 12001; } return true; } private byte[] GetLayoutBytes(Layout layout) { if (layout == null) { return ArrayHelper.Empty(); } ReusableObjectCreator.LockOject lockOject = ReusableLayoutBuilder.Allocate(); try { ReusableObjectCreator.LockOject lockOject2 = _reusableEncodingBuffer.Allocate(); try { layout.Render(LogEventInfo.CreateNullEvent(), lockOject.Result); lockOject.Result.Append(LineEnding.NewLineCharacters); using MemoryStream memoryStream = new MemoryStream(lockOject.Result.Length); lockOject.Result.CopyToStream(memoryStream, Encoding, lockOject2.Result); return memoryStream.ToArray(); } finally { ((IDisposable)lockOject2).Dispose(); } } finally { ((IDisposable)lockOject).Dispose(); } } internal byte[] GetFooterLayoutBytes() { if (base.Footer != null) { InternalLogger.Trace("{0}: Write footer", this); return GetLayoutBytes(base.Footer); } return ArrayHelper.Empty(); } internal Stream CreateFileStreamWithRetry(IFileAppender fileAppender, int bufferSize, bool initialFileOpen) { int num = 1; int num2 = ((!KeepFileOpen) ? 5 : 0); string filePath = fileAppender.FilePath; for (int i = 0; i <= num2; i++) { try { return CreateFileStreamWithDirectory(filePath, bufferSize, initialFileOpen); } catch (DirectoryNotFoundException) { throw; } catch (IOException ex2) { if (i >= num2) { throw; } int num3 = ((num > 4) ? new Random().Next(4, num) : num); InternalLogger.Warn("{0}: Attempt #{1} to open {2} failed - {3} {4}. Sleeping for {5}ms", new ReadOnlySpan(new object[6] { this, i, filePath, ex2.GetType(), ex2.Message, num3 })); num *= 4; Thread.Sleep(num3); } } throw new InvalidOperationException("Should not be reached."); } private Stream CreateFileStreamWithDirectory(string filePath, int bufferSize, bool initialFileOpen) { try { return OpenNewFileStream(filePath, bufferSize, initialFileOpen); } catch (DirectoryNotFoundException) { if (!CreateDirs) { throw; } InternalLogger.Debug("{0}: DirectoryNotFoundException - Attempting to create directory for file: {1}", this, filePath); string text = Path.GetDirectoryName(filePath) ?? string.Empty; try { Directory.CreateDirectory(text); } catch (Exception innerException) { throw new NLogRuntimeException("Could not create directory " + text, innerException); } return OpenNewFileStream(filePath, bufferSize, initialFileOpen); } } private Stream OpenNewFileStream(string filePath, int bufferSize, bool initialFileOpen) { Stream stream = CreateFileStream(filePath, bufferSize); try { bool? flag = null; if (WriteBom) { flag = ReplaceFileContentsOnEachWrite || stream.Length == 0; if (flag.GetValueOrDefault()) { InternalLogger.Trace("{0}: Write byte order mark from encoding={1}", this, Encoding); byte[] preamble = Encoding.GetPreamble(); if (preamble.Length != 0) { stream.Write(preamble, 0, preamble.Length); } } } if (base.Header != null && ((initialFileOpen && WriteHeaderWhenInitialFileNotEmpty) || ReplaceFileContentsOnEachWrite || (flag ?? (stream.Length == 0)))) { InternalLogger.Trace("{0}: Write header", this); byte[] layoutBytes = GetLayoutBytes(base.Header); stream.Write(layoutBytes, 0, layoutBytes.Length); } return stream; } catch { stream?.Dispose(); throw; } } protected virtual Stream CreateFileStream(string filePath, int bufferSize) { FileShare fileShare = FileShare.Read; if (EnableFileDelete) { fileShare |= FileShare.Delete; } FileMode mode = FileMode.Append; if (ReplaceFileContentsOnEachWrite) { mode = FileMode.Create; } return new FileStream(filePath, mode, FileAccess.Write, fileShare, bufferSize); } private IFileAppender CreateFileAppender(string filePath) { if (DiscardAll) { return new DiscardAllFileAppender(filePath); } if (ReplaceFileContentsOnEachWrite) { return new MinimalFileLockingAppender(this, filePath); } if (KeepFileOpen) { return new ExclusiveFileLockingAppender(this, filePath); } return new MinimalFileLockingAppender(this, filePath); } private IFileArchiveHandler CreateFileArchiveHandler() { if (MaxArchiveFiles < 0 && MaxArchiveDays == 0 && ArchiveAboveSize == 0L && ArchiveEvery == FileArchivePeriod.None) { if (!DeleteOldFileOnStartup && !ArchiveOldFileOnStartup) { return DisabledFileArchiveHandler.Default; } if (!ArchiveOldFileOnStartup) { return new ZeroFileArchiveHandler(this); } } if (MaxArchiveFiles == 0) { return new ZeroFileArchiveHandler(this); } if (ArchiveFileName == null) { return new RollingArchiveFileHandler(this); } return new LegacyArchiveFileNameHandler(this); } } internal interface IColoredConsolePrinter { IList DefaultConsoleRowHighlightingRules { get; } TextWriter AcquireTextWriter(TextWriter consoleStream, StringBuilder reusableBuilder); void ReleaseTextWriter(TextWriter consoleWriter, TextWriter consoleStream, ConsoleColor? oldForegroundColor, ConsoleColor? oldBackgroundColor, bool flush); ConsoleColor? ChangeForegroundColor(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? oldForegroundColor = null); ConsoleColor? ChangeBackgroundColor(TextWriter consoleWriter, ConsoleColor? backgroundColor, ConsoleColor? oldBackgroundColor = null); void ResetDefaultColors(TextWriter consoleWriter, ConsoleColor? foregroundColor, ConsoleColor? backgroundColor); void WriteSubString(TextWriter consoleWriter, string text, int index, int endIndex); void WriteChar(TextWriter consoleWriter, char text); void WriteLine(TextWriter consoleWriter, string text); } public class JsonSerializeOptions { [Obsolete("Marked obsolete with NLog 5.0.")] [EditorBrowsable(EditorBrowsableState.Never)] public bool QuoteKeys { get; set; } = true; [Obsolete("Marked obsolete with NLog 5.0. Should always be InvariantCulture.")] [EditorBrowsable(EditorBrowsableState.Never)] public IFormatProvider? FormatProvider { get; set; } [Obsolete("Marked obsolete with NLog 5.0. Should always be InvariantCulture.")] [EditorBrowsable(EditorBrowsableState.Never)] public string? Format { get; set; } public bool EscapeUnicode { get; set; } [Obsolete("Marked obsolete with NLog 5.5. Should never escape forward slash")] [EditorBrowsable(EditorBrowsableState.Never)] public bool EscapeForwardSlash { get; set; } public bool EnumAsInteger { get; set; } public bool SuppressSpaces { get; set; } = true; public bool SanitizeDictionaryKeys { get; set; } public int MaxRecursionLimit { get; set; } = 10; } [TypeConverter(typeof(LineEndingModeConverter))] public sealed class LineEndingMode : IEquatable { public class LineEndingModeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (!(sourceType == typeof(string))) { return base.CanConvertFrom(context, sourceType); } return true; } public override object? ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (!(value is string name)) { return base.ConvertFrom(context, culture, value); } return FromString(name); } } public static readonly LineEndingMode Default = new LineEndingMode("Default", Environment.NewLine); public static readonly LineEndingMode CRLF = new LineEndingMode("CRLF", "\r\n"); public static readonly LineEndingMode CR = new LineEndingMode("CR", "\r"); public static readonly LineEndingMode LF = new LineEndingMode("LF", "\n"); public static readonly LineEndingMode Null = new LineEndingMode("Null", "\0"); public static readonly LineEndingMode None = new LineEndingMode("None", string.Empty); private readonly string _name; private readonly string _newLineCharacters; public string Name => _name; public string NewLineCharacters => _newLineCharacters; private LineEndingMode() { _name = string.Empty; _newLineCharacters = string.Empty; } private LineEndingMode(string name, string newLineCharacters) { _name = name; _newLineCharacters = newLineCharacters; } public static LineEndingMode FromString(string name) { Guard.ThrowIfNull(name, "name"); if (name.Equals(CRLF.Name, StringComparison.OrdinalIgnoreCase)) { return CRLF; } if (name.Equals(LF.Name, StringComparison.OrdinalIgnoreCase)) { return LF; } if (name.Equals(CR.Name, StringComparison.OrdinalIgnoreCase)) { return CR; } if (name.Equals(Default.Name, StringComparison.OrdinalIgnoreCase)) { return Default; } if (name.Equals(Null.Name, StringComparison.OrdinalIgnoreCase)) { return Null; } if (name.Equals(None.Name, StringComparison.OrdinalIgnoreCase)) { return None; } throw new ArgumentOutOfRangeException("name", name, "LineEndingMode is out of range"); } public static bool operator ==(LineEndingMode mode1, LineEndingMode mode2) { if ((object)mode1 == null) { return (object)mode2 == null; } if ((object)mode2 == null) { return false; } return mode1.NewLineCharacters == mode2.NewLineCharacters; } public static bool operator !=(LineEndingMode mode1, LineEndingMode mode2) { if ((object)mode1 == null) { return (object)mode2 != null; } if ((object)mode2 == null) { return true; } return mode1.NewLineCharacters != mode2.NewLineCharacters; } public override string ToString() { return Name; } public override int GetHashCode() { return _newLineCharacters?.GetHashCode() ?? 0; } public override bool Equals(object? obj) { if (obj is LineEndingMode other) { return Equals(other); } return false; } public bool Equals(LineEndingMode? other) { if ((object)this != other) { return string.Equals(_newLineCharacters, other?._newLineCharacters, StringComparison.Ordinal); } return true; } } [Target("Memory")] public sealed class MemoryTarget : TargetWithLayoutHeaderAndFooter { private sealed class ThreadSafeList : IList, ICollection, IEnumerable, IEnumerable { [CompilerGenerated] private sealed class d__17 : IEnumerator, IEnumerator, IDisposable { private int <>1__state; private T <>2__current; public ThreadSafeList <>4__this; private List <>7__wrap1; private bool <>7__wrap2; private List.Enumerator <>7__wrap3; T IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__17(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if ((uint)(num - -4) <= 1u || num == 1) { try { if (num == -4 || num == 1) { try { } finally { <>m__Finally2(); } } } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>7__wrap3 = default(List.Enumerator); <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; ThreadSafeList threadSafeList = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = threadSafeList._list; <>7__wrap2 = false; <>1__state = -3; Monitor.Enter(<>7__wrap1, ref <>7__wrap2); <>7__wrap3 = threadSafeList._list.GetEnumerator(); <>1__state = -4; break; case 1: <>1__state = -4; break; } if (<>7__wrap3.MoveNext()) { T current = <>7__wrap3.Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally2(); <>7__wrap3 = default(List.Enumerator); <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap2) { Monitor.Exit(<>7__wrap1); } } private void <>m__Finally2() { <>1__state = -3; ((IDisposable)<>7__wrap3).Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__18 : IEnumerator, IEnumerator, IDisposable { private int <>1__state; private object <>2__current; public ThreadSafeList <>4__this; private List <>7__wrap1; private bool <>7__wrap2; private List.Enumerator <>7__wrap3; object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__18(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if ((uint)(num - -4) <= 1u || num == 1) { try { if (num == -4 || num == 1) { try { } finally { <>m__Finally2(); } } } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>7__wrap3 = default(List.Enumerator); <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; ThreadSafeList threadSafeList = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = threadSafeList._list; <>7__wrap2 = false; <>1__state = -3; Monitor.Enter(<>7__wrap1, ref <>7__wrap2); <>7__wrap3 = threadSafeList._list.GetEnumerator(); <>1__state = -4; break; case 1: <>1__state = -4; break; } if (<>7__wrap3.MoveNext()) { T current = <>7__wrap3.Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally2(); <>7__wrap3 = default(List.Enumerator); <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap2) { Monitor.Exit(<>7__wrap1); } } private void <>m__Finally2() { <>1__state = -3; ((IDisposable)<>7__wrap3).Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private readonly List _list = new List(); public T this[int index] { get { lock (_list) { return _list[index]; } } set { lock (_list) { _list[index] = value; } } } public int Count => _list.Count; bool ICollection.IsReadOnly => ((ICollection)_list).IsReadOnly; public void Add(T item) { lock (_list) { _list.Add(item); } } public void Add(T item, int maxListCount) { lock (_list) { if (maxListCount > 0) { while (_list.Count >= maxListCount) { _list.RemoveAt(0); } } _list.Add(item); } } void ICollection.Clear() { lock (_list) { _list.Clear(); } } bool ICollection.Contains(T item) { lock (_list) { return _list.Contains(item); } } void ICollection.CopyTo(T[] array, int arrayIndex) { lock (_list) { _list.CopyTo(array, arrayIndex); } } public int IndexOf(T item) { lock (_list) { return _list.IndexOf(item); } } public void Insert(int index, T item) { lock (_list) { _list.Insert(index, item); } } bool ICollection.Remove(T item) { lock (_list) { return _list.Remove(item); } } public void RemoveAt(int index) { lock (_list) { _list.RemoveAt(index); } } [IteratorStateMachine(typeof(ThreadSafeList<>.d__17))] public IEnumerator GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__17(0) { <>4__this = this }; } [IteratorStateMachine(typeof(ThreadSafeList<>.d__18))] IEnumerator IEnumerable.GetEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__18(0) { <>4__this = this }; } } private readonly ThreadSafeList _logs = new ThreadSafeList(); public IList Logs => _logs; public int MaxLogsCount { get; set; } public MemoryTarget() { } public MemoryTarget(string name) : this() { base.Name = name; } protected override void InitializeTarget() { base.InitializeTarget(); if (base.Header != null) { _logs.Add(RenderLogEvent(base.Header, LogEventInfo.CreateNullEvent())); } } protected override void CloseTarget() { if (base.Footer != null) { _logs.Add(RenderLogEvent(base.Footer, LogEventInfo.CreateNullEvent())); } base.CloseTarget(); } protected override void Write(LogEventInfo logEvent) { _logs.Add(RenderLogEvent(Layout, logEvent), MaxLogsCount); } } [NLogConfigurationItem] public class MethodCallParameter { private readonly ValueTypeLayoutInfo _layoutInfo = new ValueTypeLayoutInfo(); public string Name { get; set; } = string.Empty; public Layout Layout { get { return _layoutInfo.Layout; } set { _layoutInfo.Layout = value; } } [Obsolete("Use property ParameterType instead. Marked obsolete on NLog 4.6")] [EditorBrowsable(EditorBrowsableState.Never)] public Type Type { get { return ParameterType; } set { ParameterType = value; } } public Type ParameterType { get { return _layoutInfo.ValueType ?? typeof(string); } set { _layoutInfo.ValueType = value; } } public Layout? DefaultValue { get { return _layoutInfo.DefaultValue; } set { _layoutInfo.DefaultValue = value; } } public MethodCallParameter() { ParameterType = typeof(string); } public MethodCallParameter(Layout layout) { ParameterType = typeof(string); Layout = layout; } public MethodCallParameter(string parameterName, Layout layout) { ParameterType = typeof(string); Name = parameterName; Layout = layout; } public MethodCallParameter(string name, Layout layout, Type type) { ParameterType = type; Name = name; Layout = layout; } public object? RenderValue(LogEventInfo logEvent) { return _layoutInfo.RenderValue(logEvent); } } [Target("MethodCall")] public sealed class MethodCallTarget : MethodCallTargetBase { private Action? _logEventAction; public string ClassName { get; set; } = string.Empty; public string MethodName { get; set; } = string.Empty; public MethodCallTarget() { } public MethodCallTarget(string name) { base.Name = name; } public MethodCallTarget(string name, Action logEventAction) { base.Name = name; _logEventAction = logEventAction; } protected override void InitializeTarget() { base.InitializeTarget(); if (!string.IsNullOrEmpty(ClassName) && !string.IsNullOrEmpty(MethodName)) { _logEventAction = BuildLogEventAction(ClassName, MethodName); } else if (_logEventAction == null) { throw new NLogConfigurationException("MethodCallTarget: Missing configuration of ClassName and MethodName"); } } [UnconditionalSuppressMessage("Trimming - Allow method lookup from config", "IL2075")] private static Action BuildLogEventAction(string className, string methodName) { Type type = PropertyTypeConverter.ConvertToType(className.Trim(), throwOnError: false); if ((object)type == null) { throw new NLogConfigurationException("MethodCallTarget: failed to get type from ClassName=" + className); } MethodInfo method = type.GetMethod(methodName); if ((object)method == null) { throw new NLogConfigurationException("MethodCallTarget: MethodName=" + methodName + " not found in ClassName=" + className + " - and must be static method"); } if (!method.IsStatic) { throw new NLogConfigurationException("MethodCallTarget: MethodName=" + methodName + " found in ClassName=" + className + " - but not static method"); } return BuildLogEventAction(method); } private static Action BuildLogEventAction(MethodInfo methodInfo) { MethodInfo methodInfo2 = methodInfo; int neededParameters = methodInfo2.GetParameters().Length; ReflectionHelpers.LateBoundMethod lateBoundMethod = null; return delegate(LogEventInfo logEvent, object?[] parameters) { if (neededParameters - parameters.Length > 0) { object[] array = new object[neededParameters]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i]; } for (int j = parameters.Length; j < neededParameters; j++) { array[j] = Type.Missing; } parameters = array; methodInfo2.Invoke(null, parameters); } else if (parameters.Length != neededParameters && neededParameters != 0) { methodInfo2.Invoke(null, parameters); } else { parameters = ((neededParameters == 0) ? ArrayHelper.Empty() : parameters); if (lateBoundMethod == null) { lateBoundMethod = CreateFastInvoke(methodInfo2, parameters) ?? CreateNormalInvoke(methodInfo2, parameters); } else { CallMethod(lateBoundMethod, parameters); } } }; } private static ReflectionHelpers.LateBoundMethod? CreateFastInvoke(MethodInfo methodInfo, object?[] parameters) { try { ReflectionHelpers.LateBoundMethod lateBoundMethod = ReflectionHelpers.CreateLateBoundMethod(methodInfo); CallMethod(lateBoundMethod, parameters); return lateBoundMethod; } catch (Exception ex) { InternalLogger.Warn(ex, "MethodCallTarget: Failed to create expression method {0} - {1}", new ReadOnlySpan(new object[2] { methodInfo.Name, ex.Message })); return null; } } private static void CallMethod(ReflectionHelpers.LateBoundMethod lateBoundMethod, object?[] parameters) { lateBoundMethod(null, parameters); } private static ReflectionHelpers.LateBoundMethod CreateNormalInvoke(MethodInfo methodInfo, object?[] parameters) { MethodInfo methodInfo2 = methodInfo; ReflectionHelpers.LateBoundMethod lateBoundMethod = (object target, object?[] args) => methodInfo2.Invoke(null, args); try { CallMethod(lateBoundMethod, parameters); return lateBoundMethod; } catch (Exception ex) { InternalLogger.Warn(ex, "MethodCallTarget: Failed to invoke reflection method {0} - {1}", new ReadOnlySpan(new object[2] { methodInfo2.Name, ex.Message })); return lateBoundMethod; } } protected override void DoInvoke(object?[] parameters, AsyncLogEventInfo logEvent) { try { ExecuteLogMethod(parameters, logEvent.LogEvent); logEvent.Continuation(null); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "DoInvoke")) { throw; } logEvent.Continuation(exception); } } protected override void DoInvoke(object?[] parameters) { throw new NotSupportedException(); } private void ExecuteLogMethod(object?[] parameters, LogEventInfo logEvent) { if (_logEventAction == null) { InternalLogger.Debug("{0}: No invoke because class/method was not found or set", this); return; } try { _logEventAction(logEvent, parameters); } catch (TargetInvocationException ex) { InternalLogger.Warn("{0}: Failed to invoke method - {1}", this, ex.Message); if (ex.InnerException != null) { throw ex.InnerException; } throw; } } } public abstract class MethodCallTargetBase : Target { [ArrayParameter(typeof(MethodCallParameter), "parameter")] public IList Parameters { get; } protected MethodCallTargetBase() { Parameters = new List(); } protected override void Write(AsyncLogEventInfo logEvent) { object[] array = ((Parameters.Count > 0) ? new object[Parameters.Count] : ArrayHelper.Empty()); for (int i = 0; i < array.Length; i++) { try { object obj = Parameters[i].RenderValue(logEvent.LogEvent); array[i] = obj; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Warn(ex, "{0}: Failed to get parameter value {1}", new ReadOnlySpan(new object[2] { this, Parameters[i].Name })); throw; } } DoInvoke(array, logEvent); } protected virtual void DoInvoke(object?[] parameters, AsyncLogEventInfo logEvent) { try { DoInvoke(parameters); logEvent.Continuation(null); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "DoInvoke")) { throw; } logEvent.Continuation(exception); } } protected abstract void DoInvoke(object?[] parameters); } [Target("Null")] public sealed class NullTarget : TargetWithLayout { private int _logEventCounter; private StringBuilder? _lastMesageBuilder; private LogEventInfo? _lastLogEvent; public int LogEventCounter => _logEventCounter; public bool FormatMessage { get; set; } public string LastMessage => _lastMesageBuilder?.ToString() ?? string.Empty; public LogEventInfo? LastLogEvent => _lastLogEvent; public NullTarget() { } public NullTarget(string name) : this() { base.Name = name; } protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { if (FormatMessage) { base.WriteAsyncThreadSafe(logEvent); return; } Interlocked.Increment(ref _logEventCounter); logEvent.Continuation(null); } protected override void WriteAsyncThreadSafe(IList logEvents) { if (FormatMessage) { base.WriteAsyncThreadSafe(logEvents); return; } Interlocked.Add(ref _logEventCounter, logEvents.Count); for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(null); } } protected override void Write(LogEventInfo logEvent) { _logEventCounter++; if (FormatMessage) { _lastLogEvent = logEvent; StringBuilder stringBuilder = _lastMesageBuilder ?? (_lastMesageBuilder = new StringBuilder(128)); stringBuilder.Length = 0; Layout?.Render(logEvent, stringBuilder); } } } [NLogConfigurationItem] public abstract class Target : ISupportsInitialize, IInternalLoggerContext, IDisposable { internal string? _tostring; private Layout[] _allLayouts = ArrayHelper.Empty(); private bool _allLayoutsAreThreadAgnostic; private bool _anyLayoutsAreThreadAgnosticImmutable; private bool _scannedForLayouts; private Exception? _initializeException; private string _name = string.Empty; private bool? _optimizeBufferReuse; internal bool? _layoutWithLock; private volatile bool _isInitialized; internal readonly ReusableBuilderCreator ReusableLayoutBuilder = new ReusableBuilderCreator(); private StringBuilderPool? _precalculateStringBuilderPool; internal StackTraceUsage StackTraceUsage { get; private set; } internal Exception? InitializeException => _initializeException; public string Name { get { return _name; } set { _name = value; _tostring = null; } } [Obsolete("No longer used, and always returns true. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool OptimizeBufferReuse { get { return _optimizeBufferReuse.GetValueOrDefault(true); } set { _optimizeBufferReuse = (value ? new bool?(true) : null); } } [Obsolete("Temporary workaround for broken Layout Renderers that are not threadsafe. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool LayoutWithLock { get { return _layoutWithLock.GetValueOrDefault(); } set { _layoutWithLock = value; } } protected object SyncRoot { get; } = new object(); protected LoggingConfiguration? LoggingConfiguration { get; private set; } LogFactory? IInternalLoggerContext.LogFactory => LoggingConfiguration?.LogFactory; protected bool IsInitialized { get { if (_isInitialized) { return true; } lock (SyncRoot) { return _isInitialized; } } } void ISupportsInitialize.Initialize(LoggingConfiguration? configuration) { lock (SyncRoot) { bool isInitialized = _isInitialized; Initialize(configuration); if (isInitialized && configuration != null) { FindAllLayouts(); } } } void ISupportsInitialize.Close() { Close(); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public void Flush(AsyncContinuation asyncContinuation) { Guard.ThrowIfNull(asyncContinuation, "asyncContinuation"); asyncContinuation = AsyncHelpers.PreventMultipleCalls(asyncContinuation); if (Monitor.TryEnter(SyncRoot, 15000)) { try { if (!IsInitialized) { asyncContinuation(null); return; } try { FlushAsync(asyncContinuation); return; } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "Flush")) { throw; } asyncContinuation(exception); return; } } finally { Monitor.Exit(SyncRoot); } } asyncContinuation(new NLogRuntimeException($"Target {this} failed to flush after lock timeout.")); } public void PrecalculateVolatileLayouts(LogEventInfo logEvent) { if ((!_allLayoutsAreThreadAgnostic || (_anyLayoutsAreThreadAgnosticImmutable && !logEvent.IsLogEventThreadAgnosticImmutable())) && IsInitialized) { if (_layoutWithLock.GetValueOrDefault()) { PrecalculateVolatileLayoutsWithLock(logEvent); } else { PrecalculateVolatileLayoutsConcurrent(logEvent); } } } private void PrecalculateVolatileLayoutsConcurrent(LogEventInfo logEvent) { if (_precalculateStringBuilderPool == null) { Interlocked.CompareExchange(ref _precalculateStringBuilderPool, new StringBuilderPool(Environment.ProcessorCount * 2), null); } StringBuilderPool.ItemHolder itemHolder = _precalculateStringBuilderPool.Acquire(); try { Layout[] allLayouts = _allLayouts; foreach (Layout obj in allLayouts) { itemHolder.Item.ClearBuilder(); obj.PrecalculateBuilder(logEvent, itemHolder.Item); } } finally { ((IDisposable)itemHolder).Dispose(); } } private void PrecalculateVolatileLayoutsWithLock(LogEventInfo logEvent) { lock (SyncRoot) { ReusableObjectCreator.LockOject lockOject = ReusableLayoutBuilder.Allocate(); try { Layout[] allLayouts = _allLayouts; foreach (Layout obj in allLayouts) { lockOject.Result.ClearBuilder(); obj.PrecalculateBuilder(logEvent, lockOject.Result); } } finally { ((IDisposable)lockOject).Dispose(); } } } public override string ToString() { return _tostring ?? (_tostring = GenerateTargetToString(targetWrapper: false)); } internal string GenerateTargetToString(bool targetWrapper, string? targetName = null) { TargetAttribute firstCustomAttribute = GetType().GetFirstCustomAttribute(); string text = (firstCustomAttribute?.Name ?? GetType().Name).Trim(); targetWrapper = targetWrapper || (firstCustomAttribute != null && firstCustomAttribute.IsCompound) || (firstCustomAttribute?.IsWrapper ?? false); if (!targetWrapper && text.IndexOf("Target", StringComparison.OrdinalIgnoreCase) < 0) { text += "Target"; } targetName = targetName ?? Name; if (string.IsNullOrEmpty(targetName)) { if (!targetWrapper) { return text + "([unnamed])"; } return text; } return text + "(Name=" + targetName + ")"; } public void WriteAsyncLogEvent(AsyncLogEventInfo logEvent) { if (!IsInitialized) { lock (SyncRoot) { logEvent.Continuation(null); return; } } AsyncContinuation asyncContinuation = AsyncHelpers.PreventMultipleCalls(logEvent.Continuation); AsyncLogEventInfo logEvent2 = logEvent.LogEvent.WithContinuation(asyncContinuation); if (_initializeException != null) { lock (SyncRoot) { WriteFailedNotInitialized(logEvent2, _initializeException); return; } } try { WriteAsyncThreadSafe(logEvent2); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "WriteAsyncLogEvent")) { throw; } logEvent2.Continuation(exception); } } public void WriteAsyncLogEvents(params AsyncLogEventInfo[] logEvents) { if (logEvents != null && logEvents.Length != 0) { WriteAsyncLogEvents((IList)logEvents); } } public void WriteAsyncLogEvents(IList logEvents) { if (logEvents == null || logEvents.Count == 0) { return; } if (!IsInitialized) { lock (SyncRoot) { for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(null); } return; } } if (_initializeException != null) { lock (SyncRoot) { for (int j = 0; j < logEvents.Count; j++) { WriteFailedNotInitialized(logEvents[j], _initializeException); } return; } } for (int k = 0; k < logEvents.Count; k++) { logEvents[k] = logEvents[k].LogEvent.WithContinuation(AsyncHelpers.PreventMultipleCalls(logEvents[k].Continuation)); } try { WriteAsyncThreadSafe(logEvents); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "WriteAsyncLogEvents")) { throw; } for (int l = 0; l < logEvents.Count; l++) { logEvents[l].Continuation(exception); } } } protected virtual void WriteFailedNotInitialized(AsyncLogEventInfo logEvent, Exception initializeException) { if (!_scannedForLayouts) { _scannedForLayouts = true; InternalLogger.Error(_initializeException, "{0}: No output because target failed initialize.", new ReadOnlySpan(new object[1] { this })); } else { InternalLogger.Debug("{0}: No output because target failed initialize. {1} {2}", this, _initializeException?.GetType(), _initializeException?.Message); } NLogRuntimeException exception = new NLogRuntimeException($"Target {this} failed to initialize.", initializeException); logEvent.Continuation(exception); } internal void Initialize(LoggingConfiguration? configuration) { lock (SyncRoot) { LoggingConfiguration = configuration; if (IsInitialized) { return; } try { _scannedForLayouts = false; InitializeTarget(); _initializeException = null; if (!_scannedForLayouts) { InternalLogger.Debug("{0}: InitializeTarget is done but not scanned For Layouts", this); FindAllLayouts(); } } catch (NLogDependencyResolveException initializeException) { NLogDependencyResolveException exception = (NLogDependencyResolveException)(_initializeException = initializeException); _scannedForLayouts = false; if (ExceptionMustBeRethrown(exception, "Initialize")) { throw; } } catch (Exception initializeException2) { Exception ex = (_initializeException = initializeException2); _scannedForLayouts = false; if (ExceptionMustBeRethrown(ex, "Initialize")) { throw; } LogFactory logFactory = LoggingConfiguration?.LogFactory ?? LogManager.LogFactory; if (logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions) { throw new NLogConfigurationException($"Error during initialization of target {this}", ex); } } finally { _isInitialized = true; } } } internal void Close() { lock (SyncRoot) { LoggingConfiguration = null; if (!IsInitialized) { return; } _isInitialized = false; try { if (_initializeException == null) { InternalLogger.Debug("{0}: Closing...", this); CloseTarget(); InternalLogger.Debug("{0}: Closed.", this); } } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "Close")) { throw; } } } } protected virtual void Dispose(bool disposing) { if (disposing && _isInitialized) { _isInitialized = false; if (_initializeException == null) { CloseTarget(); } } } protected virtual void InitializeTarget() { FindAllLayouts(); } private void FindAllLayouts() { List list = ObjectGraphScanner.FindReachableObjects(ConfigurationItemFactory.Default, aggressiveSearch: false, new object[1] { this }); InternalLogger.Trace("{0} has {1} layouts", this, list.Count); _allLayoutsAreThreadAgnostic = list.All((Layout layout) => layout.ThreadAgnostic); _anyLayoutsAreThreadAgnosticImmutable = _allLayoutsAreThreadAgnostic && list.Any((Layout layout) => layout.ThreadAgnosticImmutable); StackTraceUsage stackTraceUsage = list.Aggregate(StackTraceUsage.None, (StackTraceUsage agg, Layout layout) => agg | layout.StackTraceUsage); StackTraceUsage = stackTraceUsage | ((this as IUsesStackTrace)?.StackTraceUsage ?? StackTraceUsage.None); _allLayouts = list.Where((Layout l) => !l.ThreadAgnostic || l.ThreadAgnosticImmutable || !(l is SimpleLayout)).Distinct(SingleItemOptimizedHashSet.ReferenceEqualityComparer.Default).ToArray(); _scannedForLayouts = true; } protected virtual void CloseTarget() { } protected virtual void FlushAsync(AsyncContinuation asyncContinuation) { asyncContinuation(null); } protected virtual void Write(LogEventInfo logEvent) { } protected virtual void Write(AsyncLogEventInfo logEvent) { try { Write(logEvent.LogEvent); logEvent.Continuation(null); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "Write")) { throw; } logEvent.Continuation(exception); } } protected virtual void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { lock (SyncRoot) { if (!IsInitialized) { logEvent.Continuation(null); } else { Write(logEvent); } } } protected virtual void Write(IList logEvents) { for (int i = 0; i < logEvents.Count; i++) { Write(logEvents[i]); } } protected virtual void WriteAsyncThreadSafe(IList logEvents) { lock (SyncRoot) { if (!IsInitialized) { for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(null); } } else { Write(logEvents); } } } [Obsolete("Logger.Trace(logEvent) now automatically captures the logEvent Properties. Marked obsolete on NLog 4.6")] [EditorBrowsable(EditorBrowsableState.Never)] protected void MergeEventProperties(LogEventInfo logEvent) { if (logEvent.Parameters == null || logEvent.Parameters.Length == 0) { return; } for (int i = 0; i < logEvent.Parameters.Length; i++) { if (!(logEvent.Parameters[i] is LogEventInfo logEventInfo) || !logEventInfo.HasProperties) { continue; } foreach (object key in logEventInfo.Properties.Keys) { logEvent.Properties.Add(key, logEventInfo.Properties[key]); } logEventInfo.Properties.Clear(); } } protected string RenderLogEvent(Layout? layout, LogEventInfo logEvent) { if (layout == null || logEvent == null) { return string.Empty; } if (layout is IStringValueRenderer stringValueRenderer) { string formattedString = stringValueRenderer.GetFormattedString(logEvent); if (formattedString != null) { return formattedString; } } if (TryGetCachedValue(layout, logEvent, out object value)) { return value?.ToString() ?? string.Empty; } ReusableObjectCreator.LockOject lockOject = ReusableLayoutBuilder.Allocate(); try { return layout.RenderAllocateBuilder(logEvent, lockOject.Result); } finally { ((IDisposable)lockOject).Dispose(); } } protected T? RenderLogEvent(Layout? layout, LogEventInfo logEvent, T? defaultValue = default(T?)) { if (layout == null) { return defaultValue; } if (layout.IsFixed) { return layout.FixedValue; } if (logEvent == null) { return defaultValue; } if (TryGetCachedValue(layout, logEvent, out object value)) { if (value != null) { return (T)value; } return defaultValue; } ReusableObjectCreator.LockOject lockOject = ReusableLayoutBuilder.Allocate(); try { return layout.RenderTypedValue(logEvent, lockOject.Result, defaultValue); } finally { ((IDisposable)lockOject).Dispose(); } } protected T ResolveService() where T : class { return LoggingConfiguration.GetServiceProvider().ResolveService(IsInitialized); } internal bool ExceptionMustBeRethrown(Exception exception, [CallerMemberName] string? callerMemberName = null) { return exception.MustBeRethrown(this, callerMemberName); } private static bool TryGetCachedValue(Layout layout, LogEventInfo logEvent, out object? value) { if (layout.ThreadAgnostic && !layout.ThreadAgnosticImmutable) { value = null; return false; } return logEvent.TryGetCachedLayoutValue(layout, out value); } [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Register<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name) where T : Target { Type typeFromHandle = typeof(T); Register(name, typeFromHandle); } [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Register(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type targetType) { ConfigurationItemFactory.Default.GetTargetFactory().RegisterDefinition(name, targetType); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class TargetAttribute : NameBaseAttribute { public bool IsWrapper { get; set; } public bool IsCompound { get; set; } public TargetAttribute(string name) : base(name) { } } [NLogConfigurationItem] public class TargetPropertyWithContext { private readonly ValueTypeLayoutInfo _layoutInfo = new ValueTypeLayoutInfo(); private bool _includeEmptyValue; public string Name { get; set; } public Layout Layout { get { return _layoutInfo.Layout; } set { _layoutInfo.Layout = value; } } public Type PropertyType { get { return _layoutInfo.ValueType ?? typeof(string); } set { _layoutInfo.ValueType = value; } } public Layout? DefaultValue { get { return _layoutInfo.DefaultValue; } set { _layoutInfo.DefaultValue = value; } } public bool IncludeEmptyValue { get { return _includeEmptyValue; } set { _includeEmptyValue = value; _layoutInfo.ForceDefaultValueNull = !value; } } public TargetPropertyWithContext() : this(string.Empty, NLog.Layouts.Layout.Empty) { } public TargetPropertyWithContext(string name, Layout layout) { Name = name; Layout = layout; } public object? RenderValue(LogEventInfo logEvent) { return _layoutInfo.RenderValue(logEvent); } } public abstract class TargetWithContext : TargetWithLayout, IIncludeContext { [ThreadAgnostic] internal sealed class TargetWithContextLayout : Layout, IIncludeContext, IUsesStackTrace, IStringValueRenderer { public class LayoutScopeContextProperties : Layout { private readonly TargetWithContext _owner; public bool IsActive { get; set; } public LayoutScopeContextProperties(TargetWithContext owner) { _owner = owner; } protected override string GetFormattedMessage(LogEventInfo logEvent) { CaptureContext(logEvent); return string.Empty; } public override void Precalculate(LogEventInfo logEvent) { CaptureContext(logEvent); } private void CaptureContext(LogEventInfo logEvent) { if (IsActive && !logEvent.TryGetCachedLayoutValue(this, out object _)) { IDictionary value2 = _owner.CaptureScopeContextProperties(logEvent, null); logEvent.AddCachedLayoutValue(this, value2); } } } public class LayoutScopeContextNestedStates : Layout { private readonly TargetWithContext _owner; public bool IsActive { get; set; } public LayoutScopeContextNestedStates(TargetWithContext owner) { _owner = owner; } protected override string GetFormattedMessage(LogEventInfo logEvent) { CaptureContext(logEvent); return string.Empty; } public override void Precalculate(LogEventInfo logEvent) { CaptureContext(logEvent); } private void CaptureContext(LogEventInfo logEvent) { if (IsActive && !logEvent.TryGetCachedLayoutValue(this, out object _)) { IList value2 = _owner.CaptureScopeContextNested(logEvent); logEvent.AddCachedLayoutValue(this, value2); } } } private Layout _targetLayout = NLog.Layouts.Layout.Empty; private IStringValueRenderer? _targetStringLayout; private bool? _includeScopeProperties; private bool? _includeScopeNested; private bool? _includeMdc; private bool? _includeMdlc; private bool? _includeNdc; private bool? _includeNdlc; public Layout TargetLayout { get { return _targetLayout; } set { _targetLayout = ((this == value) ? _targetLayout : value); _targetStringLayout = _targetLayout as IStringValueRenderer; } } internal LayoutScopeContextProperties ScopeContextPropertiesLayout { get; } internal LayoutScopeContextNestedStates ScopeContextNestedStatesLayout { get; } public bool IncludeEventProperties { get; set; } public bool IncludeCallSite { get; set; } public bool IncludeCallSiteStackTrace { get; set; } public bool IncludeScopeProperties { get { return _includeScopeProperties ?? ScopeContextPropertiesLayout.IsActive; } set { bool value2 = (ScopeContextPropertiesLayout.IsActive = value); _includeScopeProperties = value2; } } public bool IncludeScopeNested { get { return _includeScopeNested ?? ScopeContextNestedStatesLayout.IsActive; } set { bool value2 = (ScopeContextNestedStatesLayout.IsActive = value); _includeScopeNested = value2; } } [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdc { get { return _includeMdc.GetValueOrDefault(); } set { _includeMdc = value; ScopeContextPropertiesLayout.IsActive = _includeScopeProperties ?? (_includeMdlc.GetValueOrDefault() || value); } } [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdlc { get { return _includeMdlc.GetValueOrDefault(); } set { _includeMdlc = value; ScopeContextPropertiesLayout.IsActive = _includeScopeProperties ?? (_includeMdc.GetValueOrDefault() || value); } } [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] public bool IncludeNdc { get { return _includeNdc.GetValueOrDefault(); } set { _includeNdc = value; ScopeContextNestedStatesLayout.IsActive = _includeScopeNested ?? (_includeNdlc.GetValueOrDefault() || value); } } [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] public bool IncludeNdlc { get { return _includeNdlc.GetValueOrDefault(); } set { _includeNdlc = value; ScopeContextNestedStatesLayout.IsActive = _includeScopeNested ?? (_includeNdc.GetValueOrDefault() || value); } } StackTraceUsage IUsesStackTrace.StackTraceUsage { get { if (IncludeCallSiteStackTrace) { return StackTraceUsage.WithSource; } if (IncludeCallSite) { return StackTraceUsage.WithCallSite | StackTraceUsage.WithCallSiteClassName; } return StackTraceUsage.None; } } public TargetWithContextLayout(TargetWithContext owner, Layout targetLayout) { TargetLayout = targetLayout; ScopeContextPropertiesLayout = new LayoutScopeContextProperties(owner); ScopeContextNestedStatesLayout = new LayoutScopeContextNestedStates(owner); } protected override void InitializeLayout() { base.InitializeLayout(); if (IncludeScopeProperties || IncludeScopeNested) { base.ThreadAgnostic = false; } if (IncludeEventProperties) { base.ThreadAgnosticImmutable = true; } } public override string ToString() { return TargetLayout?.ToString() ?? base.ToString() ?? GetType().ToString(); } public override void Precalculate(LogEventInfo logEvent) { Layout targetLayout = TargetLayout; if (targetLayout == null || targetLayout.ThreadAgnostic) { Layout targetLayout2 = TargetLayout; if (targetLayout2 == null || !targetLayout2.ThreadAgnosticImmutable) { goto IL_004f; } } TargetLayout.Precalculate(logEvent); if (logEvent.TryGetCachedLayoutValue(TargetLayout, out object value)) { logEvent.AddCachedLayoutValue(this, value); } goto IL_004f; IL_004f: PrecalculateContext(logEvent); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { Layout targetLayout = TargetLayout; if (targetLayout == null || targetLayout.ThreadAgnostic) { Layout targetLayout2 = TargetLayout; if (targetLayout2 == null || !targetLayout2.ThreadAgnosticImmutable) { goto IL_0050; } } TargetLayout.PrecalculateBuilder(logEvent, target); if (logEvent.TryGetCachedLayoutValue(TargetLayout, out object value)) { logEvent.AddCachedLayoutValue(this, value); } goto IL_0050; IL_0050: PrecalculateContext(logEvent); } private void PrecalculateContext(LogEventInfo logEvent) { if (IncludeScopeProperties) { ScopeContextPropertiesLayout.Precalculate(logEvent); } if (IncludeScopeNested) { ScopeContextNestedStatesLayout.Precalculate(logEvent); } } protected override string GetFormattedMessage(LogEventInfo logEvent) { return TargetLayout?.Render(logEvent) ?? string.Empty; } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { TargetLayout?.Render(logEvent, target); } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return _targetStringLayout?.GetFormattedString(logEvent); } } private TargetWithContextLayout _contextLayout; public sealed override Layout Layout { get { return _contextLayout; } set { if (_contextLayout == null) { _contextLayout = new TargetWithContextLayout(this, value); } else { _contextLayout.TargetLayout = value; } } } public bool IncludeEventProperties { get { return _contextLayout.IncludeEventProperties; } set { _contextLayout.IncludeEventProperties = value; } } public bool IncludeScopeProperties { get { return _contextLayout.IncludeScopeProperties; } set { _contextLayout.IncludeScopeProperties = value; } } public bool IncludeScopeNested { get { return _contextLayout.IncludeScopeNested; } set { _contextLayout.IncludeScopeNested = value; } } [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdc { get { return _contextLayout.IncludeMdc; } set { _contextLayout.IncludeMdc = value; } } [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeNdc { get { return _contextLayout.IncludeNdc; } set { _contextLayout.IncludeNdc = value; } } [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdlc { get { return _contextLayout.IncludeMdlc; } set { _contextLayout.IncludeMdlc = value; } } [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeNdlc { get { return _contextLayout.IncludeNdlc; } set { _contextLayout.IncludeNdlc = value; } } public bool IncludeGdc { get; set; } public bool IncludeCallSite { get { return _contextLayout.IncludeCallSite; } set { _contextLayout.IncludeCallSite = value; } } public bool IncludeCallSiteStackTrace { get { return _contextLayout.IncludeCallSiteStackTrace; } set { _contextLayout.IncludeCallSiteStackTrace = value; } } [ArrayParameter(typeof(TargetPropertyWithContext), "contextproperty")] public virtual IList ContextProperties { get; } = new List(); public ISet ExcludeProperties { get; set; } protected TargetWithContext() { _contextLayout = _contextLayout ?? new TargetWithContextLayout(this, base.Layout); ExcludeProperties = new HashSet(StringComparer.OrdinalIgnoreCase); } protected override void InitializeTarget() { base.InitializeTarget(); IList contextProperties = ContextProperties; if (contextProperties == null || contextProperties.Count <= 0) { return; } foreach (TargetPropertyWithContext contextProperty in ContextProperties) { if (string.IsNullOrEmpty(contextProperty.Name)) { throw new NLogConfigurationException($"{this}: Contains invalid ContextProperty with unassigned Name-property"); } } } protected bool ShouldIncludeProperties(LogEventInfo logEvent) { if (!IncludeGdc && !IncludeScopeProperties) { if (IncludeEventProperties) { return logEvent?.HasProperties ?? false; } return false; } return true; } protected IDictionary? GetContextProperties(LogEventInfo logEvent) { return GetContextProperties(logEvent, null); } protected IDictionary? GetContextProperties(LogEventInfo logEvent, IDictionary? combinedProperties) { IList contextProperties = ContextProperties; if (contextProperties != null && contextProperties.Count > 0) { combinedProperties = CaptureContextProperties(logEvent, combinedProperties); } if (IncludeScopeProperties && !CombineProperties(logEvent, _contextLayout.ScopeContextPropertiesLayout, ref combinedProperties)) { combinedProperties = CaptureScopeContextProperties(logEvent, combinedProperties); } if (IncludeGdc) { combinedProperties = CaptureContextGdc(logEvent, combinedProperties); } return combinedProperties; } protected IDictionary GetAllProperties(LogEventInfo logEvent) { return GetAllProperties(logEvent, null); } protected IDictionary GetAllProperties(LogEventInfo logEvent, IDictionary? combinedProperties) { if (IncludeEventProperties && logEvent.HasProperties) { combinedProperties = combinedProperties ?? CreateNewDictionary(logEvent.Properties.Count + (ContextProperties?.Count ?? 0)); bool checkForDuplicates = combinedProperties.Count > 0; ISet set = ((ExcludeProperties == null || ExcludeProperties.Count == 0) ? null : ExcludeProperties); using PropertiesDictionary.PropertyDictionaryEnumerator propertyDictionaryEnumerator = logEvent.CreatePropertiesInternal().GetPropertyEnumerator(); while (propertyDictionaryEnumerator.MoveNext()) { KeyValuePair currentProperty = propertyDictionaryEnumerator.CurrentProperty; if (!string.IsNullOrEmpty(currentProperty.Key) && (set == null || !set.Contains(currentProperty.Key))) { AddContextProperty(logEvent, currentProperty.Key, currentProperty.Value, checkForDuplicates, combinedProperties); } } } combinedProperties = GetContextProperties(logEvent, combinedProperties); return combinedProperties ?? CreateNewDictionary(0); } private static Dictionary CreateNewDictionary(int initialCapacity) { return new Dictionary((initialCapacity >= 3) ? initialCapacity : 0, StringComparer.Ordinal); } protected virtual string GenerateUniqueItemName(LogEventInfo logEvent, string itemName, object? itemValue, IDictionary combinedProperties) { return PropertiesDictionary.GenerateUniquePropertyName(itemName, combinedProperties, (string newKey, IDictionary props) => props.ContainsKey(newKey)); } private bool CombineProperties(LogEventInfo logEvent, Layout contextLayout, ref IDictionary? combinedProperties) { if (!logEvent.TryGetCachedLayoutValue(contextLayout, out object value)) { return false; } if (value is IDictionary dictionary) { if (combinedProperties != null) { bool checkForDuplicates = combinedProperties.Count > 0; foreach (KeyValuePair item in dictionary) { AddContextProperty(logEvent, item.Key, item.Value, checkForDuplicates, combinedProperties); } } else { combinedProperties = dictionary; } } return true; } private void AddContextProperty(LogEventInfo logEvent, string propertyName, object? propertyValue, bool checkForDuplicates, IDictionary combinedProperties) { if (checkForDuplicates && combinedProperties.ContainsKey(propertyName)) { propertyName = GenerateUniqueItemName(logEvent, propertyName, propertyValue, combinedProperties); } combinedProperties[propertyName] = propertyValue; } protected IDictionary? GetScopeContextProperties(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.ScopeContextPropertiesLayout, out object value)) { return value as IDictionary; } return CaptureScopeContextProperties(logEvent, null); } protected IList? GetScopeContextNested(LogEventInfo logEvent) { if (logEvent.TryGetCachedLayoutValue(_contextLayout.ScopeContextNestedStatesLayout, out object value)) { return value as IList; } return CaptureScopeContextNested(logEvent); } private IDictionary? CaptureContextProperties(LogEventInfo logEvent, IDictionary? combinedProperties) { combinedProperties = combinedProperties ?? CreateNewDictionary(ContextProperties.Count); for (int i = 0; i < ContextProperties.Count; i++) { TargetPropertyWithContext targetPropertyWithContext = ContextProperties[i]; if (targetPropertyWithContext == null || string.IsNullOrEmpty(targetPropertyWithContext.Name)) { continue; } try { if (TryGetContextPropertyValue(logEvent, targetPropertyWithContext, out object propertyValue)) { combinedProperties[targetPropertyWithContext.Name] = propertyValue; } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Warn(ex, "{0}: Failed to add context property {1}", new ReadOnlySpan(new object[2] { this, targetPropertyWithContext.Name })); } } return combinedProperties; } private static bool TryGetContextPropertyValue(LogEventInfo logEvent, TargetPropertyWithContext contextProperty, out object? propertyValue) { propertyValue = contextProperty.RenderValue(logEvent); if (!contextProperty.IncludeEmptyValue && StringHelpers.IsNullOrEmptyString(propertyValue)) { return false; } return true; } protected virtual IDictionary? CaptureContextGdc(LogEventInfo logEvent, IDictionary? contextProperties) { ICollection names = GlobalDiagnosticsContext.GetNames(); if (names.Count == 0) { return contextProperties; } contextProperties = contextProperties ?? CreateNewDictionary(names.Count); bool checkForDuplicates = contextProperties.Count > 0; ISet set = ((ExcludeProperties == null || ExcludeProperties.Count == 0) ? null : ExcludeProperties); foreach (string item in names) { if (!string.IsNullOrEmpty(item) && (set == null || !set.Contains(item))) { object serializedValue = GlobalDiagnosticsContext.GetObject(item); if (SerializeItemValue(logEvent, item, serializedValue, out serializedValue)) { AddContextProperty(logEvent, item, serializedValue, checkForDuplicates, contextProperties); } } } return contextProperties; } protected virtual IDictionary? CaptureScopeContextProperties(LogEventInfo logEvent, IDictionary? contextProperties) { using ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = ScopeContext.GetAllPropertiesEnumerator(); bool checkForDuplicates = contextProperties != null && contextProperties.Count > 0; ISet set = ((ExcludeProperties == null || ExcludeProperties.Count == 0) ? null : ExcludeProperties); while (scopeContextPropertyEnumerator.MoveNext()) { KeyValuePair current = scopeContextPropertyEnumerator.Current; string key = current.Key; if (!string.IsNullOrEmpty(key) && (set == null || !set.Contains(key))) { contextProperties = contextProperties ?? CreateNewDictionary(0); object value = current.Value; if (SerializeScopeContextProperty(logEvent, key, value, out object serializedValue)) { AddContextProperty(logEvent, key, serializedValue, checkForDuplicates, contextProperties); } } } return contextProperties; } protected virtual bool SerializeScopeContextProperty(LogEventInfo logEvent, string name, object? value, out object? serializedValue) { if (string.IsNullOrEmpty(name)) { serializedValue = null; return false; } return SerializeItemValue(logEvent, name, value, out serializedValue); } protected virtual IList CaptureScopeContextNested(LogEventInfo logEvent) { IList allNestedStateList = ScopeContext.GetAllNestedStateList(); if (allNestedStateList.Count == 0) { return allNestedStateList; } List list = null; for (int i = 0; i < allNestedStateList.Count; i++) { object value = allNestedStateList[i]; if (SerializeScopeContextNestedState(logEvent, value, out object serializedValue) && serializedValue != null) { if (list != null) { list.Add(serializedValue); } else { allNestedStateList[i] = serializedValue; } } else if (list == null) { list = new List(allNestedStateList.Count); for (int j = 0; j < i; j++) { list.Add(allNestedStateList[j]); } } } IList list2 = list; return list2 ?? allNestedStateList; } protected virtual bool SerializeScopeContextNestedState(LogEventInfo logEvent, object value, out object? serializedValue) { return SerializeItemValue(logEvent, string.Empty, value, out serializedValue); } protected virtual bool SerializeItemValue(LogEventInfo logEvent, string name, object? value, out object? serializedValue) { if (value == null) { serializedValue = null; return true; } if (value is string || Convert.GetTypeCode(value) != TypeCode.Object || value.GetType().IsValueType) { serializedValue = value; return true; } serializedValue = Convert.ToString(value, CultureInfo.InvariantCulture); return true; } [Obsolete("Replaced by GetScopeContextNested. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected IList? GetContextNdlc(LogEventInfo logEvent) { return GetScopeContextNested(logEvent); } [Obsolete("Replaced by GetScopeContextProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] protected IDictionary? GetContextMdlc(LogEventInfo logEvent) { return GetScopeContextProperties(logEvent); } } public abstract class TargetWithLayout : Target { private const string DefaultLayoutText = "${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}"; private static LayoutRenderer[] DefaultLayout => new LayoutRenderer[7] { new LongDateLayoutRenderer(), new LiteralLayoutRenderer("|"), new LevelLayoutRenderer { Uppercase = true }, new LiteralLayoutRenderer("|"), new LoggerNameLayoutRenderer(), new LiteralLayoutRenderer("|"), new MessageLayoutRenderer { WithException = true } }; public virtual Layout Layout { get; set; } protected TargetWithLayout() { Layout = new SimpleLayout(DefaultLayout, "${longdate}|${level:uppercase=true}|${logger}|${message:withexception=true}"); } } public abstract class TargetWithLayoutHeaderAndFooter : TargetWithLayout { private Layout _layout; public override Layout Layout { get { return _layout; } set { if (value is LayoutWithHeaderAndFooter layoutWithHeaderAndFooter) { base.Layout = value; _layout = layoutWithHeaderAndFooter.Layout; } else if (base.Layout is LayoutWithHeaderAndFooter layoutWithHeaderAndFooter2) { layoutWithHeaderAndFooter2.Layout = value; _layout = value; } else { base.Layout = new LayoutWithHeaderAndFooter { Layout = value }; _layout = value; } } } public Layout? Footer { get { return (base.Layout as LayoutWithHeaderAndFooter)?.Footer; } set { if (base.Layout is LayoutWithHeaderAndFooter layoutWithHeaderAndFooter) { layoutWithHeaderAndFooter.Footer = value; } else if (value != null) { base.Layout = new LayoutWithHeaderAndFooter { Layout = base.Layout, Footer = value }; } } } public Layout? Header { get { return (base.Layout as LayoutWithHeaderAndFooter)?.Header; } set { if (base.Layout is LayoutWithHeaderAndFooter layoutWithHeaderAndFooter) { layoutWithHeaderAndFooter.Header = value; } else if (value != null) { base.Layout = new LayoutWithHeaderAndFooter { Layout = base.Layout, Header = value }; } } } protected TargetWithLayoutHeaderAndFooter() { Layout layout = base.Layout; _layout = ((layout is LayoutWithHeaderAndFooter layoutWithHeaderAndFooter) ? layoutWithHeaderAndFooter.Layout : layout); } } } namespace NLog.Targets.Wrappers { internal sealed class AsyncRequestQueue : AsyncRequestQueueBase { private readonly Queue _logEventInfoQueue = new Queue(1000); public int RequestCount { get { lock (_logEventInfoQueue) { return _logEventInfoQueue.Count; } } } public override bool IsEmpty => RequestCount == 0; public AsyncRequestQueue(int queueLimit, AsyncTargetWrapperOverflowAction overflowAction) { base.QueueLimit = queueLimit; base.OnOverflow = overflowAction; } public override bool Enqueue(AsyncLogEventInfo logEventInfo) { lock (_logEventInfoQueue) { int count = _logEventInfoQueue.Count; if (count >= base.QueueLimit) { switch (base.OnOverflow) { case AsyncTargetWrapperOverflowAction.Discard: InternalLogger.Debug("AsyncQueue - Discarding single item, because queue is full"); OnLogEventDropped(_logEventInfoQueue.Dequeue().LogEvent); break; case AsyncTargetWrapperOverflowAction.Grow: InternalLogger.Debug("AsyncQueue - Growing the size of queue, because queue is full"); base.QueueLimit *= 2; OnLogEventQueueGrows(count + 1); break; case AsyncTargetWrapperOverflowAction.Block: while (count >= base.QueueLimit) { InternalLogger.Debug("AsyncQueue - Blocking until ready, because queue is full"); Monitor.Wait(_logEventInfoQueue); InternalLogger.Trace("AsyncQueue - Entered critical section."); count = _logEventInfoQueue.Count; } InternalLogger.Trace("AsyncQueue - Limit ok."); break; } } _logEventInfoQueue.Enqueue(logEventInfo); return count == 0; } } public override AsyncLogEventInfo[] DequeueBatch(int count) { AsyncLogEventInfo[] array; lock (_logEventInfoQueue) { if (_logEventInfoQueue.Count < count) { count = _logEventInfoQueue.Count; } if (count == 0) { return ArrayHelper.Empty(); } array = new AsyncLogEventInfo[count]; for (int i = 0; i < count; i++) { array[i] = _logEventInfoQueue.Dequeue(); } if (base.OnOverflow == AsyncTargetWrapperOverflowAction.Block) { Monitor.PulseAll(_logEventInfoQueue); } } return array; } public override void DequeueBatch(int count, IList result) { lock (_logEventInfoQueue) { if (_logEventInfoQueue.Count < count) { count = _logEventInfoQueue.Count; } for (int i = 0; i < count; i++) { result.Add(_logEventInfoQueue.Dequeue()); } if (base.OnOverflow == AsyncTargetWrapperOverflowAction.Block) { Monitor.PulseAll(_logEventInfoQueue); } } } public override void Clear() { lock (_logEventInfoQueue) { _logEventInfoQueue.Clear(); if (base.OnOverflow == AsyncTargetWrapperOverflowAction.Block) { Monitor.PulseAll(_logEventInfoQueue); } } } } internal abstract class AsyncRequestQueueBase { public abstract bool IsEmpty { get; } public int QueueLimit { get; set; } public AsyncTargetWrapperOverflowAction OnOverflow { get; set; } public event EventHandler? LogEventDropped; public event EventHandler? LogEventQueueGrow; public abstract bool Enqueue(AsyncLogEventInfo logEventInfo); public abstract AsyncLogEventInfo[] DequeueBatch(int count); public abstract void DequeueBatch(int count, IList result); public abstract void Clear(); protected void OnLogEventDropped(LogEventInfo logEventInfo) { this.LogEventDropped?.Invoke(this, new LogEventDroppedEventArgs(logEventInfo)); } protected void OnLogEventQueueGrows(long requestsCount) { this.LogEventQueueGrow?.Invoke(this, new LogEventQueueGrowEventArgs(QueueLimit, requestsCount)); } } [Target("AsyncWrapper", IsWrapper = true)] public class AsyncTargetWrapper : WrapperTargetBase { private readonly object _writeLockObject = new object(); private readonly object _timerLockObject = new object(); private Timer? _lazyWriterTimer; private readonly ReusableAsyncLogEventList _reusableAsyncLogEventList = new ReusableAsyncLogEventList(200); private readonly WaitCallback _flushEventsInQueueDelegate; private bool _missingServiceTypes; private bool? _forceLockingQueue; private AsyncRequestQueueBase _requestQueue; public int BatchSize { get; set; } = 200; public int TimeToSleepBetweenBatches { get; set; } = 1; public AsyncTargetWrapperOverflowAction OverflowAction { get { return _requestQueue.OnOverflow; } set { _requestQueue.OnOverflow = value; } } public int QueueLimit { get { return _requestQueue.QueueLimit; } set { _requestQueue.QueueLimit = value; } } public int FullBatchSizeWriteLimit { get; set; } = 10; public bool ForceLockingQueue { get { return _forceLockingQueue.GetValueOrDefault(); } set { _forceLockingQueue = value; } } private event EventHandler? _logEventDroppedEvent; private event EventHandler? _eventQueueGrowEvent; public event EventHandler LogEventDropped { add { if (this._logEventDroppedEvent == null) { _requestQueue.LogEventDropped += OnRequestQueueDropItem; } _logEventDroppedEvent += value; } remove { _logEventDroppedEvent -= value; if (this._logEventDroppedEvent == null) { _requestQueue.LogEventDropped -= OnRequestQueueDropItem; } } } public event EventHandler EventQueueGrow { add { if (this._eventQueueGrowEvent == null) { _requestQueue.LogEventQueueGrow += OnRequestQueueGrow; } _eventQueueGrowEvent += value; } remove { _eventQueueGrowEvent -= value; if (this._eventQueueGrowEvent == null) { _requestQueue.LogEventQueueGrow -= OnRequestQueueGrow; } } } public AsyncTargetWrapper() { _requestQueue = new ConcurrentRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard); _flushEventsInQueueDelegate = FlushEventsInQueue; } public AsyncTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { base.Name = name ?? base.Name; } public AsyncTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard) { } public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction) : this() { base.Name = ((wrappedTarget == null || string.IsNullOrEmpty(wrappedTarget.Name)) ? base.Name : (wrappedTarget.Name + "_wrapper")); base.WrappedTarget = wrappedTarget; QueueLimit = queueLimit; OverflowAction = overflowAction; } protected override void FlushAsync(AsyncContinuation asyncContinuation) { AsyncHelpers.StartAsyncTask(_flushEventsInQueueDelegate, asyncContinuation); } protected override void InitializeTarget() { base.InitializeTarget(); if (!ForceLockingQueue && OverflowAction == AsyncTargetWrapperOverflowAction.Block && (decimal)BatchSize * 1.5m > (decimal)QueueLimit) { ForceLockingQueue = true; } if (_forceLockingQueue.HasValue && _forceLockingQueue.Value != _requestQueue is AsyncRequestQueue) { _requestQueue = (ForceLockingQueue ? ((AsyncRequestQueueBase)new AsyncRequestQueue(QueueLimit, OverflowAction)) : ((AsyncRequestQueueBase)new ConcurrentRequestQueue(QueueLimit, OverflowAction))); } if (BatchSize > QueueLimit && TimeToSleepBetweenBatches <= 1) { BatchSize = QueueLimit; } _layoutWithLock = _layoutWithLock ?? base.WrappedTarget?._layoutWithLock; if (base.WrappedTarget != null && base.WrappedTarget.InitializeException is NLogDependencyResolveException && OverflowAction == AsyncTargetWrapperOverflowAction.Discard) { _missingServiceTypes = true; InternalLogger.Debug("{0} WrappedTarget has unresolved missing dependencies.", this); } _requestQueue.Clear(); InternalLogger.Trace("{0}: Start Timer", this); _lazyWriterTimer = new Timer(ProcessPendingEvents, null, -1, -1); StartLazyWriterTimer(); } protected override void CloseTarget() { StopLazyWriterThread(); int millisecondsTimeout = ((OverflowAction == AsyncTargetWrapperOverflowAction.Discard) ? 500 : 1500); if (Monitor.TryEnter(_writeLockObject, millisecondsTimeout)) { try { WriteLogEventsInQueue(int.MaxValue, "Closing Target"); } finally { Monitor.Exit(_writeLockObject); } } else { InternalLogger.Debug("{0}: Failed to flush after lock timeout", this); } if (OverflowAction == AsyncTargetWrapperOverflowAction.Block) { _requestQueue.Clear(); } base.CloseTarget(); } protected virtual void StartLazyWriterTimer() { if (TimeToSleepBetweenBatches <= 1) { StartTimerUnlessWriterActive(instant: false); return; } lock (_timerLockObject) { _lazyWriterTimer?.Change(TimeToSleepBetweenBatches, -1); } } protected virtual bool StartInstantWriterTimer() { return StartLazyWriterThread(instant: true); } private void StartTimerUnlessWriterActive(bool instant) { bool flag = false; try { flag = Monitor.TryEnter(_writeLockObject); if (flag) { if (instant) { StartInstantWriterTimer(); } else { StartLazyWriterThread(instant: false); } } else { InternalLogger.Trace("{0}: Timer not scheduled, since already active", this); } } finally { if (flag) { Monitor.Exit(_writeLockObject); } } } private bool StartLazyWriterThread(bool instant) { lock (_timerLockObject) { if (_lazyWriterTimer != null) { if (instant) { InternalLogger.Trace("{0}: Timer scheduled instantly", this); _lazyWriterTimer.Change(0, -1); } else { InternalLogger.Trace("{0}: Timer scheduled throttled", this); _lazyWriterTimer.Change(1, -1); } return true; } } return false; } protected virtual void StopLazyWriterThread() { lock (_timerLockObject) { Timer lazyWriterTimer = _lazyWriterTimer; if (lazyWriterTimer != null) { _lazyWriterTimer = null; lazyWriterTimer.WaitForDispose(TimeSpan.FromSeconds(1.0)); } } } protected override void Write(AsyncLogEventInfo logEvent) { PrecalculateVolatileLayouts(logEvent.LogEvent); if (_requestQueue.Enqueue(logEvent)) { if (TimeToSleepBetweenBatches == 0) { StartTimerUnlessWriterActive(instant: true); } else if (TimeToSleepBetweenBatches <= 1) { StartLazyWriterTimer(); } } } protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { try { Write(logEvent); } catch (Exception exception) { if (ExceptionMustBeRethrown(exception, "WriteAsyncThreadSafe")) { throw; } logEvent.Continuation(exception); } } private void ProcessPendingEvents(object? state) { if (_lazyWriterTimer == null) { return; } bool flag = false; try { lock (_writeLockObject) { flag = WriteLogEventsInQueue(BatchSize, "Timer") == BatchSize; if (flag && TimeToSleepBetweenBatches <= 1) { StartInstantWriterTimer(); } } } catch (Exception ex) { flag = false; InternalLogger.Error(ex, "{0}: Error in lazy writer timer procedure.", new ReadOnlySpan(new object[1] { this })); } finally { if (TimeToSleepBetweenBatches <= 1) { if (!flag) { if (!_requestQueue.IsEmpty) { StartLazyWriterTimer(); } else { InternalLogger.Trace("{0}: Timer not scheduled, since queue empty", this); } } } else { StartLazyWriterTimer(); } } } private void FlushEventsInQueue(object? state) { AsyncContinuation asyncContinuation = state as AsyncContinuation; if (Monitor.TryEnter(_writeLockObject, 1500)) { try { WriteLogEventsInQueue(int.MaxValue, "Flush Async"); if (asyncContinuation != null) { base.FlushAsync(asyncContinuation); } return; } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Error in flush procedure.", new ReadOnlySpan(new object[1] { this })); return; } finally { Monitor.Exit(_writeLockObject); if (TimeToSleepBetweenBatches <= 1 && !_requestQueue.IsEmpty) { StartLazyWriterTimer(); } } } asyncContinuation?.Invoke(new NLogRuntimeException($"Target {this} failed to flush after lock timeout.")); } private int WriteLogEventsInQueue(int batchSize, string reason) { if (base.WrappedTarget == null) { InternalLogger.Debug("{0}: No output because WrappedTarget is NULL", this); return 0; } if (_missingServiceTypes) { if (base.WrappedTarget.InitializeException is NLogDependencyResolveException) { return 0; } _missingServiceTypes = false; InternalLogger.Debug("{0}: WrappedTarget has resolved missing dependency", this); } if (batchSize == int.MaxValue) { AsyncLogEventInfo[] logEvents = _requestQueue.DequeueBatch(int.MaxValue); return WriteLogEventsToTarget(logEvents, reason); } int num = 0; for (int i = 0; i < FullBatchSizeWriteLimit; i++) { ReusableObjectCreator>.LockOject lockOject = _reusableAsyncLogEventList.Allocate(); try { IList result = lockOject.Result; _requestQueue.DequeueBatch(batchSize, result); num = WriteLogEventsToTarget(result, reason); } finally { ((IDisposable)lockOject).Dispose(); } if (num < batchSize) { break; } } return num; } private int WriteLogEventsToTarget(IList logEvents, string reason) { int count = logEvents.Count; if (count > 0) { if (reason != null) { InternalLogger.Trace("{0}: Writing {1} events ({2})", this, count, reason); } base.WrappedTarget?.WriteAsyncLogEvents(logEvents); } return count; } private void OnRequestQueueDropItem(object? sender, LogEventDroppedEventArgs logEventDroppedEventArgs) { this._logEventDroppedEvent?.Invoke(this, logEventDroppedEventArgs); } private void OnRequestQueueGrow(object? sender, LogEventQueueGrowEventArgs logEventQueueGrowEventArgs) { this._eventQueueGrowEvent?.Invoke(this, logEventQueueGrowEventArgs); } } public enum AsyncTargetWrapperOverflowAction { Grow, Discard, Block } [Target("AutoFlushWrapper", IsWrapper = true)] public class AutoFlushTargetWrapper : WrapperTargetBase { private bool? _asyncFlush; private readonly AsyncOperationCounter _pendingManualFlushList = new AsyncOperationCounter(); private readonly AsyncContinuation _flushCompletedContinuation; public ConditionExpression? Condition { get; set; } public bool AsyncFlush { get { return _asyncFlush.GetValueOrDefault(true); } set { _asyncFlush = value; } } public bool FlushOnConditionOnly { get; set; } public AutoFlushTargetWrapper() { _flushCompletedContinuation = delegate(Exception? ex) { _pendingManualFlushList.CompleteOperation(ex); }; } public AutoFlushTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { base.Name = name ?? base.Name; } public AutoFlushTargetWrapper(Target wrappedTarget) : this() { base.Name = ((wrappedTarget == null || string.IsNullOrEmpty(wrappedTarget.Name)) ? base.Name : (wrappedTarget.Name + "_wrapper")); base.WrappedTarget = wrappedTarget; } protected override void InitializeTarget() { base.InitializeTarget(); if (!_asyncFlush.HasValue && !TargetSupportsAsyncFlush()) { AsyncFlush = false; } } private bool TargetSupportsAsyncFlush() { if (base.WrappedTarget is BufferingTargetWrapper) { return false; } if (base.WrappedTarget is AsyncTaskTarget) { return false; } return true; } protected override void Write(AsyncLogEventInfo logEvent) { if (Condition == null || ConditionExpression.BoxedTrue.Equals(Condition.Evaluate(logEvent.LogEvent))) { if (AsyncFlush) { AsyncContinuation currentContinuation = logEvent.Continuation; AsyncContinuation asyncContinuation = delegate(Exception? ex) { _pendingManualFlushList.CompleteOperation(ex); if (ex == null) { AsyncContinuation asyncContinuation2 = _pendingManualFlushList.RegisterCompletionNotification(delegate { }); FlushWrappedTarget(asyncContinuation2); } currentContinuation(ex); }; _pendingManualFlushList.BeginOperation(); base.WrappedTarget?.WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(asyncContinuation)); } else { _pendingManualFlushList.BeginOperation(); base.WrappedTarget?.WriteAsyncLogEvent(logEvent); FlushWrappedTarget(_flushCompletedContinuation); } } else { base.WrappedTarget?.WriteAsyncLogEvent(logEvent); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { AsyncContinuation asyncContinuation2 = _pendingManualFlushList.RegisterCompletionNotification(asyncContinuation); if (FlushOnConditionOnly) { asyncContinuation2(null); } else { FlushWrappedTarget(asyncContinuation2); } } private void FlushWrappedTarget(AsyncContinuation asyncContinuation) { base.WrappedTarget?.Flush(asyncContinuation); } protected override void CloseTarget() { _pendingManualFlushList.Clear(); base.CloseTarget(); } } [Target("BufferingWrapper", IsWrapper = true)] public class BufferingTargetWrapper : WrapperTargetBase { private AsyncRequestQueue _buffer = new AsyncRequestQueue(100, AsyncTargetWrapperOverflowAction.Discard); private Timer? _flushTimer; private readonly object _lockObject = new object(); public Layout BufferSize { get; set; } public Layout FlushTimeout { get; set; } public bool SlidingTimeout { get; set; } = true; public BufferingTargetWrapperOverflowAction OverflowAction { get; set; } public BufferingTargetWrapper() { BufferSize = 100; FlushTimeout = -1; } public BufferingTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { base.Name = name ?? base.Name; } public BufferingTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 100) { } public BufferingTargetWrapper(Target wrappedTarget, int bufferSize) : this(wrappedTarget, bufferSize, -1) { } public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout) : this(wrappedTarget, bufferSize, flushTimeout, BufferingTargetWrapperOverflowAction.Flush) { } public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout, BufferingTargetWrapperOverflowAction overflowAction) { base.Name = ((wrappedTarget == null || string.IsNullOrEmpty(wrappedTarget.Name)) ? base.Name : (wrappedTarget.Name + "_wrapper")); base.WrappedTarget = wrappedTarget; BufferSize = bufferSize; FlushTimeout = flushTimeout; OverflowAction = overflowAction; } protected override void FlushAsync(AsyncContinuation asyncContinuation) { if (Monitor.TryEnter(_lockObject, 1500)) { try { WriteEventsInBuffer("Flush Async"); base.FlushAsync(asyncContinuation); return; } finally { Monitor.Exit(_lockObject); } } asyncContinuation(new NLogRuntimeException($"Target {this} failed to flush after lock timeout.")); } protected override void InitializeTarget() { base.InitializeTarget(); int queueLimit = RenderLogEvent(BufferSize, LogEventInfo.CreateNullEvent(), 0); _buffer = new AsyncRequestQueue(queueLimit, AsyncTargetWrapperOverflowAction.Discard); InternalLogger.Trace("{0}: Create Timer", this); int num = RenderLogEvent(FlushTimeout, LogEventInfo.CreateNullEvent(), 0); _flushTimer = new Timer(FlushCallback, num, -1, -1); } protected override void CloseTarget() { Timer flushTimer = _flushTimer; if (flushTimer != null) { _flushTimer = null; if (flushTimer.WaitForDispose(TimeSpan.FromSeconds(1.0))) { if (OverflowAction == BufferingTargetWrapperOverflowAction.Discard) { _buffer.Clear(); } else { int millisecondsTimeout = ((OverflowAction == BufferingTargetWrapperOverflowAction.Discard) ? 500 : 1500); if (Monitor.TryEnter(_lockObject, millisecondsTimeout)) { try { WriteEventsInBuffer("Closing Target"); } finally { Monitor.Exit(_lockObject); } } else { InternalLogger.Debug("{0}: Failed to flush after lock timeout", this); } } } } base.CloseTarget(); } protected override void Write(AsyncLogEventInfo logEvent) { PrecalculateVolatileLayouts(logEvent.LogEvent); bool flag = _buffer.Enqueue(logEvent); if (_buffer.RequestCount >= _buffer.QueueLimit) { if (OverflowAction == BufferingTargetWrapperOverflowAction.Flush) { lock (_lockObject) { WriteEventsInBuffer("Exceeding BufferSize"); } } } else if (SlidingTimeout || flag) { int num = RenderLogEvent(FlushTimeout, logEvent.LogEvent, 0); if (num > 0) { _flushTimer?.Change(num, -1); } } } private void FlushCallback(object? state) { bool flag = false; try { int num = Math.Min((state as int?).GetValueOrDefault() / 2, 100); flag = Monitor.TryEnter(_lockObject, num); if (flag) { if (_flushTimer != null) { WriteEventsInBuffer(string.Empty); } } else if (!_buffer.IsEmpty) { _flushTimer?.Change(num, -1); } } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Error in flush procedure.", new ReadOnlySpan(new object[1] { this })); } finally { if (flag) { Monitor.Exit(_lockObject); } } } private void WriteEventsInBuffer(string reason) { if (base.WrappedTarget == null) { InternalLogger.Debug("{0}: No output because WrappedTarget is NULL", this); return; } AsyncLogEventInfo[] array = _buffer.DequeueBatch(int.MaxValue); if (array.Length != 0) { if (!string.IsNullOrEmpty(reason)) { InternalLogger.Trace("{0}: Writing {1} events ({2})", this, array.Length, reason); } base.WrappedTarget.WriteAsyncLogEvents(array); } } } public enum BufferingTargetWrapperOverflowAction { Flush, Discard } public abstract class CompoundTargetBase : Target { public IList Targets { get; } protected CompoundTargetBase(params Target[] targets) { Targets = new List(targets); } public override string ToString() { return _tostring ?? (_tostring = GenerateTargetToString()); } private string GenerateTargetToString() { if (string.IsNullOrEmpty(base.Name)) { IList targets = Targets; if (targets != null && targets.Count > 0) { string value = string.Empty; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(GenerateTargetToString(targetWrapper: true)); stringBuilder.Append('['); foreach (Target target in Targets) { stringBuilder.Append(value); stringBuilder.Append(target.ToString()); value = ", "; } stringBuilder.Append(']'); return stringBuilder.ToString(); } } return GenerateTargetToString(targetWrapper: true); } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException("This target must not be invoked in a synchronous way."); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { AsyncHelpers.ForEachItemInParallel(Targets, asyncContinuation, delegate(Target t, AsyncContinuation c) { t.Flush(c); }); } } internal sealed class ConcurrentRequestQueue : AsyncRequestQueueBase { private readonly ConcurrentQueue _logEventInfoQueue = new ConcurrentQueue(); private long _count; public override bool IsEmpty { get { if (_logEventInfoQueue.IsEmpty) { return Interlocked.Read(ref _count) == 0; } return false; } } public int Count => (int)_count; public ConcurrentRequestQueue(int queueLimit, AsyncTargetWrapperOverflowAction overflowAction) { base.QueueLimit = queueLimit; base.OnOverflow = overflowAction; } public override bool Enqueue(AsyncLogEventInfo logEventInfo) { long num = Interlocked.Increment(ref _count); bool result = num == 1; if (num > base.QueueLimit) { switch (base.OnOverflow) { case AsyncTargetWrapperOverflowAction.Discard: result = DequeueUntilBelowRequestLimit(); break; case AsyncTargetWrapperOverflowAction.Block: result = WaitForBelowRequestLimit(); break; case AsyncTargetWrapperOverflowAction.Grow: { InternalLogger.Debug("AsyncQueue - Growing the size of queue, because queue is full"); int queueLimit = base.QueueLimit; if (num > queueLimit) { base.QueueLimit = queueLimit * 2; } OnLogEventQueueGrows(num); break; } } } _logEventInfoQueue.Enqueue(logEventInfo); return result; } private bool DequeueUntilBelowRequestLimit() { bool flag = false; long num; do { if (_logEventInfoQueue.TryDequeue(out var result)) { InternalLogger.Debug("AsyncQueue - Discarding single item, because queue is full"); flag = Interlocked.Decrement(ref _count) == 1 || flag; OnLogEventDropped(result.LogEvent); break; } num = Interlocked.Read(ref _count); flag = true; } while (num > base.QueueLimit); return flag; } private bool WaitForBelowRequestLimit() { long num = TrySpinWaitForLowerCount(); if (num > base.QueueLimit) { InternalLogger.Debug("AsyncQueue - Blocking until ready, because queue is full"); lock (_logEventInfoQueue) { InternalLogger.Trace("AsyncQueue - Entered critical section."); for (num = Interlocked.Read(ref _count); num > base.QueueLimit; num = Interlocked.Increment(ref _count)) { Interlocked.Decrement(ref _count); Monitor.Wait(_logEventInfoQueue); InternalLogger.Trace("AsyncQueue - Entered critical section."); } } } InternalLogger.Trace("AsyncQueue - Limit ok."); return true; } private long TrySpinWaitForLowerCount() { long num = 0L; bool flag = true; SpinWait spinWait = default(SpinWait); for (int i = 0; i < 15; i++) { if (spinWait.NextSpinWillYield) { if (flag) { InternalLogger.Debug("AsyncQueue - Blocking with yield, because queue is full"); } flag = false; } spinWait.SpinOnce(); num = Interlocked.Read(ref _count); if (num <= base.QueueLimit) { break; } } return num; } public override AsyncLogEventInfo[] DequeueBatch(int count) { if (_logEventInfoQueue.IsEmpty) { return ArrayHelper.Empty(); } if (_count < count) { count = Math.Min(count, Count); } List list = new List(count); DequeueBatch(count, list); if (list.Count == 0) { return ArrayHelper.Empty(); } return list.ToArray(); } public override void DequeueBatch(int count, IList result) { bool flag = base.OnOverflow == AsyncTargetWrapperOverflowAction.Block; for (int i = 0; i < count; i++) { if (_logEventInfoQueue.TryDequeue(out var result2)) { if (!flag) { Interlocked.Decrement(ref _count); } result.Add(result2); continue; } count = i; break; } if (flag) { lock (_logEventInfoQueue) { Interlocked.Add(ref _count, -count); Monitor.PulseAll(_logEventInfoQueue); } } } public override void Clear() { while (!_logEventInfoQueue.IsEmpty) { _logEventInfoQueue.TryDequeue(out var _); } Interlocked.Exchange(ref _count, 0L); if (base.OnOverflow == AsyncTargetWrapperOverflowAction.Block) { lock (_logEventInfoQueue) { Monitor.PulseAll(_logEventInfoQueue); } } } } [Target("FallbackGroup", IsCompound = true)] public class FallbackGroupTarget : CompoundTargetBase { private long _currentTarget; public bool ReturnToFirstOnSuccess { get; set; } public bool EnableBatchWrite { get; set; } = true; public FallbackGroupTarget() : this(ArrayHelper.Empty()) { } public FallbackGroupTarget(string name, params Target[] targets) : this(targets) { base.Name = name; } public FallbackGroupTarget(params Target[] targets) : base(targets) { } protected override void WriteAsyncThreadSafe(IList logEvents) { if (logEvents.Count == 1) { WriteAsyncThreadSafe(logEvents[0]); } else if (EnableBatchWrite) { int num = (int)Interlocked.Read(ref _currentTarget); for (int i = 0; i < logEvents.Count; i++) { logEvents[i] = WrapWithFallback(logEvents[i], num); } base.Targets[num].WriteAsyncLogEvents(logEvents); } else { for (int j = 0; j < logEvents.Count; j++) { WriteAsyncThreadSafe(logEvents[j]); } } } protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { Write(logEvent); } protected override void Write(AsyncLogEventInfo logEvent) { int num = (int)Interlocked.Read(ref _currentTarget); AsyncLogEventInfo logEvent2 = WrapWithFallback(logEvent, num); base.Targets[num].WriteAsyncLogEvent(logEvent2); } private AsyncLogEventInfo WrapWithFallback(AsyncLogEventInfo logEvent, int targetToInvoke) { for (int i = 0; i < base.Targets.Count; i++) { if (i != targetToInvoke) { base.Targets[i].PrecalculateVolatileLayouts(logEvent.LogEvent); } } AsyncContinuation continuation = null; int tryCounter = 0; continuation = delegate(Exception? ex) { if (ex == null) { if (ReturnToFirstOnSuccess && Interlocked.Read(ref _currentTarget) != 0L) { InternalLogger.Debug("{0}: Target '{1}' succeeded. Returning to the first one.", this, base.Targets[targetToInvoke]); Interlocked.Exchange(ref _currentTarget, 0L); } logEvent.Continuation(null); } else { tryCounter++; int num = (targetToInvoke + 1) % base.Targets.Count; Interlocked.CompareExchange(ref _currentTarget, num, targetToInvoke); if (tryCounter < base.Targets.Count) { InternalLogger.Warn(ex, "{0}: Target '{1}' failed. Fallback to next: `{2}`", new ReadOnlySpan(new object[3] { this, base.Targets[targetToInvoke], base.Targets[num] })); targetToInvoke = num; base.Targets[targetToInvoke].WriteAsyncLogEvent((continuation == null) ? logEvent : logEvent.LogEvent.WithContinuation(continuation)); } else { InternalLogger.Warn(ex, "{0}: Target '{1}' failed. Fallback not possible", new ReadOnlySpan(new object[2] { this, base.Targets[targetToInvoke] })); logEvent.Continuation(ex); } } }; return logEvent.LogEvent.WithContinuation(continuation); } } [NLogConfigurationItem] public class FilteringRule { public ConditionExpression? Exists { get; set; } public ConditionExpression? Filter { get; set; } public FilteringRule() { } public FilteringRule(ConditionExpression whenExistsExpression, ConditionExpression filterToApply) { Exists = whenExistsExpression; Filter = filterToApply; } } [Target("FilteringWrapper", IsWrapper = true)] public class FilteringTargetWrapper : WrapperTargetBase { public ConditionExpression? Condition { get { return (Filter as ConditionBasedFilter)?.Condition; } set { Filter = CreateFilter(value); } } public Filter Filter { get; set; } public FilteringTargetWrapper() { Filter = ConditionBasedFilter.Empty; } public FilteringTargetWrapper(string name, Target wrappedTarget, ConditionExpression condition) : this(wrappedTarget, condition) { base.Name = name ?? base.Name; } public FilteringTargetWrapper(Target wrappedTarget, ConditionExpression condition) { base.Name = ((wrappedTarget == null || string.IsNullOrEmpty(wrappedTarget.Name)) ? base.Name : (wrappedTarget.Name + "_wrapper")); base.WrappedTarget = wrappedTarget; Filter = CreateFilter(condition); } protected override void InitializeTarget() { if (Filter == null || Filter == ConditionBasedFilter.Empty) { throw new NLogConfigurationException("FilteringTargetWrapper Filter-property must be assigned. Filter LogEvents using blank Filter not supported."); } base.InitializeTarget(); } protected override void Write(AsyncLogEventInfo logEvent) { if (ShouldLogEvent(logEvent, Filter)) { base.WrappedTarget?.WriteAsyncLogEvent(logEvent); } } protected override void Write(IList logEvents) { IList list = logEvents.Filter(Filter, (AsyncLogEventInfo logEvent, Filter filter) => ShouldLogEvent(logEvent, filter)); if (list.Count > 0) { base.WrappedTarget?.WriteAsyncLogEvents(list); } } private static bool ShouldLogEvent(AsyncLogEventInfo logEvent, Filter filter) { FilterResult filterResult = filter.GetFilterResult(logEvent.LogEvent); if (filterResult != FilterResult.Ignore && filterResult != FilterResult.IgnoreFinal) { return true; } logEvent.Continuation(null); return false; } private static ConditionBasedFilter CreateFilter(ConditionExpression? value) { if (value == null) { return ConditionBasedFilter.Empty; } return new ConditionBasedFilter { Condition = value, FilterDefaultAction = FilterResult.Ignore }; } } [Target("GroupByWrapper", IsWrapper = true)] public class GroupByTargetWrapper : WrapperTargetBase { private readonly SortHelpers.KeySelector _buildKeyStringDelegate; public Layout Key { get; set; } = Layout.Empty; public GroupByTargetWrapper() { _buildKeyStringDelegate = (AsyncLogEventInfo logEvent) => RenderLogEvent(Key, logEvent.LogEvent); } public GroupByTargetWrapper(Target wrappedTarget) : this(string.Empty, wrappedTarget) { } public GroupByTargetWrapper(string name, Target wrappedTarget) : this(name, wrappedTarget, Layout.Empty) { } public GroupByTargetWrapper(string name, Target wrappedTarget, Layout key) : this() { base.Name = ((!string.IsNullOrEmpty(name) || wrappedTarget == null || string.IsNullOrEmpty(wrappedTarget.Name)) ? name : (wrappedTarget.Name + "_wrapper")); base.WrappedTarget = wrappedTarget; Key = key; } protected override void InitializeTarget() { if (Key == null || Key == Layout.Empty) { throw new NLogConfigurationException("GroupByTargetWrapper Key-property must be assigned. Group LogEvents using blank Key not supported."); } base.InitializeTarget(); } protected override void Write(AsyncLogEventInfo logEvent) { base.WrappedTarget?.WriteAsyncLogEvent(logEvent); } protected override void Write(IList logEvents) { foreach (KeyValuePair> item in logEvents.BucketSort(_buildKeyStringDelegate)) { base.WrappedTarget?.WriteAsyncLogEvents(item.Value); } } } [Target("LimitingWrapper", IsWrapper = true)] public class LimitingTargetWrapper : WrapperTargetBase { private DateTime _firstWriteInInterval; public Layout MessageLimit { get; set; } public Layout Interval { get; set; } public int MessagesWrittenCount { get; private set; } public LimitingTargetWrapper() { MessageLimit = 1000; Interval = TimeSpan.FromHours(1.0); } public LimitingTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget, 1000, TimeSpan.FromHours(1.0)) { base.Name = name ?? base.Name; } public LimitingTargetWrapper(Target wrappedTarget) : this(wrappedTarget, 1000, TimeSpan.FromHours(1.0)) { } public LimitingTargetWrapper(Target wrappedTarget, int messageLimit, TimeSpan interval) { base.Name = ((wrappedTarget == null || string.IsNullOrEmpty(wrappedTarget.Name)) ? base.Name : (wrappedTarget.Name + "_wrapper")); base.WrappedTarget = wrappedTarget; MessageLimit = messageLimit; Interval = interval; } protected override void InitializeTarget() { if (MessageLimit.IsFixed && MessageLimit.FixedValue <= 0) { throw new NLogConfigurationException("The LimitingTargetWrapper's MessageLimit property must be > 0."); } if (Interval.IsFixed && Interval.FixedValue <= TimeSpan.Zero) { throw new NLogConfigurationException("The LimitingTargetWrapper's property Interval must be > 0."); } base.InitializeTarget(); ResetInterval(DateTime.MinValue); InternalLogger.Trace("{0}: Initialized with MessageLimit={1} and Interval={2}.", this, MessageLimit, Interval); } protected override void Write(AsyncLogEventInfo logEvent) { int num = RenderLogEvent(MessageLimit, logEvent.LogEvent, 0); TimeSpan timeSpan = RenderLogEvent(Interval, logEvent.LogEvent); if (logEvent.LogEvent.TimeStamp - _firstWriteInInterval > timeSpan) { ResetInterval(logEvent.LogEvent.TimeStamp); InternalLogger.Debug("{0}: New interval of '{1}' started.", this, timeSpan); } if (num <= 0 || MessagesWrittenCount < num) { base.WrappedTarget?.WriteAsyncLogEvent(logEvent); MessagesWrittenCount++; } else { logEvent.Continuation(null); InternalLogger.Trace("{0}: Discarded event, because MessageLimit of '{1}' was reached.", this, num); } } private void ResetInterval(DateTime timestamp) { _firstWriteInInterval = timestamp; MessagesWrittenCount = 0; } } public class LogEventDroppedEventArgs : EventArgs { public LogEventInfo DroppedLogEventInfo { get; } public LogEventDroppedEventArgs(LogEventInfo logEventInfo) { DroppedLogEventInfo = logEventInfo; } } public class LogEventQueueGrowEventArgs : EventArgs { public long NewQueueSize { get; } public long RequestsCount { get; } public LogEventQueueGrowEventArgs(long newQueueSize, long requestsCount) { NewQueueSize = newQueueSize; RequestsCount = requestsCount; } } [Target("PostFilteringWrapper", IsWrapper = true)] public class PostFilteringTargetWrapper : WrapperTargetBase { public ConditionExpression? DefaultFilter { get; set; } [ArrayParameter(typeof(FilteringRule), "when")] public IList Rules { get; } = new List(); public PostFilteringTargetWrapper() { } public PostFilteringTargetWrapper(Target wrappedTarget) : this(string.Empty, wrappedTarget) { } public PostFilteringTargetWrapper(string name, Target wrappedTarget) { base.Name = ((!string.IsNullOrEmpty(name) || wrappedTarget == null || string.IsNullOrEmpty(wrappedTarget.Name)) ? name : (wrappedTarget.Name + "_wrapper")); base.WrappedTarget = wrappedTarget; } protected override void InitializeTarget() { base.InitializeTarget(); foreach (FilteringRule rule in Rules) { if (rule.Exists == null) { throw new NLogConfigurationException("PostFilteringTargetWrapper When-Rules with unassigned Exists-property."); } if (rule.Filter == null) { throw new NLogConfigurationException("PostFilteringTargetWrapper When-Rules with unassigned Filter-property."); } } } protected override void Write(AsyncLogEventInfo logEvent) { Write(new AsyncLogEventInfo[1] { logEvent }); } protected override void Write(IList logEvents) { InternalLogger.Trace("{0}: Running on {1} events", this, logEvents.Count); ConditionExpression conditionExpression = EvaluateAllRules(logEvents); if (conditionExpression == null) { base.WrappedTarget?.WriteAsyncLogEvents(logEvents); return; } InternalLogger.Trace("{0}: Filter to apply: {1}", this, conditionExpression); IList list = logEvents.Filter(conditionExpression, (AsyncLogEventInfo logEvent, ConditionExpression filter) => ShouldLogEvent(logEvent, filter)); InternalLogger.Trace("{0}: After filtering: {1} events.", this, list.Count); if (list.Count > 0) { InternalLogger.Trace("{0}: Sending to {1}", this, base.WrappedTarget); base.WrappedTarget?.WriteAsyncLogEvents(list); } } private static bool ShouldLogEvent(AsyncLogEventInfo logEvent, ConditionExpression resultFilter) { object obj = resultFilter.Evaluate(logEvent.LogEvent); if (ConditionExpression.BoxedTrue.Equals(obj)) { return true; } logEvent.Continuation(null); return false; } private ConditionExpression? EvaluateAllRules(IList logEvents) { if (Rules.Count == 0) { return DefaultFilter; } for (int i = 0; i < logEvents.Count; i++) { for (int j = 0; j < Rules.Count; j++) { FilteringRule filteringRule = Rules[j]; object obj = filteringRule.Exists?.Evaluate(logEvents[i].LogEvent); if (ConditionExpression.BoxedTrue.Equals(obj)) { InternalLogger.Trace("{0}: Rule matched: {1}", this, filteringRule.Exists); return filteringRule.Filter; } } } return DefaultFilter; } } [Target("RandomizeGroup", IsCompound = true)] public class RandomizeGroupTarget : CompoundTargetBase { private readonly Random _random = new Random(); public RandomizeGroupTarget() : this(ArrayHelper.Empty()) { } public RandomizeGroupTarget(string name, params Target[] targets) : this(targets) { base.Name = name; } public RandomizeGroupTarget(params Target[] targets) : base(targets) { } protected override void Write(AsyncLogEventInfo logEvent) { if (base.Targets.Count == 0) { logEvent.Continuation(null); return; } int index; lock (_random) { index = _random.Next(base.Targets.Count); } base.Targets[index].WriteAsyncLogEvent(logEvent); } } [Target("RepeatingWrapper", IsWrapper = true)] public class RepeatingTargetWrapper : WrapperTargetBase { public int RepeatCount { get; set; } = 3; public RepeatingTargetWrapper() { } public RepeatingTargetWrapper(string name, Target wrappedTarget, int repeatCount) : this(wrappedTarget, repeatCount) { base.Name = name; } public RepeatingTargetWrapper(Target wrappedTarget, int repeatCount) { base.Name = ((wrappedTarget == null || string.IsNullOrEmpty(wrappedTarget.Name)) ? base.Name : (wrappedTarget.Name + "_wrapper")); base.WrappedTarget = wrappedTarget; RepeatCount = repeatCount; } protected override void Write(AsyncLogEventInfo logEvent) { AsyncHelpers.Repeat(RepeatCount, logEvent.Continuation, delegate(AsyncContinuation cont) { base.WrappedTarget?.WriteAsyncLogEvent(logEvent.LogEvent.WithContinuation(cont)); }); } } [Target("RetryingWrapper", IsWrapper = true)] public class RetryingTargetWrapper : WrapperTargetBase { private readonly object _retrySyncObject = new object(); public Layout RetryCount { get; set; } public Layout RetryDelayMilliseconds { get; set; } public bool EnableBatchWrite { get; set; } = true; public RetryingTargetWrapper() { RetryCount = 3; RetryDelayMilliseconds = 100; } public RetryingTargetWrapper(string name, Target wrappedTarget, int retryCount, int retryDelayMilliseconds) : this(wrappedTarget, retryCount, retryDelayMilliseconds) { base.Name = name ?? base.Name; } public RetryingTargetWrapper(Target wrappedTarget, int retryCount, int retryDelayMilliseconds) { base.Name = ((wrappedTarget == null || string.IsNullOrEmpty(wrappedTarget.Name)) ? base.Name : (wrappedTarget.Name + "_wrapper")); base.WrappedTarget = wrappedTarget; RetryCount = retryCount; RetryDelayMilliseconds = retryDelayMilliseconds; } protected override void WriteAsyncThreadSafe(IList logEvents) { if (logEvents.Count == 1) { WriteAsyncThreadSafe(logEvents[0]); return; } if (EnableBatchWrite) { int initialSleep = 1; Func sleepBeforeRetry = (int retryNumber) => retryNumber > 1 || Interlocked.Exchange(ref initialSleep, 0) == 1; for (int i = 0; i < logEvents.Count; i++) { logEvents[i] = WrapWithRetry(logEvents[i], sleepBeforeRetry); } lock (_retrySyncObject) { base.WrappedTarget?.WriteAsyncLogEvents(logEvents); return; } } lock (_retrySyncObject) { for (int j = 0; j < logEvents.Count; j++) { WriteAsyncThreadSafe(logEvents[j]); } } } protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { lock (_retrySyncObject) { Write(logEvent); } } protected override void Write(AsyncLogEventInfo logEvent) { base.WrappedTarget?.WriteAsyncLogEvent(WrapWithRetry(logEvent, (int retryNumber) => true)); } private AsyncLogEventInfo WrapWithRetry(AsyncLogEventInfo logEvent, Func sleepBeforeRetry) { Func sleepBeforeRetry2 = sleepBeforeRetry; AsyncContinuation continuation = null; int counter = 0; continuation = delegate(Exception? ex) { if (ex == null) { logEvent.Continuation(null); } else { int num = Interlocked.Increment(ref counter); int num2 = RetryCount.RenderValue(logEvent.LogEvent, 0); int num3 = RetryDelayMilliseconds.RenderValue(logEvent.LogEvent, 0); InternalLogger.Warn(ex, "{0}: Error while writing to '{1}'. Try {2}/{3}", new ReadOnlySpan(new object[4] { this, base.WrappedTarget, num, num2 })); if (num >= num2) { InternalLogger.Warn("{0}: Too many retries. Aborting.", this); logEvent.Continuation(ex); } else { if (sleepBeforeRetry2(num)) { int num4 = 0; while (num4 < num3) { int num5 = Math.Min(100, num3 - num4); AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(num5)); num4 += num5; if (!base.IsInitialized) { InternalLogger.Warn("{0}): Target closed. Aborting.", this); logEvent.Continuation(ex); return; } } } base.WrappedTarget?.WriteAsyncLogEvent((continuation == null) ? logEvent : logEvent.LogEvent.WithContinuation(continuation)); } } }; return logEvent.LogEvent.WithContinuation(continuation); } } [Target("RoundRobinGroup", IsCompound = true)] public class RoundRobinGroupTarget : CompoundTargetBase { private int _currentTarget = -1; public RoundRobinGroupTarget() : this(ArrayHelper.Empty()) { } public RoundRobinGroupTarget(string name, params Target[] targets) : this(targets) { base.Name = name; } public RoundRobinGroupTarget(params Target[] targets) : base(targets) { } protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent) { Write(logEvent); } protected override void Write(AsyncLogEventInfo logEvent) { if (base.Targets.Count == 0) { logEvent.Continuation(null); return; } int index = (int)((uint)Interlocked.Increment(ref _currentTarget) % base.Targets.Count); base.Targets[index].WriteAsyncLogEvent(logEvent); } } [Target("SplitGroup", IsCompound = true)] public class SplitGroupTarget : CompoundTargetBase { public SplitGroupTarget() : this(ArrayHelper.Empty()) { } public SplitGroupTarget(string name, params Target[] targets) : this(targets) { base.Name = name; } public SplitGroupTarget(params Target[] targets) : base(targets) { } protected override void Write(AsyncLogEventInfo logEvent) { if (base.Targets.Count == 0) { logEvent.Continuation(null); return; } if (base.Targets.Count > 1) { logEvent = logEvent.LogEvent.WithContinuation(CreateCountedContinuation(logEvent.Continuation, base.Targets.Count)); } for (int i = 0; i < base.Targets.Count; i++) { base.Targets[i].WriteAsyncLogEvent(logEvent); } } protected override void Write(IList logEvents) { InternalLogger.Trace("{0}: Writing {1} events", this, logEvents.Count); if (logEvents.Count == 1) { Write(logEvents[0]); return; } if (base.Targets.Count == 0 || logEvents.Count == 0) { for (int i = 0; i < logEvents.Count; i++) { logEvents[i].Continuation(null); } return; } if (base.Targets.Count > 1) { for (int j = 0; j < logEvents.Count; j++) { AsyncLogEventInfo asyncLogEventInfo = logEvents[j]; logEvents[j] = asyncLogEventInfo.LogEvent.WithContinuation(CreateCountedContinuation(asyncLogEventInfo.Continuation, base.Targets.Count)); } } for (int k = 0; k < base.Targets.Count; k++) { InternalLogger.Trace("{0}: Sending {1} events to {2}", this, logEvents.Count, base.Targets[k]); IList logEvents2 = logEvents; if (k < base.Targets.Count - 1) { AsyncLogEventInfo[] array = new AsyncLogEventInfo[logEvents.Count]; logEvents.CopyTo(array, 0); logEvents2 = array; } base.Targets[k].WriteAsyncLogEvents(logEvents2); } } private static AsyncContinuation CreateCountedContinuation(AsyncContinuation originalContinuation, int targetCounter) { AsyncContinuation originalContinuation2 = originalContinuation; IList exceptions = null; return delegate(Exception? ex) { if (ex != null) { if (exceptions == null) { Interlocked.CompareExchange(ref exceptions, new List(), null); } lock (exceptions) { exceptions.Add(ex); } } int num = Interlocked.Decrement(ref targetCounter); if (num == 0) { Exception combinedException = AsyncHelpers.GetCombinedException(exceptions ?? ArrayHelper.Empty()); InternalLogger.Trace("SplitGroup: Combined exception: {0}", combinedException); originalContinuation2(combinedException); } else { InternalLogger.Trace("SplitGroup: {0} remaining.", num); } }; } } public abstract class WrapperTargetBase : Target { private Target? _wrappedTarget; public Target? WrappedTarget { get { return _wrappedTarget; } set { _wrappedTarget = value; _tostring = null; } } public override string ToString() { return _tostring ?? (_tostring = GenerateTargetToString()); } private string GenerateTargetToString() { if (WrappedTarget == null) { return GenerateTargetToString(targetWrapper: true); } if (string.IsNullOrEmpty(base.Name)) { return $"{GenerateTargetToString(targetWrapper: true, string.Empty)}_{WrappedTarget}"; } return GenerateTargetToString(targetWrapper: true, string.Empty) + "_" + WrappedTarget.GenerateTargetToString(targetWrapper: false, base.Name); } protected override void FlushAsync(AsyncContinuation asyncContinuation) { if (WrappedTarget == null) { asyncContinuation(null); } else { WrappedTarget.Flush(asyncContinuation); } } protected override void InitializeTarget() { if (WrappedTarget == null) { throw new NLogConfigurationException(GetType().Name + "(Name=" + base.Name + "): No wrapped Target configured."); } base.InitializeTarget(); } protected sealed override void Write(LogEventInfo logEvent) { throw new NotSupportedException("This target must not be invoked in a synchronous way."); } } } namespace NLog.Targets.FileArchiveHandlers { internal class BaseFileArchiveHandler { private readonly struct FileInfoDateTime : IComparer { [CompilerGenerated] private sealed class d__15 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private FileInfo <>2__current; private int <>l__initialThreadId; private FileInfo[] fileInfos; public FileInfo[] <>3__fileInfos; private int fileWildcardStartIndex; public int <>3__fileWildcardStartIndex; private int fileWildcardEndIndex; public int <>3__fileWildcardEndIndex; private bool parseArchiveSequenceNo; public bool <>3__parseArchiveSequenceNo; private string excludeFileName; public string <>3__excludeFileName; private int maxArchiveFiles; public int <>3__maxArchiveFiles; private int maxArchiveDays; public int <>3__maxArchiveDays; private List 5__2; private int 5__3; FileInfo IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__15(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: { <>1__state = -1; if (fileInfos.Length == 1) { if (ExcludeFileName(fileInfos[0].Name, fileWildcardStartIndex, fileWildcardEndIndex, parseArchiveSequenceNo, excludeFileName)) { return false; } if (maxArchiveFiles == 0) { <>2__current = fileInfos[0]; <>1__state = 1; return true; } } 5__2 = new List(fileInfos.Length); FileInfo[] array = fileInfos; foreach (FileInfo fileInfo in array) { string name = fileInfo.Name; if (!ExcludeFileName(name, fileWildcardStartIndex, fileWildcardEndIndex, parseArchiveSequenceNo, excludeFileName)) { DateTime fileCreatedTimeUtc = fileInfo.LookupValidFileCreationTimeUtc(); if (parseArchiveSequenceNo && TryParseStartSequenceNumber(name, fileWildcardStartIndex, fileWildcardEndIndex, out var archiveSequenceNo)) { 5__2.Add(new FileInfoDateTime(fileInfo, fileCreatedTimeUtc, archiveSequenceNo)); } else { 5__2.Add(new FileInfoDateTime(fileInfo, fileCreatedTimeUtc)); } } } 5__2.Sort((FileInfoDateTime x, FileInfoDateTime y) => x.Compare(x, y)); 5__3 = 0; break; } case 1: <>1__state = -1; return false; case 2: <>1__state = -1; 5__3++; break; } if (5__3 < 5__2.Count) { if (ShouldDeleteFile(5__2[5__3], 5__2.Count - 5__3, maxArchiveFiles, maxArchiveDays)) { <>2__current = 5__2[5__3].FileInfo; <>1__state = 2; return true; } return false; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { d__15 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__15(0); } d__.fileInfos = <>3__fileInfos; d__.maxArchiveFiles = <>3__maxArchiveFiles; d__.maxArchiveDays = <>3__maxArchiveDays; d__.fileWildcardStartIndex = <>3__fileWildcardStartIndex; d__.fileWildcardEndIndex = <>3__fileWildcardEndIndex; d__.parseArchiveSequenceNo = <>3__parseArchiveSequenceNo; d__.excludeFileName = <>3__excludeFileName; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } public FileInfo FileInfo { get; } public DateTime FileCreatedTimeUtc { get; } public int? ArchiveSequenceNumber { get; } public FileInfoDateTime(FileInfo fileInfo, DateTime fileCreatedTimeUtc, int? archiveSequenceNumber = null) { FileInfo = fileInfo; ArchiveSequenceNumber = archiveSequenceNumber; FileCreatedTimeUtc = fileCreatedTimeUtc; } public int Compare(FileInfoDateTime x, FileInfoDateTime y) { if (x.ArchiveSequenceNumber.HasValue && y.ArchiveSequenceNumber.HasValue) { return x.ArchiveSequenceNumber.Value.CompareTo(y.ArchiveSequenceNumber.Value); } if (x.FileCreatedTimeUtc.Date == y.FileCreatedTimeUtc.Date) { return NaturalStringComparer(x.FileInfo.Name, y.FileInfo.Name); } return x.FileCreatedTimeUtc.CompareTo(y.FileCreatedTimeUtc); } private static int NaturalStringComparer(string x, string y) { if (x == null || y == null || x.Length == y.Length) { return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); } int x_pos = 0; int y_pos = 0; while (x_pos < x.Length && y_pos < y.Length) { char c = x[x_pos]; char c2 = y[y_pos]; if (char.IsDigit(c) && char.IsDigit(c2)) { int num = NaturalStringCompareNumericBlocks(x, ref x_pos, y, ref y_pos); if (num != 0) { return num; } continue; } if (c != c2) { int num2 = char.ToUpperInvariant(c).CompareTo(char.ToUpperInvariant(c2)); if (num2 != 0) { return num2; } } x_pos++; y_pos++; } return x.Length.CompareTo(y.Length); } private static int NaturalStringCompareNumericBlocks(string x, ref int x_pos, string y, ref int y_pos) { while (x_pos < x.Length && x[x_pos] == '0') { x_pos++; } while (y_pos < y.Length && y[y_pos] == '0') { y_pos++; } int num = x_pos; int num2 = y_pos; while (x_pos < x.Length && char.IsDigit(x[x_pos])) { x_pos++; } while (y_pos < y.Length && char.IsDigit(y[y_pos])) { y_pos++; } int num3 = x_pos - num; int num4 = y_pos - num2; if (num3 != num4) { return num3.CompareTo(num4); } for (int i = 0; i < num3; i++) { int num5 = x[num + i].CompareTo(y[num2 + i]); if (num5 != 0) { return num5; } } return 0; } public override string ToString() { return FileInfo.Name; } public static int? ScanFileNamesForMaxSequenceNo(FileInfo[] fileInfos, int fileWildcardStartIndex, int fileWildcardEndIndex) { int? result = null; if (fileWildcardStartIndex < 0) { return null; } for (int i = 0; i < fileInfos.Length; i++) { string name = fileInfos[i].Name; if (!ExcludeFileName(name, fileWildcardStartIndex, fileWildcardEndIndex, parseArchiveSequenceNo: true, null) && TryParseStartSequenceNumber(name, fileWildcardStartIndex, fileWildcardEndIndex, out var archiveSequenceNo) && (!result.HasValue || archiveSequenceNo > result.Value)) { result = archiveSequenceNo; } } return result; } [IteratorStateMachine(typeof(d__15))] public static IEnumerable CleanupFiles(FileInfo[] fileInfos, int maxArchiveFiles, int maxArchiveDays, int fileWildcardStartIndex, int fileWildcardEndIndex, bool parseArchiveSequenceNo, string? excludeFileName = null) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__15(-2) { <>3__fileInfos = fileInfos, <>3__maxArchiveFiles = maxArchiveFiles, <>3__maxArchiveDays = maxArchiveDays, <>3__fileWildcardStartIndex = fileWildcardStartIndex, <>3__fileWildcardEndIndex = fileWildcardEndIndex, <>3__parseArchiveSequenceNo = parseArchiveSequenceNo, <>3__excludeFileName = excludeFileName }; } private static bool ExcludeFileName(string archiveFileName, int fileWildcardStartIndex, int fileWildcardEndIndex, bool parseArchiveSequenceNo, string? excludeFileName) { if (fileWildcardStartIndex >= 0 && fileWildcardEndIndex > 0 && parseArchiveSequenceNo) { for (int i = fileWildcardStartIndex; i <= archiveFileName.Length - fileWildcardEndIndex; i++) { if (char.IsLetter(archiveFileName[i])) { return true; } } } if (excludeFileName == null) { return false; } return string.Equals(archiveFileName, excludeFileName, StringComparison.OrdinalIgnoreCase); } private static bool ShouldDeleteFile(FileInfoDateTime existingArchiveFile, int remainingFileCount, int maxArchiveFiles, int maxArchiveDays) { if (maxArchiveFiles >= 0 && remainingFileCount > maxArchiveFiles) { return true; } if (maxArchiveDays > 0) { DateTime date = TimeSource.Current.Time.Date; DateTime dateTime = TimeSource.Current.FromSystemTime(existingArchiveFile.FileCreatedTimeUtc); double totalDays = (date - dateTime.Date).TotalDays; if (totalDays > (double)maxArchiveDays) { InternalLogger.Debug("FileTarget: Archive cleanup found old file: {0} , Age={1} days, FileCreated={2:u}, CurrentDate={3:u}", new ReadOnlySpan(new object[4] { existingArchiveFile.FileInfo.FullName, Math.Round(totalDays, 1), dateTime, date })); return true; } } return false; } private static bool TryParseStartSequenceNumber(string archiveFileName, int fileWildcardStartIndex, int fileWildcardEndIndex, out int archiveSequenceNo) { int? num = null; bool flag = false; if (fileWildcardStartIndex < 0 || fileWildcardEndIndex <= 0) { archiveSequenceNo = 0; return false; } for (int i = fileWildcardStartIndex; i <= archiveFileName.Length - fileWildcardEndIndex; i++) { char c = archiveFileName[i]; if (!char.IsDigit(c)) { flag = num.HasValue; continue; } if (flag) { archiveSequenceNo = 0; return false; } num = ((!(num > 0)) ? new int?(0) : (num * 10)) + (c - 48); } archiveSequenceNo = num.GetValueOrDefault(); return num.HasValue; } } protected readonly FileTarget _fileTarget; public BaseFileArchiveHandler(FileTarget fileTarget) { _fileTarget = fileTarget; } protected bool DeleteOldFilesBeforeArchive(string filePath, bool initialFileOpen, bool parseArchiveSequenceNo, string? excludeFileName = null) { string fileDirectory = Path.GetDirectoryName(filePath) ?? string.Empty; string deleteOldFileNameWildcard = GetDeleteOldFileNameWildcard(filePath); return DeleteOldFilesBeforeArchive(fileDirectory, deleteOldFileNameWildcard, initialFileOpen, parseArchiveSequenceNo, excludeFileName); } protected bool DeleteOldFilesBeforeArchive(string fileDirectory, string fileWildcard, bool initialFileOpen, bool parseArchiveSequenceNo, string? excludeFileName = null) { try { if (string.IsNullOrEmpty(fileWildcard)) { return false; } if (string.IsNullOrEmpty(fileDirectory)) { return false; } DirectoryInfo directoryInfo = new DirectoryInfo(fileDirectory); if (!directoryInfo.Exists) { InternalLogger.Debug("{0}: Archive cleanup found no files matching wildcard '{1}' in directory: {2}", _fileTarget, fileWildcard, fileDirectory); return false; } FileInfo[] files = directoryInfo.GetFiles(fileWildcard); InternalLogger.Debug("{0}: Archive cleanup found {1} files matching wildcard '{2}' in directory: {3}", new ReadOnlySpan(new object[4] { _fileTarget, files.Length, fileWildcard, fileDirectory })); if (files.Length == 0) { return false; } int num = ResolveMaxArchiveFiles(initialFileOpen); if (num >= files.Length && _fileTarget.MaxArchiveDays <= 0) { return false; } string archiveCleanupReason = ((_fileTarget.MaxArchiveFiles < 0 && _fileTarget.MaxArchiveDays > 0) ? $"MaxArchiveDays={_fileTarget.MaxArchiveDays}" : $"MaxArchiveFiles={_fileTarget.MaxArchiveFiles}"); if (initialFileOpen && _fileTarget.DeleteOldFileOnStartup) { archiveCleanupReason = "DeleteOldFileOnStartup=true"; } int num2 = fileWildcard.IndexOf('*'); int fileWildcardEndIndex = ((num2 >= 0 && num2 == fileWildcard.LastIndexOf('*')) ? (fileWildcard.Length - num2) : (-1)); bool result = false; foreach (FileInfo item in FileInfoDateTime.CleanupFiles(files, num, _fileTarget.MaxArchiveDays, num2, fileWildcardEndIndex, parseArchiveSequenceNo, excludeFileName)) { result = true; DeleteOldArchiveFile(item.FullName, archiveCleanupReason); } return result; } catch (Exception ex) { InternalLogger.Warn(ex, "{0}: Failed to cleanup archive folder: {1} {2}", new ReadOnlySpan(new object[3] { _fileTarget, fileDirectory, fileWildcard ?? "" })); if (ex.MustBeRethrown(_fileTarget)) { throw; } } return false; } private int ResolveMaxArchiveFiles(bool initialFileOpen) { int num = _fileTarget.MaxArchiveFiles; if (initialFileOpen && (!_fileTarget.ArchiveOldFileOnStartup || _fileTarget.DeleteOldFileOnStartup)) { num = ((!_fileTarget.DeleteOldFileOnStartup) ? num : 0); } else if (num > 0) { num--; } return num; } protected static int? GetMaxArchiveSequenceNo(FileInfo[] fileInfos, int fileWildcardStartIndex, int fileWildcardEndIndex) { return FileInfoDateTime.ScanFileNamesForMaxSequenceNo(fileInfos, fileWildcardStartIndex, fileWildcardEndIndex); } private static string GetDeleteOldFileNameWildcard(string filepath) { string text = Path.GetFileNameWithoutExtension(filepath) ?? string.Empty; string text2 = Path.GetExtension(filepath) ?? string.Empty; if (string.IsNullOrEmpty(text) && string.IsNullOrEmpty(text2)) { return string.Empty; } int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; bool flag = false; for (int i = 0; i < text.Length; i++) { if (!char.IsLetter(text[i])) { flag = flag || char.IsDigit(text[i]); if (flag) { if (num3 == 0) { num4 = i; } num3++; } continue; } if (num3 != 0) { if (num2 <= num3) { num = num4; num2 = num3; } num3 = 0; } flag = false; } if (num2 < num3) { num = num4; num2 = num3; } if (num2 > 0) { string text3 = text.Substring(0, num); string text4 = text.Substring(num + num2); if (!string.IsNullOrEmpty(text4)) { return text3 + "*" + text4 + "*" + text2; } return text3 + "*" + text2; } return text + "*" + text2; } protected bool DeleteOldArchiveFile(string filepath, string archiveCleanupReason) { for (int i = 1; i <= 3; i++) { try { InternalLogger.Info("{0}: Cleanup file archive {1}. Delete file: '{2}'", _fileTarget, archiveCleanupReason, filepath); _fileTarget.CloseOpenFileBeforeArchiveCleanup(filepath); File.Delete(filepath); return true; } catch (DirectoryNotFoundException ex) { InternalLogger.Debug(ex, "{0}: Failed to delete old file as directory not found: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, filepath })); return true; } catch (FileNotFoundException ex2) { InternalLogger.Debug(ex2, "{0}: Failed to delete old file as file not found: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, filepath })); return true; } catch (IOException ex3) { InternalLogger.Debug(ex3, "{0}: Failed to delete old file, maybe file is locked: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, filepath })); if (!File.Exists(filepath)) { return true; } if (i >= 3 && ex3.MustBeRethrown(_fileTarget)) { throw; } } catch (Exception ex4) { InternalLogger.Warn(ex4, "{0}: Failed to delete old archive file: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, filepath })); if (ex4.MustBeRethrown(_fileTarget)) { throw; } return false; } Thread.Sleep(i * 10); } return false; } protected void FixWindowsFileSystemTunneling(string newFilePath) { try { if (PlatformDetector.IsWin32 && !File.Exists(newFilePath)) { File.Create(newFilePath).Dispose(); File.SetCreationTimeUtc(newFilePath, DateTime.UtcNow); } } catch (Exception ex) { InternalLogger.Debug(ex, "{0}: Failed to refresh CreationTimeUtc for file: {1}", new ReadOnlySpan(new object[2] { _fileTarget, newFilePath })); } } } internal sealed class DisabledFileArchiveHandler : IFileArchiveHandler { public static readonly IFileArchiveHandler Default = new DisabledFileArchiveHandler(); public int ArchiveBeforeOpenFile(string newFileName, LogEventInfo firstLogEvent, DateTime? previousFileLastModified, int newSequenceNumber) { return 0; } } internal interface IFileArchiveHandler { int ArchiveBeforeOpenFile(string newFileName, LogEventInfo firstLogEvent, DateTime? previousFileLastModified, int newSequenceNumber); } internal sealed class LegacyArchiveFileNameHandler : RollingArchiveFileHandler, IFileArchiveHandler { public LegacyArchiveFileNameHandler(FileTarget fileTarget) : base(fileTarget) { } public override int ArchiveBeforeOpenFile(string newFileName, LogEventInfo firstLogEvent, DateTime? previousFileLastModified, int newSequenceNumber) { string text = _fileTarget.ArchiveFileName?.Render(firstLogEvent); if (text == null || StringHelpers.IsNullOrWhiteSpace(text)) { return base.ArchiveBeforeOpenFile(newFileName, firstLogEvent, previousFileLastModified, newSequenceNumber); } string newFilePath = FileTarget.CleanFullFilePath(newFileName); bool initialFileOpen = newSequenceNumber == 0; if (ArchiveBeforeOpenFile(text, newFilePath, firstLogEvent, previousFileLastModified, initialFileOpen)) { FixWindowsFileSystemTunneling(newFilePath); } return 0; } private bool ArchiveBeforeOpenFile(string archiveFileName, string newFilePath, LogEventInfo firstLogEvent, DateTime? previousFileLastModified, bool initialFileOpen) { bool result = false; if (_fileTarget.MaxArchiveFiles >= 0 || _fileTarget.MaxArchiveDays > 0 || (initialFileOpen && _fileTarget.DeleteOldFileOnStartup)) { bool num = _fileTarget.ArchiveSuffixFormat.IndexOf("{0", StringComparison.Ordinal) >= 0 && _fileTarget.ArchiveSuffixFormat.IndexOf("{1", StringComparison.Ordinal) < 0 && (!(_fileTarget.ArchiveFileName is SimpleLayout simpleLayout) || (simpleLayout.OriginalText.IndexOf("${date", StringComparison.OrdinalIgnoreCase) < 0 && simpleLayout.OriginalText.IndexOf("${shortdate", StringComparison.OrdinalIgnoreCase) < 0)); string fileName = Path.GetFileName(newFilePath); if (num) { string text = BuildArchiveFilePath(archiveFileName, int.MaxValue, DateTime.MinValue); string path = text.Replace(int.MaxValue.ToString(), "*"); string fileDirectory = Path.GetDirectoryName(text) ?? string.Empty; result = DeleteOldFilesBeforeArchive(fileDirectory, Path.GetFileName(path), initialFileOpen, parseArchiveSequenceNo: true, fileName); } else { string filePath = FileTarget.CleanFullFilePath(archiveFileName); result = DeleteOldFilesBeforeArchive(filePath, initialFileOpen, parseArchiveSequenceNo: false, fileName); } } if (initialFileOpen && !_fileTarget.ArchiveOldFileOnStartup) { return result; } if (!ArchiveOldFileWithRetry(archiveFileName, newFilePath, firstLogEvent, previousFileLastModified)) { return result; } return true; } private bool ArchiveOldFileWithRetry(string archiveFileName, string newFilePath, LogEventInfo firstLogEvent, DateTime? previousFileLastModified) { DateTime? dateTime = null; long? num = null; bool result = false; for (int i = 1; i <= 3; i++) { try { FileInfo fileInfo = new FileInfo(newFilePath); if (!fileInfo.Exists) { return result; } result = true; if (HasFileInfoChanged(fileInfo, dateTime, num)) { return false; } dateTime = dateTime ?? fileInfo.LastWriteTimeUtc; num = num ?? fileInfo.Length; if (ArchiveOldFile(archiveFileName, fileInfo, firstLogEvent, previousFileLastModified)) { return true; } } catch (IOException ex) { InternalLogger.Debug(ex, "{0}: Failed to archive file, maybe file is locked: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, newFilePath })); if (!File.Exists(newFilePath)) { return result; } if (i >= 3 && LogManager.ThrowExceptions) { throw; } } catch (Exception ex2) { InternalLogger.Debug(ex2, "{0}: Failed to archive file: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, newFilePath })); if (LogManager.ThrowExceptions) { throw; } Thread.Sleep(i * 10); } } return result; } private static bool HasFileInfoChanged(FileInfo newFileInfo, DateTime? lastWriteTimeUtc, long? lastFileLength) { if (lastWriteTimeUtc.HasValue && lastWriteTimeUtc.Value != newFileInfo.LastWriteTimeUtc) { return true; } if (lastFileLength.HasValue && lastFileLength.Value != newFileInfo.Length) { return true; } return false; } private bool ArchiveOldFile(string archiveFileName, FileInfo newFileInfo, LogEventInfo firstLogEvent, DateTime? previousFileLastModified) { DateTime dateTime = TimeSource.Current.FromSystemTime(newFileInfo.LastWriteTimeUtc); if (previousFileLastModified.HasValue && (previousFileLastModified > dateTime || dateTime >= firstLogEvent.TimeStamp)) { dateTime = previousFileLastModified.Value; } int num = ResolveNextArchiveSequenceNo(archiveFileName, newFileInfo, dateTime); string text = BuildArchiveFilePath(archiveFileName, num, dateTime); if (!File.Exists(text)) { InternalLogger.Info("{0}: Archive moving file from '{1}' to '{2}'", _fileTarget, newFileInfo.FullName, text); File.Move(newFileInfo.FullName, text); return true; } if (!newFileInfo.Exists) { return true; } if (num == 0) { ArchiveFileAppendExisting(newFileInfo.FullName, text); return true; } return false; } private string BuildArchiveFilePath(string archiveFileName, int archiveNextSequenceNo, DateTime fileLastWriteTime) { return _fileTarget.BuildFullFilePath(archiveFileName, archiveNextSequenceNo, fileLastWriteTime); } private void ArchiveFileAppendExisting(string newFilePath, string archiveFilePath) { InternalLogger.Info("{0}: Archive appending to already existing file: {1}", _fileTarget, archiveFilePath); FileShare fileShare = FileShare.Read | FileShare.Delete; using (FileStream fileStream = File.Open(newFilePath, FileMode.Open, FileAccess.ReadWrite, fileShare)) { using FileStream fileStream2 = File.Open(archiveFilePath, FileMode.Append); if (_fileTarget.WriteBom) { byte[] preamble = _fileTarget.Encoding.GetPreamble(); if (preamble.Length != 0) { fileStream.Seek(preamble.Length, SeekOrigin.Begin); } } byte[] array = new byte[4096]; int count; while ((count = fileStream.Read(array, 0, array.Length)) > 0) { fileStream2.Write(array, 0, count); } fileStream.SetLength(0L); if (!DeleteOldArchiveFile(newFilePath, "Truncate Active File")) { fileShare &= ~FileShare.Delete; } fileStream.Close(); } if ((fileShare & FileShare.Delete) == 0) { DeleteOldArchiveFile(newFilePath, "Truncate Active File"); } } private int ResolveNextArchiveSequenceNo(string archiveFileName, FileInfo newFileInfo, DateTime fileLastWriteTime) { string path = BuildArchiveFilePath(archiveFileName, int.MaxValue, fileLastWriteTime); string directoryName = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(directoryName)) { return 0; } DirectoryInfo directoryInfo = new DirectoryInfo(directoryName); if (!directoryInfo.Exists && _fileTarget.CreateDirs) { InternalLogger.Debug("{0}: Creating archive directory: {1}", _fileTarget, directoryName); directoryInfo.Create(); } string text = Path.GetFileName(path).Replace(int.MaxValue.ToString(), "*"); int num = text.IndexOf('*'); if (num < 0) { return 0; } int fileWildcardEndIndex = text.Length - num; if (num > 0 && !char.IsLetterOrDigit(text[num - 1])) { text = text.Substring(0, num - 1) + text.Substring(num); } FileInfo[] files = directoryInfo.GetFiles(text); InternalLogger.Debug("{0}: Archive Sequence Rolling found {1} files matching wildcard {2} in directory: {3}", new ReadOnlySpan(new object[4] { _fileTarget, files.Length, text, directoryName })); if (files.Length == 0) { return 0; } int? maxArchiveSequenceNo = BaseFileArchiveHandler.GetMaxArchiveSequenceNo(files, num, fileWildcardEndIndex); if (maxArchiveSequenceNo.HasValue) { return maxArchiveSequenceNo.Value + 1; } if (string.Equals(directoryInfo.FullName, newFileInfo.DirectoryName, StringComparison.OrdinalIgnoreCase) && string.Equals(Path.GetFileName(archiveFileName), newFileInfo.Name, StringComparison.OrdinalIgnoreCase)) { return 1; } return 0; } } internal class RollingArchiveFileHandler : BaseFileArchiveHandler, IFileArchiveHandler { public RollingArchiveFileHandler(FileTarget fileTarget) : base(fileTarget) { } public virtual int ArchiveBeforeOpenFile(string newFileName, LogEventInfo firstLogEvent, DateTime? previousFileLastModified, int newSequenceNumber) { bool flag = newSequenceNumber == 0; if (_fileTarget.MaxArchiveFiles >= 0 || _fileTarget.MaxArchiveDays > 0 || (flag && _fileTarget.DeleteOldFileOnStartup)) { string text = FileTarget.CleanFullFilePath(newFileName); bool parseArchiveSequenceNo = !Path.GetFileNameWithoutExtension(text).Any((char c) => char.IsDigit(c)); bool flag2 = flag && File.Exists(text); bool flag3 = DeleteOldFilesBeforeArchive(text, flag, parseArchiveSequenceNo); if (_fileTarget.MaxArchiveFiles == 0 || _fileTarget.MaxArchiveFiles == 1 || (flag && _fileTarget.DeleteOldFileOnStartup)) { if (flag3) { FixWindowsFileSystemTunneling(text); } return 0; } if (flag2 && flag3) { FixWindowsFileSystemTunneling(text); } } if (flag && (_fileTarget.ArchiveOldFileOnStartup || _fileTarget.ArchiveAboveSize > 0 || _fileTarget.ArchiveEvery != 0)) { string newFilePath = FileTarget.CleanFullFilePath(newFileName); return RollToInitialSequenceNumber(newFilePath); } return newSequenceNumber; } private int RollToInitialSequenceNumber(string newFilePath) { int num = 0; try { if (AllowOptimizedRollingForArchiveAboveSize()) { FileInfo fileInfo = new FileInfo(newFilePath); long num2 = (fileInfo.Exists ? fileInfo.Length : 0); if (num2 > 0 && num2 < _fileTarget.ArchiveAboveSize) { InternalLogger.Debug("{0}: Archive rolling skipped because file-size={1} < ArchiveAboveSize for file: {2}", _fileTarget, num2, newFilePath); return num; } } string directoryName = Path.GetDirectoryName(newFilePath); if (string.IsNullOrEmpty(directoryName)) { return 0; } DirectoryInfo directoryInfo = new DirectoryInfo(directoryName); if (!directoryInfo.Exists) { InternalLogger.Debug("{0}: Archive Sequence Rolling found no files in directory: {1}", _fileTarget, directoryName); return 0; } string? fileNameWithoutExtension = Path.GetFileNameWithoutExtension(newFilePath); string extension = Path.GetExtension(newFilePath); string text = fileNameWithoutExtension + "*" + extension; FileInfo[] files = directoryInfo.GetFiles(text); InternalLogger.Debug("{0}: Archive Sequence Rolling found {1} files matching wildcard {2} in directory: {3}", new ReadOnlySpan(new object[4] { _fileTarget, files.Length, text, directoryName })); if (files.Length == 0) { return 0; } if (_fileTarget.DeleteOldFileOnStartup) { FileInfo[] array = files; foreach (FileInfo fileInfo2 in array) { DeleteOldArchiveFile(fileInfo2.FullName, "DeleteOldFileOnStartup=true"); } return 0; } string fileName = Path.GetFileName(_fileTarget.BuildFullFilePath(newFilePath, int.MaxValue, DateTime.MinValue).Replace(int.MaxValue.ToString(), "*")); int num3 = fileName.IndexOf('*'); int fileWildcardEndIndex = ((num3 >= 0) ? (fileName.Length - num3) : (-1)); num = BaseFileArchiveHandler.GetMaxArchiveSequenceNo(files, num3, fileWildcardEndIndex).GetValueOrDefault(); if (_fileTarget.ArchiveOldFileOnStartup) { num++; } return num; } catch (Exception ex) { InternalLogger.Warn(ex, "{0}: Failed to resolve initial archive sequence number for file: {1}", new ReadOnlySpan(new object[2] { _fileTarget, newFilePath })); if (ex.MustBeRethrown(_fileTarget)) { throw; } return num; } } private bool AllowOptimizedRollingForArchiveAboveSize() { if (_fileTarget.ArchiveAboveSize > 0 && _fileTarget.ArchiveEvery == FileArchivePeriod.None && !_fileTarget.ArchiveOldFileOnStartup && !_fileTarget.DeleteOldFileOnStartup) { return _fileTarget.GetType().Equals(typeof(FileTarget)); } return false; } } internal sealed class ZeroFileArchiveHandler : BaseFileArchiveHandler, IFileArchiveHandler { public ZeroFileArchiveHandler(FileTarget fileTarget) : base(fileTarget) { } public int ArchiveBeforeOpenFile(string newFileName, LogEventInfo firstLogEvent, DateTime? previousFileLastModified, int newSequenceNumber) { string newFilePath = FileTarget.CleanFullFilePath(newFileName); bool initialFileOpen = newSequenceNumber == 0; if (DeleteOldArchiveFiles(newFilePath, initialFileOpen)) { FixWindowsFileSystemTunneling(newFilePath); } return 0; } private bool DeleteOldArchiveFiles(string newFilePath, bool initialFileOpen) { try { if (initialFileOpen && _fileTarget.DeleteOldFileOnStartup && Path.GetFileNameWithoutExtension(newFilePath).Any((char chr) => char.IsDigit(chr))) { return DeleteOldFilesBeforeArchive(newFilePath, initialFileOpen, parseArchiveSequenceNo: false); } if (File.Exists(newFilePath)) { string archiveCleanupReason = ((_fileTarget.MaxArchiveFiles < 0 && _fileTarget.ArchiveOldFileOnStartup) ? "ArchiveOldFileOnStartup=true" : $"MaxArchiveFiles={_fileTarget.MaxArchiveFiles}"); return DeleteOldArchiveFile(newFilePath, archiveCleanupReason); } } catch (Exception ex) { InternalLogger.Debug(ex, "{0}: Failed to archive file: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, newFilePath })); if (ex.MustBeRethrown(_fileTarget)) { throw; } } return false; } } } namespace NLog.Targets.FileAppenders { internal sealed class DiscardAllFileAppender : IFileAppender, IDisposable { public string FilePath { get; } public DateTime OpenStreamTime { get; } public DateTime LastWriteTime => OpenStreamTime; public DateTime FileLastModified => OpenStreamTime; public DateTime NextArchiveTime => DateTime.MaxValue; public long FileSize => 0L; public DiscardAllFileAppender(string filePath) { FilePath = filePath; OpenStreamTime = TimeSource.Current.Time; } public void Write(DateTime timestamp, byte[] buffer, int offset, int count) { } public void Flush() { } public void Dispose() { } public bool VerifyFileExists() { return true; } public override string ToString() { return FilePath; } } internal sealed class ExclusiveFileLockingAppender : IFileAppender, IDisposable { private readonly FileTarget _fileTarget; private readonly string _filePath; private Stream _fileStream; private DateTime _lastFileDeletedCheck; private long? _countedFileSize; private DateTime? _fileBirthTime; private DateTime _nextArchiveTime; private DateTime _lastFileBirthTime; public string FilePath => _filePath; public DateTime OpenStreamTime { get; } public DateTime LastWriteTime => FileLastModified; public DateTime FileLastModified { get; private set; } private DateTime FileBirthTime { get { return _fileBirthTime ?? OpenStreamTime; } set { _fileBirthTime = value; } } public DateTime NextArchiveTime { get { DateTime fileBirthTime = FileBirthTime; if (_lastFileBirthTime != fileBirthTime) { _nextArchiveTime = FileTarget.CalculateNextArchiveEventTime(_fileTarget.ArchiveEvery, fileBirthTime); _lastFileBirthTime = fileBirthTime; } return _nextArchiveTime; } } public long FileSize => _countedFileSize ?? _fileStream.Length; public ExclusiveFileLockingAppender(FileTarget fileTarget, string filePath) { _fileTarget = fileTarget; _filePath = filePath; OpenStreamTime = TimeSource.Current.Time; _lastFileDeletedCheck = OpenStreamTime; long fileInfoSize = RefreshFileBirthTimeUtc(forceRefresh: true); _fileStream = _fileTarget.CreateFileStreamWithRetry(this, fileTarget.BufferSize, initialFileOpen: true); _countedFileSize = RefreshCountedFileSize(_fileStream, fileInfoSize); } private long RefreshFileBirthTimeUtc(bool forceRefresh) { FileLastModified = TimeSource.Current.Time; if (_fileTarget.ArchiveEvery == FileArchivePeriod.None && _fileTarget.ArchiveAboveSize <= 0 && _fileTarget.ArchiveFileName == null) { return 0L; } try { FileInfo fileInfo = new FileInfo(_filePath); long num = (fileInfo.Exists ? fileInfo.Length : 0); if (num > 0) { DateTime systemTime = fileInfo.LookupValidFileCreationTimeUtc(); DateTime fileBirthTime = ((systemTime.Year > 1980) ? TimeSource.Current.FromSystemTime(systemTime) : OpenStreamTime); if (!forceRefresh && fileBirthTime.Date < FileBirthTime.Date) { fileBirthTime = FileBirthTime; } FileBirthTime = fileBirthTime; FileLastModified = TimeSource.Current.FromSystemTime(fileInfo.LastWriteTimeUtc); } return num; } catch (Exception ex) { InternalLogger.Debug(ex, "{0}: Failed to refresh BirthTime for file: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, _filePath })); return 0L; } } public void Write(DateTime timestamp, byte[] buffer, int offset, int count) { long num = timestamp.Ticks - _lastFileDeletedCheck.Ticks; if (num > 10000000 || num < -10000000) { MonitorFileHasBeenDeleted(); } _fileStream.Write(buffer, offset, count); if (_countedFileSize.HasValue) { _countedFileSize += count; } } public void Flush() { _fileStream.Flush(); } public void Dispose() { SafeCloseFile(_filePath, _fileStream); } public bool VerifyFileExists() { return SafeFileExists(_filePath); } private void MonitorFileHasBeenDeleted() { DateTime lastFileDeletedCheck = (FileLastModified = TimeSource.Current.Time); long num = lastFileDeletedCheck.Ticks - _lastFileDeletedCheck.Ticks; if (num > 10000000 || num < -10000000) { _lastFileDeletedCheck = lastFileDeletedCheck; if (!SafeFileExists(_filePath)) { InternalLogger.Debug("{0}: Recreating FileStream because no longer File.Exists: '{1}'", _fileTarget, _filePath); SafeCloseFile(_filePath, _fileStream); _fileStream = _fileTarget.CreateFileStreamWithRetry(this, _fileTarget.BufferSize, initialFileOpen: false); long fileInfoSize = RefreshFileBirthTimeUtc(forceRefresh: false); _countedFileSize = RefreshCountedFileSize(_fileStream, fileInfoSize); } } } private long? RefreshCountedFileSize(Stream fileStream, long fileInfoSize) { if (_fileTarget.ArchiveAboveSize > 0) { if (_fileTarget.GetType().Equals(typeof(FileTarget))) { return fileStream.Length; } if (fileStream.GetType().Equals(typeof(FileStream))) { return null; } return fileInfoSize; } return null; } private void SafeCloseFile(string filepath, Stream? fileStream) { try { fileStream?.Dispose(); } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to close file: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, filepath })); } } private bool SafeFileExists(string filepath) { try { return File.Exists(filepath); } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to check if File.Exists: '{1}'", new ReadOnlySpan(new object[2] { _fileTarget, filepath })); return false; } } public override string ToString() { return _filePath; } } internal interface IFileAppender : IDisposable { string FilePath { get; } long FileSize { get; } DateTime OpenStreamTime { get; } DateTime LastWriteTime { get; } DateTime FileLastModified { get; } DateTime NextArchiveTime { get; } void Write(DateTime timestamp, byte[] buffer, int offset, int count); void Flush(); bool VerifyFileExists(); } internal sealed class MinimalFileLockingAppender : IFileAppender, IDisposable { private readonly FileTarget _fileTarget; private readonly string _filePath; private bool _initialFileOpen; private DateTime _nextArchiveTime; private DateTime _lastFileBirthTimeUtc; public string FilePath => _filePath; public DateTime OpenStreamTime { get; } public DateTime LastWriteTime { get; private set; } public DateTime FileLastModified { get { try { FileInfo fileInfo = new FileInfo(_filePath); if (fileInfo.Exists && fileInfo.Length != 0L) { return TimeSource.Current.FromSystemTime(fileInfo.LastWriteTimeUtc); } return OpenStreamTime; } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to lookup FileInfo.LastWriteTimeUtc for file: {1}", new ReadOnlySpan(new object[2] { _fileTarget, _filePath })); if (ex.MustBeRethrown()) { throw; } return OpenStreamTime; } } } public DateTime NextArchiveTime { get { if (_nextArchiveTime < TimeSource.Current.Time.AddMinutes(1.0) || _lastFileBirthTimeUtc == DateTime.MinValue) { FileInfo fileInfo = new FileInfo(_filePath); DateTime dateTime = ((fileInfo.Exists && fileInfo.Length != 0L) ? fileInfo.LookupValidFileCreationTimeUtc() : DateTime.MinValue); if (dateTime == DateTime.MinValue || _lastFileBirthTimeUtc < dateTime) { DateTime fileBirthTime = ((dateTime.Year > 1980) ? TimeSource.Current.FromSystemTime(dateTime) : OpenStreamTime); _nextArchiveTime = FileTarget.CalculateNextArchiveEventTime(_fileTarget.ArchiveEvery, fileBirthTime); _lastFileBirthTimeUtc = dateTime; } } return _nextArchiveTime; } } public long FileSize { get { try { FileInfo fileInfo = new FileInfo(_filePath); return fileInfo.Exists ? fileInfo.Length : 0; } catch (Exception ex) { InternalLogger.Error(ex, "{0}: Failed to lookup FileInfo.Length for file: {1}", new ReadOnlySpan(new object[2] { _fileTarget, _filePath })); if (ex.MustBeRethrown()) { throw; } return 0L; } } } public MinimalFileLockingAppender(FileTarget fileTarget, string filePath) { _fileTarget = fileTarget; _filePath = filePath; _initialFileOpen = true; OpenStreamTime = (LastWriteTime = TimeSource.Current.Time); } public void Write(DateTime timestamp, byte[] buffer, int offset, int count) { int bufferSize = Math.Min((count / 4096 + 1) * 4096, _fileTarget.BufferSize); bool initialFileOpen = _initialFileOpen; _initialFileOpen = false; using (Stream stream = _fileTarget.CreateFileStreamWithRetry(this, bufferSize, initialFileOpen)) { stream.Write(buffer, offset, count); if (_fileTarget.ReplaceFileContentsOnEachWrite) { byte[] footerLayoutBytes = _fileTarget.GetFooterLayoutBytes(); if (footerLayoutBytes != null && footerLayoutBytes.Length != 0) { stream.Write(footerLayoutBytes, 0, footerLayoutBytes.Length); } } } LastWriteTime = TimeSource.Current.Time; } public void Dispose() { } public void Flush() { } public bool VerifyFileExists() { return FileSize != 0; } public override string ToString() { return _filePath; } } } namespace NLog.MessageTemplates { public enum CaptureType : byte { Unknown, Normal, Serialize, Stringify } internal readonly struct Hole { public readonly string Name; public readonly string? Format; public readonly CaptureType CaptureType; public readonly short Index; public readonly short Alignment; public Hole(string name, string? format, CaptureType captureType, short parameterIndex, short alignment) { Name = name; Format = format; CaptureType = captureType; Index = parameterIndex; Alignment = alignment; } } internal readonly struct Literal { public readonly int Print; public readonly int Skip; public Literal(int print, int skip) { Print = print; Skip = skip; } } internal readonly struct LiteralHole { public readonly Literal Literal; public readonly Hole Hole; public bool MaybePositionalTemplate { get { if (Literal.Skip != 0 && Hole.Index != -1) { return Hole.CaptureType == CaptureType.Normal; } return false; } } public LiteralHole(in Literal literal, in Hole hole) { Literal = literal; Hole = hole; } } public readonly struct MessageTemplateParameter { public string Name { get; } public object? Value { get; } public string? Format { get; } public CaptureType CaptureType { get; } public int? PositionalIndex { get { switch (Name) { case "0": return 0; case "1": return 1; case "2": return 2; case "3": return 3; case "4": return 4; case "5": return 5; case "6": return 6; case "7": return 7; case "8": return 8; case "9": return 9; default: { string name = Name; if (name != null && name.Length >= 1 && Name[0] >= '0' && Name[0] <= '9' && int.TryParse(Name, out var result)) { return result; } return null; } } } } internal MessageTemplateParameter(string name, object? value, string? format) { Name = Guard.ThrowIfNull(name, "name"); Value = value; Format = format; CaptureType = CaptureType.Normal; } public MessageTemplateParameter(string name, object? value, string? format, CaptureType captureType) { Name = Guard.ThrowIfNull(name, "name"); Value = value; Format = format; CaptureType = captureType; } } public sealed class MessageTemplateParameters : IEnumerable, IEnumerable { internal static readonly MessageTemplateParameters Empty = new MessageTemplateParameters(string.Empty, ArrayHelper.Empty()); private readonly IList _parameters; public MessageTemplateParameter this[int index] => _parameters[index]; public int Count => _parameters.Count; public bool IsPositional { get; } internal bool IsValidTemplate { get; } public IEnumerator GetEnumerator() { return _parameters.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _parameters.GetEnumerator(); } internal MessageTemplateParameters(string message, object?[] parameters) { if (parameters == null || parameters.Length == 0) { _parameters = ArrayHelper.Empty(); IsValidTemplate = true; } else { _parameters = ParseMessageTemplate(message, parameters, out var isPositional, out var isValidTemplate); IsPositional = isPositional; IsValidTemplate = isValidTemplate; } } internal MessageTemplateParameters(IList templateParameters) { _parameters = templateParameters ?? ArrayHelper.Empty(); IsValidTemplate = true; } private static List ParseMessageTemplate(string template, object?[] parameters, out bool isPositional, out bool isValidTemplate) { isPositional = true; isValidTemplate = true; List list = new List(parameters.Length); try { short num = 0; TemplateEnumerator templateEnumerator = new TemplateEnumerator(template); while (templateEnumerator.MoveNext()) { if (templateEnumerator.Current.Literal.Skip == 0) { continue; } Hole hole = templateEnumerator.Current.Hole; if ((hole.Index != -1) & isPositional) { num = GetMaxHoleIndex(num, hole.Index); object holeValueSafe = GetHoleValueSafe(parameters, hole.Index, ref isValidTemplate); list.Add(new MessageTemplateParameter(hole.Name, holeValueSafe, hole.Format, hole.CaptureType)); continue; } if (isPositional) { isPositional = false; if (num != 0) { templateEnumerator = new TemplateEnumerator(template); num = 0; list.Clear(); continue; } } object holeValueSafe2 = GetHoleValueSafe(parameters, num, ref isValidTemplate); list.Add(new MessageTemplateParameter(hole.Name, holeValueSafe2, hole.Format, hole.CaptureType)); num++; } if (isPositional) { if (list.Count < parameters.Length || num != parameters.Length) { isValidTemplate = false; } } else if (list.Count != parameters.Length) { isValidTemplate = false; } return list; } catch (Exception ex) { isValidTemplate = false; InternalLogger.Warn(ex, "Error when parsing a message."); return list; } } private static short GetMaxHoleIndex(short maxHoleIndex, short holeIndex) { if (maxHoleIndex == 0) { maxHoleIndex++; } if (maxHoleIndex <= holeIndex) { maxHoleIndex = holeIndex; maxHoleIndex++; } return maxHoleIndex; } private static object? GetHoleValueSafe(object?[] parameters, short holeIndex, ref bool isValidTemplate) { if (parameters.Length > holeIndex) { return parameters[holeIndex]; } isValidTemplate = false; return null; } } internal struct TemplateEnumerator : IEnumerator, IEnumerator, IDisposable { private static readonly char[] HoleDelimiters = new char[3] { '}', ':', ',' }; private static readonly char[] TextDelimiters = new char[2] { '{', '}' }; private string _template; private int _length; private int _position; private int _literalLength; private LiteralHole _current; private const short Zero = 0; public string Template => _template; public LiteralHole Current => _current; object IEnumerator.Current => _current; public TemplateEnumerator(string template) { _template = Guard.ThrowIfNull(template, "template"); _length = _template.Length; _position = 0; _literalLength = 0; _current = default(LiteralHole); } public void Dispose() { _template = string.Empty; _length = 0; Reset(); } public void Reset() { _position = 0; _literalLength = 0; _current = default(LiteralHole); } public bool MoveNext() { try { while (_position < _length) { switch (Peek()) { case '{': ParseOpenBracketPart(); return true; case '}': ParseCloseBracketPart(); return true; } ParseTextPart(); } if (_literalLength != 0) { AddLiteral(); return true; } return false; } catch (IndexOutOfRangeException) { throw new TemplateParserException("Unexpected end of template.", _position, _template); } } private void AddLiteral() { Literal literal = new Literal(_literalLength, 0); Hole hole = default(Hole); _current = new LiteralHole(in literal, in hole); _literalLength = 0; } private void ParseTextPart() { _literalLength = SkipUntil(TextDelimiters, required: false); } private void ParseOpenBracketPart() { Skip('{'); switch (Peek()) { case '{': Skip('{'); _literalLength++; AddLiteral(); break; case '@': Skip('@'); ParseHole(CaptureType.Serialize); break; case '$': Skip('$'); ParseHole(CaptureType.Stringify); break; default: ParseHole(CaptureType.Normal); break; } } private void ParseCloseBracketPart() { Skip('}'); if (Read() != '}') { throw new TemplateParserException("Unexpected '}}' ", _position - 2, _template); } _literalLength++; AddLiteral(); } private void ParseHole(CaptureType type) { int position = _position; int parameterIndex; string name = ParseName(out parameterIndex); int num = 0; string format = null; if (Peek() != '}') { num = ((Peek() == ',') ? ParseAlignment() : 0); format = ((Peek() == ':') ? ParseFormat() : null); Skip('}'); } else { _position++; } int skip = _position - position + ((type == CaptureType.Normal) ? 1 : 2); Literal literal = new Literal(_literalLength, skip); Hole hole = new Hole(name, format, type, (short)parameterIndex, (short)num); _current = new LiteralHole(in literal, in hole); _literalLength = 0; } private string ParseName(out int parameterIndex) { parameterIndex = -1; char c = Peek(); if (c >= '0' && c <= '9') { int position = _position; int num = ReadInt(); switch (Peek()) { case ',': case ':': case '}': parameterIndex = num; return ParameterIndexToString(parameterIndex); case ' ': SkipSpaces(); c = Peek(); if (c == '}' || c == ':' || c == ',') { parameterIndex = num; } break; } _position = position; } return ReadUntil(HoleDelimiters); } private static string ParameterIndexToString(int parameterIndex) { return parameterIndex switch { 0 => "0", 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8 => "8", 9 => "9", _ => parameterIndex.ToString(CultureInfo.InvariantCulture), }; } private string ParseFormat() { Skip(':'); string text = ReadUntil(TextDelimiters); while (true) { switch (Read()) { case '}': if (_position < _length && Peek() == '}') { Skip('}'); text += "}"; break; } _position--; return text; case '{': { char c = Peek(); if (c == '{') { Skip('{'); text += "{"; break; } throw new TemplateParserException($"Expected '{{' but found '{c}' instead in format.", _position, _template); } } text += ReadUntil(TextDelimiters); } } private int ParseAlignment() { Skip(','); SkipSpaces(); int result = ReadInt(); SkipSpaces(); char c = Peek(); if (c != ':' && c != '}') { throw new TemplateParserException($"Expected ':' or '}}' but found '{c}' instead.", _position, _template); } return result; } private char Peek() { return _template[_position]; } private char Read() { return _template[_position++]; } private void Skip(char c) { _position++; } private void SkipSpaces() { while (_template[_position] == ' ') { _position++; } } private int SkipUntil(char[] search, bool required = true) { int position = _position; int num = _template.IndexOfAny(search, _position); if (num == -1 && required) { string text = string.Join(", ", search.Select((char c) => "'" + c + "'").ToArray()); throw new TemplateParserException("Reached end of template while expecting one of " + text + ".", _position, _template); } _position = ((num == -1) ? _length : num); return _position - position; } private int ReadInt() { bool flag = false; int num = 0; for (int i = 0; i < 12; i++) { char c = Peek(); if (c < '0' || c > '9') { if (i > 0 && !flag) { return num; } if (i > 1 && flag) { return -num; } if (i != 0 || c != '-') { break; } flag = true; _position++; } else { _position++; num = num * 10 + (c - 48); } } throw new TemplateParserException("An integer is expected", _position, _template); } private string ReadUntil(char[] search, bool required = true) { int position = _position; return _template.Substring(position, SkipUntil(search, required)); } } public class TemplateParserException : Exception { public int Index { get; } public string Template { get; } public TemplateParserException(string message, int index, string template) : base(message) { Index = index; Template = template; } } internal sealed class ValueFormatter : IValueFormatter { private sealed class JsonConverterWithSpaces : IJsonConverter { private readonly DefaultJsonSerializer _serializer; private readonly JsonSerializeOptions _serializerOptions; private readonly JsonSerializeOptions _exceptionSerializerOptions; public static IJsonConverter CreateJsonConverter(IJsonConverter jsonConverter) { if (jsonConverter is DefaultJsonSerializer jsonConverter2) { return new JsonConverterWithSpaces(jsonConverter2); } return jsonConverter; } private JsonConverterWithSpaces(DefaultJsonSerializer jsonConverter) { _serializer = jsonConverter; _serializerOptions = new JsonSerializeOptions { SuppressSpaces = false }; _exceptionSerializerOptions = new JsonSerializeOptions { SuppressSpaces = false, SanitizeDictionaryKeys = true }; } public bool SerializeObject(object? value, StringBuilder builder) { if (value is Exception) { return _serializer.SerializeObject(value, builder, _exceptionSerializerOptions); } return _serializer.SerializeObject(value, builder, _serializerOptions); } } private readonly MruCache _enumCache = new MruCache(2000); private readonly IServiceProvider _serviceProvider; private readonly bool _legacyStringQuotes; private IJsonConverter? _jsonConverter; private const int MaxRecursionDepth = 2; private const int MaxValueLength = 524288; private const string LiteralFormatSymbol = "l"; public const string FormatAsJson = "@"; public const string FormatAsString = "$"; private IJsonConverter JsonConverter => _jsonConverter ?? (_jsonConverter = JsonConverterWithSpaces.CreateJsonConverter(_serviceProvider.GetService())); public ValueFormatter(IServiceProvider serviceProvider, bool legacyStringQuotes) { _serviceProvider = serviceProvider; _legacyStringQuotes = legacyStringQuotes; } public bool FormatValue(object? value, string? format, CaptureType captureType, IFormatProvider? formatProvider, StringBuilder builder) { int num; switch (captureType) { case CaptureType.Serialize: return JsonConverter.SerializeObject(value, builder); case CaptureType.Stringify: if (_legacyStringQuotes) { if (builder.Length != 0) { num = ((builder[builder.Length - 1] != '"') ? 1 : 0); if (num == 0) { goto IL_0054; } } else { num = 1; } builder.Append('"'); } else { num = 0; } goto IL_0054; default: { return FormatObject(value, format, formatProvider, builder); } IL_0054: FormatToString(value, format, formatProvider, builder); if (num != 0) { builder.Append('"'); } return true; } } public bool FormatObject(object? value, string? format, IFormatProvider? formatProvider, StringBuilder builder) { if (SerializeSimpleObject(value, format, formatProvider, builder)) { return true; } if (value is IEnumerable collection) { return SerializeWithoutCyclicLoop(collection, format, formatProvider, builder, default(SingleItemOptimizedHashSet), 0); } SerializeConvertToString(value, formatProvider, builder); return true; } private bool SerializeSimpleObject(object? value, string? format, IFormatProvider? formatProvider, StringBuilder builder) { if (value is string stringValue) { SerializeStringObject(stringValue, format, builder); return true; } if (value is IConvertible value2) { SerializeConvertibleObject(value2, format, formatProvider, builder); return true; } if (value is IFormattable formattable) { if (string.IsNullOrEmpty(format)) { builder.AppendFormat(formatProvider, "{0}", formattable); } else { builder.Append(formattable.ToString(format, formatProvider)); } return true; } if (value == null) { builder.Append("NULL"); return true; } return false; } private void SerializeConvertibleObject(IConvertible value, string? format, IFormatProvider? formatProvider, StringBuilder builder) { TypeCode typeCode = value.GetTypeCode(); if (typeCode == TypeCode.String) { SerializeStringObject(value.ToString(), format, builder); return; } if (!string.IsNullOrEmpty(format) && value is IFormattable formattable) { builder.Append(formattable.ToString(format, formatProvider)); return; } switch (typeCode) { case TypeCode.Boolean: builder.Append(value.ToBoolean(CultureInfo.InvariantCulture) ? "true" : "false"); break; case TypeCode.Char: { int num; if (_legacyStringQuotes) { num = ((format != "l") ? 1 : 0); if (num != 0) { builder.Append('"'); } } else { num = 0; } builder.Append(value.ToChar(CultureInfo.InvariantCulture)); if (num != 0) { builder.Append('"'); } break; } case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (value is Enum value2) { AppendEnumAsString(builder, value2); } else { builder.AppendNumericInvariant(value, typeCode); } break; default: SerializeConvertToString(value, formatProvider, builder); break; } } private static void SerializeConvertToString(object? value, IFormatProvider? formatProvider, StringBuilder builder) { if (value is IFormattable) { builder.AppendFormat(formatProvider, "{0}", value); } else { builder.Append(Convert.ToString(value, formatProvider)); } } private void SerializeStringObject(string? stringValue, string? format, StringBuilder builder) { int num; if (_legacyStringQuotes) { num = ((format != "l") ? 1 : 0); if (num != 0) { builder.Append('"'); } } else { num = 0; } builder.Append(stringValue); if (num != 0) { builder.Append('"'); } } private void AppendEnumAsString(StringBuilder sb, Enum value) { if (!_enumCache.TryGetValue(value, out string value2)) { value2 = value.ToString(); _enumCache.TryAddValue(value, value2); } sb.Append(value2); } private bool SerializeWithoutCyclicLoop(IEnumerable collection, string? format, IFormatProvider? formatProvider, StringBuilder builder, SingleItemOptimizedHashSet objectsInPath, int depth) { if (objectsInPath.Contains(collection)) { return false; } if (depth > 2) { return false; } if (collection is IDictionary dictionary) { using (new SingleItemOptimizedHashSet.SingleItemScopedInsert(dictionary, ref objectsInPath, forceHashSet: true)) { return SerializeDictionaryObject(dictionary, format, formatProvider, builder, objectsInPath, depth); } } using (new SingleItemOptimizedHashSet.SingleItemScopedInsert(collection, ref objectsInPath, forceHashSet: true)) { return SerializeCollectionObject(collection, format, formatProvider, builder, objectsInPath, depth); } } private bool SerializeDictionaryObject(IDictionary dictionary, string? format, IFormatProvider? formatProvider, StringBuilder builder, SingleItemOptimizedHashSet objectsInPath, int depth) { bool flag = false; foreach (DictionaryEntry item in new DictionaryEntryEnumerable(dictionary)) { if (builder.Length > 524288) { return false; } if (flag) { builder.Append(", "); } SerializeCollectionItem(item.Key, format, formatProvider, builder, ref objectsInPath, depth); builder.Append('='); SerializeCollectionItem(item.Value, format, formatProvider, builder, ref objectsInPath, depth); flag = true; } return true; } private bool SerializeCollectionObject(IEnumerable collection, string? format, IFormatProvider? formatProvider, StringBuilder builder, SingleItemOptimizedHashSet objectsInPath, int depth) { bool flag = false; foreach (object item in collection) { if (builder.Length > 524288) { return false; } if (flag) { builder.Append(", "); } SerializeCollectionItem(item, format, formatProvider, builder, ref objectsInPath, depth); flag = true; } return true; } private void SerializeCollectionItem(object? item, string? format, IFormatProvider? formatProvider, StringBuilder builder, ref SingleItemOptimizedHashSet objectsInPath, int depth) { if (item is IConvertible value) { SerializeConvertibleObject(value, format, formatProvider, builder); } else if (item is IEnumerable collection) { SerializeWithoutCyclicLoop(collection, format, formatProvider, builder, objectsInPath, depth + 1); } else if (!SerializeSimpleObject(item, format, formatProvider, builder)) { SerializeConvertToString(item, formatProvider, builder); } } public static void FormatToString(object? value, string? format, IFormatProvider? formatProvider, StringBuilder builder) { if (value is string value2) { builder.Append(value2); } else if (value is IFormattable formattable) { if (string.IsNullOrEmpty(format)) { builder.AppendFormat(formatProvider, "{0}", formattable); } else { builder.Append(formattable.ToString(format, formatProvider)); } } else { builder.Append(Convert.ToString(value, formatProvider)); } } } } namespace NLog.Attributes { public class LogLevelTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { if (!(sourceType == typeof(string)) && !IsNumericType(sourceType)) { return base.CanConvertFrom(context, sourceType); } return true; } public override object? ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { Type type = value?.GetType(); if (typeof(string).Equals(type)) { return LogLevel.FromString(value?.ToString() ?? string.Empty); } if (IsNumericType(type)) { return LogLevel.FromOrdinal(Convert.ToInt32(value, CultureInfo.InvariantCulture)); } return base.ConvertFrom(context, culture, value); } public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) { if (!(destinationType == typeof(string)) && !IsNumericType(destinationType)) { return base.CanConvertTo(context, destinationType); } return true; } public override object? ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (value is LogLevel logLevel) { if (destinationType == typeof(string)) { return logLevel.ToString(); } if (IsNumericType(destinationType)) { return Convert.ChangeType(logLevel.Ordinal, destinationType, culture); } } return base.ConvertTo(context, culture, value, destinationType); } private static bool IsNumericType(Type? sourceType) { if ((object)sourceType == null) { return false; } if (typeof(int).Equals(sourceType)) { return true; } if (typeof(uint).Equals(sourceType)) { return true; } if (typeof(long).Equals(sourceType)) { return true; } if (typeof(ulong).Equals(sourceType)) { return true; } if (typeof(short).Equals(sourceType)) { return true; } if (typeof(ushort).Equals(sourceType)) { return true; } return false; } } } namespace NLog.Layouts { [Layout("CompoundLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class CompoundLayout : Layout { private Layout[]? _precalculateLayouts; private readonly List _layouts = new List(); [ArrayParameter(typeof(Layout), "layout")] public IList Layouts => _layouts; protected override void InitializeLayout() { foreach (Layout layout in _layouts) { layout.Initialize(base.LoggingConfiguration); } base.InitializeLayout(); _precalculateLayouts = ResolveLayoutPrecalculation(_layouts); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { foreach (Layout layout in _layouts) { layout.Render(logEvent, target); } } protected override void CloseLayout() { _precalculateLayouts = null; foreach (Layout layout in _layouts) { layout.Close(); } base.CloseLayout(); } public override string ToString() { return ToStringWithNestedItems(_layouts, (Layout l) => l.ToString()); } } [NLogConfigurationItem] public class CsvColumn { private Layout _layout; internal CsvQuotingMode? _quoting; public string Name { get; set; } public Layout Layout { get { return _layout; } set { _layout = value; SimpleStringValue = ((Quoting != CsvQuotingMode.Nothing) ? ResolveStringValueMethod(_layout) : null); } } internal INoAllocationStringValueRenderer? SimpleStringValue { get; private set; } public CsvQuotingMode Quoting { get { return _quoting.GetValueOrDefault(CsvQuotingMode.Auto); } set { if (_quoting != value) { _quoting = value; SimpleStringValue = ((value != CsvQuotingMode.Nothing) ? ResolveStringValueMethod(_layout) : null); } } } public CsvColumn() : this(string.Empty, NLog.Layouts.Layout.Empty) { } public CsvColumn(string name, Layout layout) { Name = name; _layout = (Layout = layout); } private static INoAllocationStringValueRenderer? ResolveStringValueMethod(Layout layout) { INoAllocationStringValueRenderer noAllocationStringValueRenderer = ((layout is SimpleLayout simpleLayout && simpleLayout.LayoutRenderers.Count() == 1) ? (simpleLayout.LayoutRenderers.First() as INoAllocationStringValueRenderer) : null); if (noAllocationStringValueRenderer != null) { if (noAllocationStringValueRenderer.GetFormattedStringNoAllocation(LogEventInfo.CreateNullEvent()) != null) { return noAllocationStringValueRenderer; } return null; } return noAllocationStringValueRenderer; } } public enum CsvColumnDelimiterMode { Auto, Comma, Semicolon, Tab, Pipe, Space, Custom } [Layout("CsvLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public class CsvLayout : LayoutWithHeaderAndFooter { [ThreadAgnostic] [AppDomainFixedOutput] internal sealed class CsvHeaderLayout : Layout { private readonly CsvLayout _parent; private string? _headerOutput; public CsvHeaderLayout(CsvLayout parent) { _parent = parent; } protected override void InitializeLayout() { _headerOutput = null; base.InitializeLayout(); } private string GetHeaderOutput() { return _headerOutput ?? (_headerOutput = BuilderHeaderOutput()); } private string BuilderHeaderOutput() { StringBuilder stringBuilder = new StringBuilder(); _parent.RenderHeader(stringBuilder); return stringBuilder.ToString(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { } protected override string GetFormattedMessage(LogEventInfo logEvent) { return GetHeaderOutput(); } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { target.Append(GetHeaderOutput()); } } private string _actualColumnDelimiter; private string _doubleQuoteChar; private char[] _quotableCharacters; private Layout[]? _precalculateLayouts; private readonly List _columns = new List(); [ArrayParameter(typeof(CsvColumn), "column")] public IList Columns => _columns; public bool WithHeader { get; set; } = true; public CsvColumnDelimiterMode Delimiter { get; set; } public CsvQuotingMode Quoting { get; set; } = CsvQuotingMode.Auto; public string QuoteChar { get; set; } = "\""; public string CustomColumnDelimiter { get; set; } = string.Empty; public CsvLayout() { base.Layout = this; base.Header = new CsvHeaderLayout(this); base.Footer = null; ResolveQuoteChars(QuoteChar, out _actualColumnDelimiter, out _doubleQuoteChar, out _quotableCharacters); } protected override void InitializeLayout() { if (!WithHeader) { base.Header = null; } base.InitializeLayout(); ResolveQuoteChars(QuoteChar, out _actualColumnDelimiter, out _doubleQuoteChar, out _quotableCharacters); _precalculateLayouts = ResolveLayoutPrecalculation(_columns.Select((CsvColumn cln) => cln.Layout)); foreach (CsvColumn column in _columns) { if (string.IsNullOrEmpty(column.Name)) { throw new NLogConfigurationException("CsvLayout: Contains invalid CsvColumn with unassigned Name-property"); } } } private void ResolveQuoteChars(string quoteChar, out string actualColumnDelimiter, out string doubleQuoteChar, out char[] quotableCharacters) { actualColumnDelimiter = ResolveColumnDelimiter(Delimiter); quotableCharacters = (quoteChar + "\r\n" + actualColumnDelimiter).ToCharArray(); doubleQuoteChar = quoteChar + quoteChar; } private string ResolveColumnDelimiter(CsvColumnDelimiterMode delimiter) { switch (delimiter) { case CsvColumnDelimiterMode.Auto: return CultureInfo.CurrentCulture.TextInfo.ListSeparator; case CsvColumnDelimiterMode.Comma: return ","; case CsvColumnDelimiterMode.Semicolon: return ";"; case CsvColumnDelimiterMode.Pipe: return "|"; case CsvColumnDelimiterMode.Tab: return "\t"; case CsvColumnDelimiterMode.Space: return " "; case CsvColumnDelimiterMode.Custom: if (!string.IsNullOrEmpty(CustomColumnDelimiter)) { return CustomColumnDelimiter; } return ";"; default: return ";"; } } protected override void CloseLayout() { _precalculateLayouts = null; base.CloseLayout(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { bool initialColumn = true; foreach (CsvColumn column in _columns) { RenderColumnLayout(logEvent, column.Layout, column.SimpleStringValue, column._quoting ?? Quoting, target, initialColumn); initialColumn = false; } } private void RenderColumnLayout(LogEventInfo logEvent, Layout columnLayout, INoAllocationStringValueRenderer? stringValueRenderer, CsvQuotingMode quoting, StringBuilder target, bool initialColumn) { if (!initialColumn) { target.Append(_actualColumnDelimiter); } if (quoting == CsvQuotingMode.All) { target.Append(QuoteChar); } if (stringValueRenderer != null && quoting != CsvQuotingMode.Nothing) { string formattedStringNoAllocation = stringValueRenderer.GetFormattedStringNoAllocation(logEvent); if (formattedStringNoAllocation != null) { AppendStringValue(formattedStringNoAllocation, quoting, target); return; } } int length = target.Length; columnLayout.Render(logEvent, target); if (length != target.Length && ColumnValueRequiresQuotes(quoting, target, length)) { string columnValue = target.ToString(length, target.Length - length); target.Length = length; AppendQuotedStringValue(columnValue, quoting, target); } else if (quoting == CsvQuotingMode.All) { target.Append(QuoteChar); } } private void AppendStringValue(string columnValue, CsvQuotingMode quoting, StringBuilder target) { if (((quoting == CsvQuotingMode.All) ? columnValue.IndexOf(QuoteChar) : columnValue.IndexOfAny(_quotableCharacters)) >= 0) { AppendQuotedStringValue(columnValue, quoting, target); return; } target.Append(columnValue); if (quoting == CsvQuotingMode.All) { target.Append(QuoteChar); } } private void AppendQuotedStringValue(string columnValue, CsvQuotingMode quoting, StringBuilder target) { if (quoting != 0) { target.Append(QuoteChar); } target.Append(columnValue.Replace(QuoteChar, _doubleQuoteChar)); target.Append(QuoteChar); } private void RenderHeader(StringBuilder sb) { LogEventInfo logEvent = LogEventInfo.CreateNullEvent(); bool initialColumn = true; foreach (CsvColumn column in _columns) { Layout layout = NLog.Layouts.Layout.FromLiteral(column.Name); layout.Initialize(base.LoggingConfiguration); RenderColumnLayout(logEvent, layout, null, column._quoting ?? Quoting, sb, initialColumn); initialColumn = false; } } private bool ColumnValueRequiresQuotes(CsvQuotingMode quoting, StringBuilder sb, int startPosition) { switch (quoting) { case CsvQuotingMode.Nothing: return false; case CsvQuotingMode.All: if (QuoteChar.Length == 1) { return sb.IndexOf(QuoteChar[0], startPosition) >= 0; } return sb.IndexOfAny(_quotableCharacters, startPosition) >= 0; default: return sb.IndexOfAny(_quotableCharacters, startPosition) >= 0; } } public override string ToString() { return ToStringWithNestedItems(_columns, (CsvColumn c) => c.Name); } } public enum CsvQuotingMode { All, Nothing, Auto } [Layout("JsonArrayLayout")] [ThreadAgnostic] public class JsonArrayLayout : Layout { private Layout[]? _precalculateLayouts; private IJsonConverter? _jsonConverter; private readonly List _items = new List(); private IJsonConverter JsonConverter => _jsonConverter ?? (_jsonConverter = ResolveService()); [ArrayParameter(typeof(Layout), "item")] public IList Items => _items; public bool SuppressSpaces { get; set; } = true; public bool RenderEmptyObject { get; set; } = true; protected override void InitializeLayout() { base.InitializeLayout(); _precalculateLayouts = ResolveLayoutPrecalculation(_items); } protected override void CloseLayout() { _jsonConverter = null; _precalculateLayouts = null; base.CloseLayout(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { int length = target.Length; RenderJsonFormattedMessage(logEvent, target); if (target.Length == length && RenderEmptyObject) { target.Append(SuppressSpaces ? "[]" : "[ ]"); } } protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb) { int length = sb.Length; foreach (Layout item in _items) { int length2 = sb.Length; if (length2 == length) { sb.Append(SuppressSpaces ? "[" : "[ "); } else { sb.Append(SuppressSpaces ? "," : ", "); } if (!RenderLayoutJsonValue(logEvent, item, sb)) { sb.Length = length2; } } if (sb.Length != length) { sb.Append(SuppressSpaces ? "]" : " ]"); } } private bool RenderLayoutJsonValue(LogEventInfo logEvent, Layout layout, StringBuilder sb) { int length = sb.Length; object rawValue; if (layout is JsonLayout) { layout.Render(logEvent, sb); } else if (layout.TryGetRawValue(logEvent, out rawValue)) { if (!JsonConverter.SerializeObject(rawValue, sb)) { return false; } } else { sb.Append('"'); length = sb.Length; layout.Render(logEvent, sb); if (length != sb.Length) { DefaultJsonSerializer.PerformJsonEscapeWhenNeeded(sb, length, escapeUnicode: false); sb.Append('"'); } } return length != sb.Length; } public override string ToString() { return ToStringWithNestedItems(_items, (Layout l) => l.ToString()); } } [NLogConfigurationItem] public class JsonAttribute { private readonly ValueTypeLayoutInfo _layoutInfo = new ValueTypeLayoutInfo(); private string _name; private bool _includeEmptyValue; public string Name { get { return _name; } set { if (string.IsNullOrEmpty(value)) { _name = value; return; } if (value.All((char chr) => char.IsLetterOrDigit(chr))) { _name = value; return; } StringBuilder stringBuilder = new StringBuilder(); DefaultJsonSerializer.AppendStringEscape(stringBuilder, value.Trim(), escapeUnicode: false); _name = stringBuilder.ToString(); } } public Layout Layout { get { return _layoutInfo.Layout; } set { _layoutInfo.Layout = value; } } public Type? ValueType { get { return _layoutInfo.ValueType; } set { _layoutInfo.ValueType = value; } } public Layout? DefaultValue { get { return _layoutInfo.DefaultValue; } set { _layoutInfo.DefaultValue = value; } } public bool Encode { get; set; } public bool EscapeUnicode { get; set; } [Obsolete("Marked obsolete since forward slash are valid JSON. Marked obsolete with NLog v5.4")] [EditorBrowsable(EditorBrowsableState.Never)] public bool EscapeForwardSlash { get; set; } public bool IncludeEmptyValue { get { return _includeEmptyValue; } set { _includeEmptyValue = value; _layoutInfo.ForceDefaultValueNull = !value; } } public JsonAttribute() : this(string.Empty, NLog.Layouts.Layout.Empty, encode: true) { } public JsonAttribute(string name, Layout layout) : this(name, layout, encode: true) { } public JsonAttribute(string name, Layout layout, bool encode) { Name = name; _name = Name; Layout = layout; Encode = encode; } internal bool RenderAppendJsonValue(LogEventInfo logEvent, IJsonConverter jsonConverter, StringBuilder builder) { if (!Encode) { int length = builder.Length; return RenderAppendJsonValue(logEvent, builder, length); } INoAllocationStringValueRenderer simpleStringValue = _layoutInfo.SimpleStringValue; if (simpleStringValue != null) { string formattedStringNoAllocation = simpleStringValue.GetFormattedStringNoAllocation(logEvent); if (formattedStringNoAllocation != null) { return RenderAppendJsonStringValue(builder, formattedStringNoAllocation); } } if ((object)ValueType == null) { builder.Append('"'); int length2 = builder.Length; if (!RenderAppendJsonValue(logEvent, builder, length2)) { return false; } DefaultJsonSerializer.PerformJsonEscapeWhenNeeded(builder, length2, EscapeUnicode); builder.Append('"'); } else { object obj = _layoutInfo.RenderValue(logEvent); if (!IncludeEmptyValue && StringHelpers.IsNullOrEmptyString(obj)) { return false; } jsonConverter.SerializeObject(obj, builder); } return true; } private bool RenderAppendJsonStringValue(StringBuilder builder, string stringValue) { if (!IncludeEmptyValue && string.IsNullOrEmpty(stringValue)) { return false; } builder.Append('"'); DefaultJsonSerializer.AppendStringEscape(builder, stringValue, EscapeUnicode); builder.Append('"'); return true; } private bool RenderAppendJsonValue(LogEventInfo logEvent, StringBuilder builder, int valueStart) { Layout.Render(logEvent, builder); if (!IncludeEmptyValue) { return builder.Length > valueStart; } return true; } } [Layout("JsonLayout")] [ThreadAgnostic] public class JsonLayout : Layout { private sealed class LimitRecursionJsonConvert : IJsonConverter { private readonly IJsonConverter _converter; private readonly DefaultJsonSerializer? _serializer; private readonly JsonSerializeOptions _serializerOptions; public LimitRecursionJsonConvert(int maxRecursionLimit, bool suppressSpaces, IJsonConverter converter) { _converter = converter; _serializer = converter as DefaultJsonSerializer; _serializerOptions = new JsonSerializeOptions { MaxRecursionLimit = Math.Max(0, maxRecursionLimit), SuppressSpaces = suppressSpaces, SanitizeDictionaryKeys = true }; } public bool SerializeObject(object? value, StringBuilder builder) { if (_serializer != null) { return _serializer.SerializeObject(value, builder, _serializerOptions); } return _converter.SerializeObject(value, builder); } public bool SerializeObjectNoLimit(object? value, StringBuilder builder) { return _converter.SerializeObject(value, builder); } } private const int SpacesPerIndent = 2; private Layout[]? _precalculateLayouts; private LimitRecursionJsonConvert? _jsonConverter; private IValueFormatter? _valueFormatter; private ObjectReflectionCache? _objectReflectionCache; private readonly List _attributes = new List(); private bool _suppressSpaces = true; private bool? _renderEmptyObject; private bool _indentJson; private bool? _includeScopeProperties; private bool? _includeMdc; private bool? _includeMdlc; private string _beginJsonMessage = "{\""; private string _completeJsonMessage = "}"; private string _beginJsonPropertyName = ",\""; private string _completeJsonPropertyName = "\":"; private LimitRecursionJsonConvert JsonConverter => _jsonConverter ?? (_jsonConverter = new LimitRecursionJsonConvert(MaxRecursionLimit, SuppressSpaces, ResolveService())); private IValueFormatter ValueFormatter => _valueFormatter ?? (_valueFormatter = ResolveService()); private ObjectReflectionCache ObjectReflectionCache => _objectReflectionCache ?? (_objectReflectionCache = new ObjectReflectionCache(ResolveService())); [ArrayParameter(typeof(JsonAttribute), "attribute")] public IList Attributes => _attributes; public bool SuppressSpaces { get { return _suppressSpaces; } set { if (_suppressSpaces != value) { _suppressSpaces = value; RefreshJsonDelimiters(); } } } public bool RenderEmptyObject { get { return _renderEmptyObject.GetValueOrDefault(true); } set { _renderEmptyObject = value; } } public bool IndentJson { get { return _indentJson; } set { if (_indentJson != value) { _indentJson = value; if (_indentJson) { _suppressSpaces = false; } RefreshJsonDelimiters(); } } } public bool DottedRecursion { get; set; } public bool IncludeEventProperties { get; set; } public bool IncludeGdc { get; set; } public bool IncludeScopeProperties { get { bool? includeScopeProperties = _includeScopeProperties; if (!includeScopeProperties.HasValue) { if (!_includeMdlc.GetValueOrDefault()) { return _includeMdc.GetValueOrDefault(); } return true; } return includeScopeProperties.GetValueOrDefault(); } set { _includeScopeProperties = value; } } [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeAllProperties { get { return IncludeEventProperties; } set { IncludeEventProperties = value; } } [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdc { get { return _includeMdc.GetValueOrDefault(); } set { _includeMdc = value; } } [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdlc { get { return _includeMdlc.GetValueOrDefault(); } set { _includeMdlc = value; } } public bool ExcludeEmptyProperties { get; set; } public ISet ExcludeProperties { get; set; } public int MaxRecursionLimit { get; set; } = 1; [Obsolete("Marked obsolete with NLog 5.5. Should never escape forward slash")] [EditorBrowsable(EditorBrowsableState.Never)] public bool EscapeForwardSlash { get; set; } public JsonLayout() { ExcludeProperties = new HashSet(StringComparer.OrdinalIgnoreCase); } protected override void InitializeLayout() { base.InitializeLayout(); if (IncludeScopeProperties) { base.ThreadAgnostic = false; } if (IncludeEventProperties) { base.ThreadAgnosticImmutable = true; } _precalculateLayouts = ((IncludeScopeProperties || IncludeEventProperties) ? null : ResolveLayoutPrecalculation(Attributes.Select((JsonAttribute atr) => atr.Layout))); foreach (JsonAttribute attribute in _attributes) { if (string.IsNullOrEmpty(attribute.Name)) { throw new NLogConfigurationException("JsonLayout: Contains invalid JsonAttribute with unassigned Name-property"); } if (!attribute.Encode && attribute.Layout is JsonLayout jsonLayout) { if (!attribute.IncludeEmptyValue && !jsonLayout._renderEmptyObject.HasValue) { jsonLayout.RenderEmptyObject = false; } if (!SuppressSpaces || IndentJson) { jsonLayout.SuppressSpaces = false; } } } } protected override void CloseLayout() { _jsonConverter = null; _valueFormatter = null; _objectReflectionCache = null; _precalculateLayouts = null; base.CloseLayout(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { int length = target.Length; RenderJsonFormattedMessage(logEvent, target); if (target.Length == length && RenderEmptyObject) { target.Append(SuppressSpaces ? "{}" : "{ }"); } } protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb) { int length = sb.Length; foreach (JsonAttribute attribute in _attributes) { RenderAppendJsonPropertyValue(attribute, logEvent, sb, sb.Length == length); } if (IncludeGdc) { ICollection names = GlobalDiagnosticsContext.GetNames(); if (names.Count > 0) { foreach (string item in names) { if (!string.IsNullOrEmpty(item)) { object @object = GlobalDiagnosticsContext.GetObject(item); AppendJsonPropertyValue(item, @object, sb, sb.Length == length); } } } } if (IncludeScopeProperties) { bool flag = ExcludeProperties.Count > 0; using ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = ScopeContext.GetAllPropertiesEnumerator(); while (scopeContextPropertyEnumerator.MoveNext()) { KeyValuePair current3 = scopeContextPropertyEnumerator.Current; if (!string.IsNullOrEmpty(current3.Key) && (!flag || !ExcludeProperties.Contains(current3.Key))) { object value = current3.Value; if (DottedRecursion && PropertyValueSupportsDottedRecursion(value)) { AppendFlattenedPropertyValue(current3.Key, value, CaptureType.Unknown, sb, sb.Length == length); } else { AppendJsonPropertyValue(current3.Key, value, sb, sb.Length == length); } } } } if (IncludeEventProperties && logEvent.HasProperties) { bool flag2 = ExcludeProperties.Count > 0; using PropertiesDictionary.PropertyDictionaryEnumerator propertyDictionaryEnumerator = logEvent.CreatePropertiesInternal().GetPropertyEnumerator(); while (propertyDictionaryEnumerator.MoveNext()) { MessageTemplateParameter currentParameter = propertyDictionaryEnumerator.CurrentParameter; if (!string.IsNullOrEmpty(currentParameter.Name) && (!flag2 || !ExcludeProperties.Contains(currentParameter.Name))) { object value2 = currentParameter.Value; if (DottedRecursion && currentParameter.CaptureType != CaptureType.Stringify && PropertyValueSupportsDottedRecursion(value2)) { AppendFlattenedPropertyValue(currentParameter.Name, value2, currentParameter.CaptureType, sb, sb.Length == length); } else { AppendPropertyValueInternal(currentParameter.Name, value2, currentParameter.Format, logEvent.FormatProvider, currentParameter.CaptureType, sb, sb.Length == length); } } } } if (sb.Length > length) { sb.Append(_completeJsonMessage); } } private static bool PropertyValueSupportsDottedRecursion(object? propertyValue) { if (propertyValue is IFormattable) { return false; } if (propertyValue is IConvertible convertible) { return convertible.GetTypeCode() == TypeCode.Object; } return propertyValue != null; } private void BeginJsonProperty(StringBuilder sb, string propName, bool beginJsonMessage, bool ensureStringEscape) { sb.Append(beginJsonMessage ? _beginJsonMessage : _beginJsonPropertyName); if (ensureStringEscape) { DefaultJsonSerializer.AppendStringEscape(sb, propName, escapeUnicode: false); } else { sb.Append(propName); } sb.Append(_completeJsonPropertyName); } private void RefreshJsonDelimiters() { if (IndentJson) { _beginJsonMessage = new StringBuilder().Append('{').AppendLine().Append(' ', 2) .Append('"') .ToString(); } else { _beginJsonMessage = (SuppressSpaces ? "{\"" : "{ \""); } if (IndentJson) { _completeJsonMessage = new StringBuilder().AppendLine().Append('}').ToString() .ToString(); } else { _completeJsonMessage = (SuppressSpaces ? "}" : " }"); } if (IndentJson) { _beginJsonPropertyName = new StringBuilder().Append(',').AppendLine().Append(' ', 2) .Append('"') .ToString(); } else { _beginJsonPropertyName = (SuppressSpaces ? ",\"" : ", \""); } _completeJsonPropertyName = (SuppressSpaces ? "\":" : "\": "); } private void AppendJsonPropertyValue(string propName, object? propertyValue, StringBuilder sb, bool beginJsonMessage) { if (!ExcludeEmptyProperties || (propertyValue != null && propertyValue != string.Empty)) { int length = sb.Length; BeginJsonProperty(sb, propName, beginJsonMessage, ensureStringEscape: true); if (!JsonConverter.SerializeObject(propertyValue, sb)) { sb.Length = length; } else if (ExcludeEmptyProperties && sb[sb.Length - 1] == '"' && sb[sb.Length - 2] == '"' && sb[sb.Length - 3] != '\\') { sb.Length = length; } } } private void AppendPropertyValueInternal(string propName, object? propertyValue, string? format, IFormatProvider? formatProvider, CaptureType captureType, StringBuilder sb, bool beginJsonMessage) { if (captureType == CaptureType.Serialize && MaxRecursionLimit <= 1) { if (!ExcludeEmptyProperties || propertyValue != null) { int length = sb.Length; BeginJsonProperty(sb, propName, beginJsonMessage, ensureStringEscape: true); if (!JsonConverter.SerializeObjectNoLimit(propertyValue, sb)) { sb.Length = length; } } } else if (captureType == CaptureType.Stringify) { if (!ExcludeEmptyProperties || !StringHelpers.IsNullOrEmptyString(propertyValue)) { BeginJsonProperty(sb, propName, beginJsonMessage, ensureStringEscape: true); sb.Append('"'); int length2 = sb.Length; ValueFormatter.FormatValue(propertyValue, format, captureType, formatProvider, sb); DefaultJsonSerializer.PerformJsonEscapeWhenNeeded(sb, length2, escapeUnicode: false); sb.Append('"'); } } else { AppendJsonPropertyValue(propName, propertyValue, sb, beginJsonMessage); } } private void AppendFlattenedPropertyValue(string propName, object? propertyValue, CaptureType captureType, StringBuilder sb, bool beginJsonMessage) { int depth = ((captureType == CaptureType.Serialize) ? Math.Min(0, MaxRecursionLimit - 10) : 0); SingleItemOptimizedHashSet objectsInPath = default(SingleItemOptimizedHashSet); FlattenObjectProperties(propName, propertyValue, sb, beginJsonMessage, ref objectsInPath, depth); } private void FlattenObjectProperties(string basePropertyName, object? propertyValue, StringBuilder sb, bool beginJsonMessage, ref SingleItemOptimizedHashSet objectsInPath, int depth = 0) { if (propertyValue == null || !PropertyValueSupportsDottedRecursion(propertyValue) || propertyValue is Exception) { AppendJsonPropertyValue(basePropertyName, propertyValue, sb, beginJsonMessage); return; } if (depth >= MaxRecursionLimit) { AppendJsonPropertyValue(basePropertyName, propertyValue, sb, beginJsonMessage); return; } if (propertyValue is IEnumerable && !ObjectReflectionCache.TryLookupExpandoObject(propertyValue, out var _)) { AppendJsonPropertyValue(basePropertyName, propertyValue, sb, beginJsonMessage); return; } ObjectReflectionCache.ObjectPropertyList objectPropertyList2 = ObjectReflectionCache.LookupObjectProperties(propertyValue); if (objectPropertyList2.IsSimpleValue) { AppendJsonPropertyValue(basePropertyName, objectPropertyList2.ObjectValue, sb, beginJsonMessage); return; } using (new SingleItemOptimizedHashSet.SingleItemScopedInsert(propertyValue, ref objectsInPath, forceHashSet: false)) { bool beginJsonMessage2 = beginJsonMessage; foreach (ObjectReflectionCache.ObjectPropertyList.PropertyValue item in objectPropertyList2) { object value = item.Value; if (value != null && !string.IsNullOrEmpty(item.Name) && (objectsInPath.Count <= 0 || !objectsInPath.Contains(value))) { string basePropertyName2 = basePropertyName + "." + item.Name; int length = sb.Length; FlattenObjectProperties(basePropertyName2, value, sb, beginJsonMessage2, ref objectsInPath, depth + 1); if (sb.Length != length) { beginJsonMessage2 = false; } } } } } private void RenderAppendJsonPropertyValue(JsonAttribute attrib, LogEventInfo logEvent, StringBuilder sb, bool beginJsonMessage) { int length = sb.Length; BeginJsonProperty(sb, attrib.Name, beginJsonMessage, ensureStringEscape: false); if (!attrib.RenderAppendJsonValue(logEvent, JsonConverter, sb)) { sb.Length = length; } } public override string ToString() { if (_attributes.Count > 0) { return ToStringWithNestedItems(_attributes, (JsonAttribute a) => a.Name + "=" + a.Layout); } if (IncludeEventProperties) { return GetType().Name + ": IncludeEventProperties=true"; } return GetType().Name; } } [NLogConfigurationItem] public abstract class Layout : ISupportsInitialize, IRenderable { public static readonly Layout Empty = new SimpleLayout(); internal bool IsInitialized; private bool _scannedForObjects; internal bool ThreadAgnostic { get; set; } internal bool ThreadAgnosticImmutable { get; set; } internal StackTraceUsage StackTraceUsage { get; set; } protected internal LoggingConfiguration? LoggingConfiguration { get; private set; } public static implicit operator Layout([Localizable(false)] string text) { if (text == null) { return new Layout(null); } return FromString(text, ConfigurationItemFactory.Default); } public static Layout FromString([Localizable(false)] string layoutText) { return FromString(layoutText, ConfigurationItemFactory.Default); } public static Layout FromString([Localizable(false)] string layoutText, ConfigurationItemFactory configurationItemFactory) { if (!string.IsNullOrEmpty(layoutText)) { return new SimpleLayout(layoutText, configurationItemFactory); } return Empty; } public static Layout FromString([Localizable(false)] string layoutText, bool throwConfigExceptions) { try { return string.IsNullOrEmpty(layoutText) ? Empty : new SimpleLayout(layoutText, ConfigurationItemFactory.Default, throwConfigExceptions); } catch (NLogConfigurationException) { throw; } catch (Exception ex2) { if (!throwConfigExceptions || ex2.MustBeRethrownImmediately()) { throw; } throw new NLogConfigurationException("Invalid Layout: " + layoutText, ex2); } } public static Layout FromLiteral([Localizable(false)] string literalText) { if (string.IsNullOrEmpty(literalText)) { return Empty; } LayoutRenderer[] layoutRenderers = new LiteralLayoutRenderer[1] { new LiteralLayoutRenderer(literalText) }; return new SimpleLayout(layoutRenderers, literalText); } public static Layout FromMethod(Func layoutMethod, LayoutRenderOptions options = LayoutRenderOptions.None) { Func layoutMethod2 = layoutMethod; Guard.ThrowIfNull(layoutMethod2, "layoutMethod"); string name = layoutMethod2.Method?.DeclaringType?.ToString() + "." + layoutMethod2.Method?.Name; FuncLayoutRenderer funcLayoutRenderer = CreateFuncLayoutRenderer((LogEventInfo l, LoggingConfiguration? c) => layoutMethod2(l), options, name); LayoutRenderer[] layoutRenderers = new FuncLayoutRenderer[1] { funcLayoutRenderer }; return new SimpleLayout(layoutRenderers, funcLayoutRenderer.LayoutRendererName); } internal static FuncLayoutRenderer CreateFuncLayoutRenderer(Func layoutMethod, LayoutRenderOptions options, string name) { if ((options & LayoutRenderOptions.ThreadAgnostic) == LayoutRenderOptions.ThreadAgnostic) { return new FuncThreadAgnosticLayoutRenderer(name, layoutMethod); } return new FuncLayoutRenderer(name, layoutMethod); } public virtual void Precalculate(LogEventInfo logEvent) { if (!ThreadAgnostic || ThreadAgnosticImmutable) { using (AppendBuilderCreator appendBuilderCreator = new AppendBuilderCreator(mustBeEmpty: true)) { PrecalculateCachedLayoutValue(logEvent, appendBuilderCreator.Builder); } } } public string Render(LogEventInfo logEvent) { if (!IsInitialized) { Initialize(LoggingConfiguration); } if ((!ThreadAgnostic || ThreadAgnosticImmutable) && logEvent.TryGetCachedLayoutValue(this, out object value)) { return value?.ToString() ?? string.Empty; } return GetFormattedMessage(logEvent) ?? string.Empty; } public void Render(LogEventInfo logEvent, StringBuilder target) { if (!IsInitialized) { Initialize(LoggingConfiguration); } if ((!ThreadAgnostic || ThreadAgnosticImmutable) && logEvent.TryGetCachedLayoutValue(this, out object value)) { target.Append(value?.ToString()); } else { RenderFormattedMessage(logEvent, target); } } internal virtual void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { Precalculate(logEvent); } private void PrecalculateCachedLayoutValue(LogEventInfo logEvent, StringBuilder target) { if (!IsInitialized) { Initialize(LoggingConfiguration); } if ((!ThreadAgnostic || ThreadAgnosticImmutable) && !logEvent.TryGetCachedLayoutValue(this, out object _)) { RenderFormattedMessage(logEvent, target); logEvent.AddCachedLayoutValue(this, target.ToString()); } } internal string RenderAllocateBuilder(LogEventInfo logEvent) { using AppendBuilderCreator appendBuilderCreator = new AppendBuilderCreator(mustBeEmpty: true); RenderFormattedMessage(logEvent, appendBuilderCreator.Builder); return appendBuilderCreator.Builder.ToString(); } internal string RenderAllocateBuilder(LogEventInfo logEvent, StringBuilder target) { RenderFormattedMessage(logEvent, target); return target.ToString(); } protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { target.Append(GetFormattedMessage(logEvent)); } void ISupportsInitialize.Initialize(LoggingConfiguration? configuration) { Initialize(configuration); } void ISupportsInitialize.Close() { Close(); } internal void Initialize(LoggingConfiguration? configuration) { if (IsInitialized) { return; } try { LoggingConfiguration = configuration; _scannedForObjects = false; InitializeLayout(); if (!_scannedForObjects) { InternalLogger.Debug("{0} Initialized Layout done but not scanned for objects", GetType()); PerformObjectScanning(); } } finally { IsInitialized = true; } } internal void PerformObjectScanning() { List list = ObjectGraphScanner.FindReachableObjects(ConfigurationItemFactory.Default, aggressiveSearch: true, new object[1] { this }); HashSet hashSet = new HashSet(list.Select((IRenderable o) => o.GetType())); hashSet.Remove(typeof(SimpleLayout)); hashSet.Remove(typeof(LiteralLayoutRenderer)); hashSet.Remove(typeof(LiteralWithRawValueLayoutRenderer)); ThreadAgnostic = hashSet.All((Type t) => t.IsDefined(typeof(ThreadAgnosticAttribute), inherit: true)); ThreadAgnosticImmutable = ThreadAgnostic && hashSet.Any((Type t) => t.IsDefined(typeof(ThreadAgnosticImmutableAttribute), inherit: true)); if (list.Count > 1 && hashSet.Count > 0) { foreach (Layout item in list.OfType()) { if (item != this) { item.Initialize(LoggingConfiguration); ThreadAgnostic = item.ThreadAgnostic && ThreadAgnostic; ThreadAgnosticImmutable = ThreadAgnostic && (item.ThreadAgnosticImmutable || ThreadAgnosticImmutable); } } } StackTraceUsage = StackTraceUsage.None; StackTraceUsage = list.OfType().DefaultIfEmpty().Aggregate(StackTraceUsage.None, (StackTraceUsage usage, IUsesStackTrace item) => (usage | item?.StackTraceUsage).GetValueOrDefault()); _scannedForObjects = true; } internal Layout[]? ResolveLayoutPrecalculation(IEnumerable allLayouts) { if (!_scannedForObjects || (ThreadAgnostic && !ThreadAgnosticImmutable)) { return null; } int num = 0; int num2 = 0; int num3 = 0; foreach (Layout allLayout in allLayouts) { num++; if ((allLayout != null && !allLayout.ThreadAgnostic) || (allLayout != null && allLayout.ThreadAgnosticImmutable)) { num2++; if (allLayout is SimpleLayout) { num3++; } } } if (num <= 1 || num2 > 4 || num2 - num3 > 2 || num - num3 <= 1 || num2 == 0) { return null; } return allLayouts.Where((Layout layout) => (layout != null && !layout.ThreadAgnostic) || (layout?.ThreadAgnosticImmutable ?? false)).ToArray(); } internal void Close() { if (IsInitialized) { LoggingConfiguration = null; IsInitialized = false; CloseLayout(); } } protected virtual void InitializeLayout() { PerformObjectScanning(); } protected virtual void CloseLayout() { } protected abstract string GetFormattedMessage(LogEventInfo logEvent); [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Register<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name) where T : Layout { Type typeFromHandle = typeof(T); Register(name, typeFromHandle); } [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Register(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type layoutType) { ConfigurationItemFactory.Default.GetLayoutFactory().RegisterDefinition(name, layoutType); } internal void PrecalculateBuilderInternal(LogEventInfo logEvent, StringBuilder target, Layout[]? precalculateLayout) { if (ThreadAgnostic && !ThreadAgnosticImmutable) { return; } if (precalculateLayout == null) { PrecalculateCachedLayoutValue(logEvent, target); return; } foreach (Layout obj in precalculateLayout) { target.ClearBuilder(); obj.PrecalculateBuilder(logEvent, target); } } internal string ToStringWithNestedItems(IList nestedItems, Func nextItemToString) { if (nestedItems != null && nestedItems.Count > 0) { string[] value = nestedItems.Select(nextItemToString).ToArray(); return GetType().Name + ": " + string.Join("|", value); } return GetType().Name; } internal virtual bool TryGetRawValue(LogEventInfo logEvent, out object? rawValue) { rawValue = null; return false; } protected T ResolveService() where T : class { return LoggingConfiguration.GetServiceProvider().ResolveService(IsInitialized); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class LayoutAttribute : NameBaseAttribute { public LayoutAttribute(string name) : base(name) { } } internal static class LayoutParser { private static readonly char[] SpecialTokens = new char[4] { '$', '\\', '}', ':' }; internal static LayoutRenderer[] CompileLayout(string value, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions, out string parsedText) { if (string.IsNullOrEmpty(value)) { parsedText = string.Empty; return ArrayHelper.Empty(); } if (value.Length < 128 && value.IndexOfAny(SpecialTokens) < 0) { parsedText = value; return new LayoutRenderer[1] { new LiteralLayoutRenderer(value) }; } return CompileLayout(configurationItemFactory, new SimpleStringReader(value), throwConfigExceptions, isNested: false, out parsedText); } internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool? throwConfigExceptions, bool isNested, out string text) { List list = new List(); StringBuilder stringBuilder = new StringBuilder(); int position = sr.Position; int num; while ((num = sr.Peek()) != -1) { if (isNested) { if (num == 92) { sr.Read(); int num2 = sr.Peek(); if (EndOfLayout(num2)) { sr.Read(); stringBuilder.Append((char)num2); } else { stringBuilder.Append('\\'); } continue; } if (EndOfLayout(num)) { break; } } sr.Read(); if (num == 36 && sr.Peek() == 123) { AddLiteral(stringBuilder, list); LayoutRenderer item = ParseLayoutRenderer(configurationItemFactory, sr, throwConfigExceptions); list.Add(item); } else { stringBuilder.Append((char)num); } } AddLiteral(stringBuilder, list); int position2 = sr.Position; MergeLiterals(list); text = sr.Substring(position, position2); return list.ToArray(); } private static void AddLiteral(StringBuilder literalBuf, List result) { if (literalBuf.Length > 0) { result.Add(new LiteralLayoutRenderer(literalBuf.ToString())); literalBuf.Length = 0; } } private static bool EndOfLayout(int ch) { if (ch != 125) { return ch == 58; } return true; } private static string ParseLayoutRendererTypeName(SimpleStringReader sr) { return sr.ReadUntilMatch((int ch) => EndOfLayout(ch)); } private static string ParseParameterNameOrValue(SimpleStringReader sr) { string text = sr.ReadUntilMatch((int chr) => EndOfLayout(chr) || chr == 61 || chr == 36 || chr == 92); if (sr.Peek() != 36 && sr.Peek() != 92) { return text; } StringBuilder stringBuilder = new StringBuilder(text); ParseLayoutParameterValue(sr, stringBuilder, (int chr) => EndOfLayout(chr) || chr == 61); return stringBuilder.ToString(); } private static string ParseParameterStringValue(SimpleStringReader sr) { string text = sr.ReadUntilMatch((int chr) => EndOfLayout(chr) || chr == 36 || chr == 92); if (sr.Peek() != 36 && sr.Peek() != 92) { return text; } StringBuilder stringBuilder = new StringBuilder(text); if (!ParseLayoutParameterValue(sr, stringBuilder, (int chr) => EndOfLayout(chr))) { return stringBuilder.ToString(); } string value = stringBuilder.ToString(); stringBuilder.ClearBuilder(); return EscapeUnicodeStringValue(value, stringBuilder); } private static bool ParseLayoutParameterValue(SimpleStringReader sr, StringBuilder parameterValue, Func endOfLayout) { bool result = false; int num = 0; int num2; while ((num2 = sr.Peek()) != -1 && (!endOfLayout(num2) || num != 0)) { switch (num2) { case 36: sr.Read(); parameterValue.Append('$'); if (sr.Peek() == 123) { parameterValue.Append('{'); num++; sr.Read(); } continue; case 125: num--; break; } if (num2 == 92) { sr.Read(); num2 = sr.Peek(); if (num == 0 && (endOfLayout(num2) || num2 == 36 || num2 == 61)) { parameterValue.Append((char)sr.Read()); } else if (num2 != -1) { result = true; parameterValue.Append('\\'); parameterValue.Append((char)sr.Read()); } } else { parameterValue.Append((char)num2); sr.Read(); } } return result; } private static string ParseParameterValue(SimpleStringReader sr) { string text = sr.ReadUntilMatch((int ch) => EndOfLayout(ch) || ch == 92); if (sr.Peek() == 92) { bool flag = false; StringBuilder stringBuilder = new StringBuilder(text); int num; while ((num = sr.Peek()) != -1 && !EndOfLayout(num)) { if (num == 92) { sr.Read(); num = sr.Peek(); if (EndOfLayout(num)) { stringBuilder.Append((char)sr.Read()); } else if (num != -1) { flag = true; stringBuilder.Append('\\'); stringBuilder.Append((char)sr.Read()); } } else { stringBuilder.Append((char)num); sr.Read(); } } text = stringBuilder.ToString(); if (flag) { stringBuilder.Length = 0; text = EscapeUnicodeStringValue(text, stringBuilder); } } return text; } private static string EscapeUnicodeStringValue(string value, StringBuilder? nameBuf = null) { bool flag = false; nameBuf = nameBuf ?? new StringBuilder(value.Length); for (int i = 0; i < value.Length; i++) { char c = value[i]; if (flag) { flag = false; switch (c) { case '"': case '\'': case ':': case '\\': case '{': case '}': nameBuf.Append(c); break; case '0': nameBuf.Append('\0'); break; case 'a': nameBuf.Append('\a'); break; case 'b': nameBuf.Append('\b'); break; case 'f': nameBuf.Append('\f'); break; case 'n': nameBuf.Append('\n'); break; case 'r': nameBuf.Append('\r'); break; case 't': nameBuf.Append('\t'); break; case 'u': { char unicode3 = GetUnicode(value, 4, ref i); nameBuf.Append(unicode3); break; } case 'U': { char unicode2 = GetUnicode(value, 8, ref i); nameBuf.Append(unicode2); break; } case 'x': { char unicode = GetUnicode(value, 4, ref i); nameBuf.Append(unicode); break; } case 'v': nameBuf.Append('\v'); break; default: nameBuf.Append(c); break; } } else if (c == '\\') { flag = true; } else { nameBuf.Append(c); } } if (flag) { nameBuf.Append('\\'); } return nameBuf.ToString(); } private static char GetUnicode(string value, int maxDigits, ref int currentIndex) { int num = 0; maxDigits = Math.Min(value.Length - 1, currentIndex + maxDigits); while (currentIndex < maxDigits) { int num2 = value[currentIndex + 1]; if (num2 >= 48 && num2 <= 57) { num2 -= 48; } else if (num2 >= 97 && num2 <= 102) { num2 = num2 - 97 + 10; } else { if (num2 < 65 || num2 > 70) { break; } num2 = num2 - 65 + 10; } num = num * 16 + num2; currentIndex++; } return (char)num; } private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader, bool? throwConfigExceptions) { int num = stringReader.Read(); string text = ParseLayoutRendererTypeName(stringReader); LayoutRenderer layoutRenderer = GetLayoutRenderer(text, configurationItemFactory, throwConfigExceptions); Dictionary wrappers = null; List orderedWrappers = null; string previousParameterName = null; num = stringReader.Read(); while (num != -1 && num != 125) { string text2 = ParseParameterNameOrValue(stringReader); if (stringReader.Peek() == 61) { stringReader.Read(); text2 = text2.Trim(); LayoutRenderer targetObject = layoutRenderer; if (!PropertyHelper.TryGetPropertyInfo(configurationItemFactory, layoutRenderer, text2, out PropertyInfo result) && TryResolveAmbientLayoutWrapper(text2, configurationItemFactory, ref wrappers, ref orderedWrappers, out LayoutRenderer layoutRenderer2) && layoutRenderer2 != null && PropertyHelper.TryGetPropertyInfo(configurationItemFactory, layoutRenderer2, text2, out result)) { targetObject = layoutRenderer2; } if ((object)result == null) { string value = ParseParameterValue(stringReader); if (!string.IsNullOrEmpty(text2) || !StringHelpers.IsNullOrWhiteSpace(value)) { NLogConfigurationException ex = new NLogConfigurationException("${" + text + "} cannot assign unknown property '" + text2 + "='"); if (throwConfigExceptions ?? ex.MustBeRethrown()) { throw ex; } } } else { object obj = ParseLayoutRendererPropertyValue(configurationItemFactory, stringReader, throwConfigExceptions, text, result); if (obj is string stringValue) { PropertyHelper.SetPropertyFromString(targetObject, result, stringValue, configurationItemFactory); } else if (obj != null) { PropertyHelper.SetPropertyValueForObject(targetObject, obj, result); } } } else { text2 = SetDefaultPropertyValue(text2, layoutRenderer, configurationItemFactory, throwConfigExceptions); } previousParameterName = ValidatePreviousParameterName(previousParameterName, text2, layoutRenderer, throwConfigExceptions); num = stringReader.Read(); } return BuildCompleteLayoutRenderer(configurationItemFactory, layoutRenderer, orderedWrappers); } private static LayoutRenderer BuildCompleteLayoutRenderer(ConfigurationItemFactory configurationItemFactory, LayoutRenderer layoutRenderer, List? orderedWrappers = null) { if (orderedWrappers != null) { layoutRenderer = ApplyWrappers(configurationItemFactory, layoutRenderer, orderedWrappers); } if (CanBeConvertedToLiteral(configurationItemFactory, layoutRenderer)) { layoutRenderer = ConvertToLiteral(layoutRenderer); } return layoutRenderer; } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2072")] private static object? ParseLayoutRendererPropertyValue(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader, bool? throwConfigExceptions, string targetTypeName, PropertyInfo propertyInfo) { if (typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType)) { string text; Layout layout = new SimpleLayout(CompileLayout(configurationItemFactory, stringReader, throwConfigExceptions, isNested: true, out text), text); if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Layout<>)) { layout = (Layout)Activator.CreateInstance(propertyInfo.PropertyType, BindingFlags.Instance | BindingFlags.Public, null, new object[1] { layout }, null); } return layout; } if (typeof(ConditionExpression).IsAssignableFrom(propertyInfo.PropertyType)) { try { return ConditionParser.ParseExpression(stringReader, configurationItemFactory); } catch (ConditionParseException ex) { NLogConfigurationException ex2 = new NLogConfigurationException("${" + targetTypeName + "} cannot parse ConditionExpression for property '" + propertyInfo.Name + "='. Error: " + ex.Message, ex); if (throwConfigExceptions ?? ex2.MustBeRethrown()) { throw ex2; } return null; } } if (typeof(string).IsAssignableFrom(propertyInfo.PropertyType)) { return ParseParameterStringValue(stringReader); } return ParseParameterValue(stringReader); } private static string? ValidatePreviousParameterName(string? previousParameterName, string parameterName, LayoutRenderer layoutRenderer, bool? throwConfigExceptions) { if (parameterName != null && parameterName.Equals(previousParameterName, StringComparison.OrdinalIgnoreCase)) { NLogConfigurationException ex = new NLogConfigurationException("'" + layoutRenderer?.GetType()?.Name + "' has same property '" + parameterName + "=' assigned twice"); if (throwConfigExceptions ?? ex.MustBeRethrown()) { throw ex; } } else { previousParameterName = parameterName ?? previousParameterName; } return previousParameterName; } private static bool TryResolveAmbientLayoutWrapper(string propertyName, ConfigurationItemFactory configurationItemFactory, ref Dictionary? wrappers, ref List? orderedWrappers, out LayoutRenderer? layoutRenderer) { if (!configurationItemFactory.AmbientRendererFactory.TryCreateInstance(propertyName, out LayoutRenderer result) || result == null) { layoutRenderer = null; return false; } wrappers = wrappers ?? new Dictionary(); orderedWrappers = orderedWrappers ?? new List(); Type type = result.GetType(); if (!wrappers.TryGetValue(type, out layoutRenderer)) { wrappers[type] = result; orderedWrappers.Add(result); layoutRenderer = result; } return true; } private static LayoutRenderer GetLayoutRenderer(string typeName, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions) { LayoutRenderer result = null; try { if (throwConfigExceptions == false && !configurationItemFactory.LayoutRendererFactory.TryCreateInstance(typeName, out result)) { InternalLogger.Debug("Failed to create LayoutRenderer with unknown type-alias: '{0}'", typeName); return new LiteralLayoutRenderer(string.Empty); } result = configurationItemFactory.LayoutRendererFactory.CreateInstance(typeName); } catch (NLogConfigurationException exception) { if (throwConfigExceptions ?? exception.MustBeRethrown()) { throw; } } catch (Exception ex) { NLogConfigurationException ex2 = new NLogConfigurationException("Failed to parse layout containing type: " + typeName + " - " + ex.Message, ex); if (throwConfigExceptions ?? ex2.MustBeRethrown()) { throw ex2; } } return result ?? new LiteralLayoutRenderer(string.Empty); } private static string SetDefaultPropertyValue(string value, LayoutRenderer layoutRenderer, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions) { if (PropertyHelper.TryGetPropertyInfo(configurationItemFactory, layoutRenderer, string.Empty, out PropertyInfo result) && result != null) { if (!typeof(Layout).IsAssignableFrom(result.PropertyType) && value.IndexOf('\\') >= 0) { value = EscapeUnicodeStringValue(value); } PropertyHelper.SetPropertyFromString(layoutRenderer, result, value, configurationItemFactory); return result.Name; } NLogConfigurationException ex = new NLogConfigurationException("'" + layoutRenderer?.GetType()?.Name + "' has no default property to assign value " + value); if (throwConfigExceptions ?? ex.MustBeRethrown()) { throw ex; } return string.Empty; } private static LayoutRenderer ApplyWrappers(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr, List orderedWrappers) { for (int num = orderedWrappers.Count - 1; num >= 0; num--) { WrapperLayoutRendererBase wrapperLayoutRendererBase = (WrapperLayoutRendererBase)orderedWrappers[num]; InternalLogger.Trace("Wrapping {0} with {1}", lr.GetType(), wrapperLayoutRendererBase.GetType()); if (CanBeConvertedToLiteral(configurationItemFactory, lr)) { lr = ConvertToLiteral(lr); } wrapperLayoutRendererBase.Inner = new SimpleLayout(new LayoutRenderer[1] { lr }, string.Empty); lr = wrapperLayoutRendererBase; } return lr; } private static bool CanBeConvertedToLiteral(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr) { if (lr is LiteralLayoutRenderer) { return false; } if (!lr.GetType().IsDefined(typeof(AppDomainFixedOutputAttribute), inherit: false)) { return false; } foreach (IRenderable item in ObjectGraphScanner.FindReachableObjects(configurationItemFactory, aggressiveSearch: true, new object[1] { lr })) { if (item != lr && !(item is SimpleLayout) && !(item is LiteralLayoutRenderer) && !item.GetType().IsDefined(typeof(AppDomainFixedOutputAttribute), inherit: false)) { return false; } } return true; } private static void MergeLiterals(List list) { for (int num = list.Count - 1; num >= 1; num--) { LiteralLayoutRenderer literalLayoutRenderer = list[num - 1] as LiteralLayoutRenderer; if (literalLayoutRenderer != null && list[num] is LiteralLayoutRenderer literalLayoutRenderer2) { if (literalLayoutRenderer is LiteralWithRawValueLayoutRenderer) { literalLayoutRenderer = (LiteralLayoutRenderer)(list[num - 1] = new LiteralLayoutRenderer(literalLayoutRenderer.Text)); } literalLayoutRenderer.Text += literalLayoutRenderer2.Text; list.RemoveAt(num); } } } private static LayoutRenderer ConvertToLiteral(LayoutRenderer renderer) { LogEventInfo logEvent = LogEventInfo.CreateNullEvent(); string text = renderer.Render(logEvent); if (renderer is IRawValue rawValue && rawValue.TryGetRawValue(logEvent, out object value)) { return new LiteralWithRawValueLayoutRenderer(text, value); } return new LiteralLayoutRenderer(text); } } [Flags] public enum LayoutRenderOptions { None = 0, [Obsolete("All LayoutRenderers and Layout should be ThreadSafe by default. Marked obsolete with NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] ThreadSafe = 1, ThreadAgnostic = 3 } [Layout("LayoutWithHeaderAndFooter")] [ThreadAgnostic] [AppDomainFixedOutput] public class LayoutWithHeaderAndFooter : Layout { public Layout Layout { get; set; } = NLog.Layouts.Layout.Empty; public Layout? Header { get; set; } public Layout? Footer { get; set; } protected override string GetFormattedMessage(LogEventInfo logEvent) { return Layout.Render(logEvent); } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { Layout.Render(logEvent, target); } } [Layout("SimpleLayout")] [ThreadAgnostic] [AppDomainFixedOutput] public sealed class SimpleLayout : Layout, IUsesStackTrace, IStringValueRenderer { private readonly IRawValue? _rawValueRenderer; private IStringValueRenderer? _stringValueRenderer; private ReadOnlyCollection? _renderers; private readonly LayoutRenderer[] _layoutRenderers; internal static SimpleLayout Default => (SimpleLayout)Layout.Empty; public string OriginalText { get; } public string Text { get; } public bool IsFixedText => FixedText != null; public string? FixedText { get; } internal bool IsSimpleStringText => _stringValueRenderer != null; [NLogConfigurationIgnoreProperty] public ReadOnlyCollection Renderers => _renderers ?? (_renderers = new ReadOnlyCollection(_layoutRenderers)); public IEnumerable LayoutRenderers => _layoutRenderers; public new StackTraceUsage StackTraceUsage => base.StackTraceUsage; public SimpleLayout() : this(ArrayHelper.Empty(), string.Empty) { } public SimpleLayout([Localizable(false)] string txt) : this(txt, ConfigurationItemFactory.Default) { } public SimpleLayout([Localizable(false)] string txt, ConfigurationItemFactory configurationItemFactory) : this(txt, configurationItemFactory, null) { } internal SimpleLayout([Localizable(false)] string txt, ConfigurationItemFactory configurationItemFactory, bool? throwConfigExceptions) : this(LayoutParser.CompileLayout(txt, configurationItemFactory, throwConfigExceptions, out string parsedText), parsedText) { OriginalText = txt ?? string.Empty; } internal SimpleLayout(LayoutRenderer[] layoutRenderers, [Localizable(false)] string txt) { Text = txt ?? string.Empty; OriginalText = txt ?? string.Empty; _layoutRenderers = layoutRenderers ?? ArrayHelper.Empty(); if (_layoutRenderers.Length == 0) { FixedText = string.Empty; _stringValueRenderer = this; } else if (_layoutRenderers.Length == 1) { if (_layoutRenderers[0] is LiteralLayoutRenderer literalLayoutRenderer) { FixedText = literalLayoutRenderer.Text; _stringValueRenderer = this; } else if (_layoutRenderers[0] is IStringValueRenderer stringValueRenderer) { _stringValueRenderer = stringValueRenderer; } if (_layoutRenderers[0] is IRawValue rawValueRenderer) { _rawValueRenderer = rawValueRenderer; } } } [return: NotNullIfNotNull("text")] public static implicit operator SimpleLayout?([Localizable(false)] string text) { if (text == null) { return null; } if (!string.IsNullOrEmpty(text)) { return new SimpleLayout(text); } return Default; } [Obsolete("Instead use Layout.FromLiteral()")] [EditorBrowsable(EditorBrowsableState.Never)] public static string Escape([Localizable(false)] string text) { return text.Replace("${", "${literal:text=\\$\\{}"); } public static string Evaluate([Localizable(false)] string text, LogEventInfo logEvent) { return Evaluate(text, null, logEvent); } public static string Evaluate([Localizable(false)] string text) { return Evaluate(text, null, null, null); } internal static string Evaluate(string text, LoggingConfiguration? loggingConfiguration, LogEventInfo? logEventInfo = null, bool? throwConfigExceptions = null) { try { if (string.IsNullOrEmpty(text)) { return string.Empty; } if (text.IndexOf('$') < 0 || text.IndexOf('{') < 0 || text.IndexOf('}') < 0) { return text; } throwConfigExceptions = throwConfigExceptions ?? loggingConfiguration?.LogFactory.ThrowConfigExceptions; Layout layout = Layout.FromString(text, throwConfigExceptions ?? LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions); layout.Initialize(loggingConfiguration); return layout.Render(logEventInfo ?? LogEventInfo.CreateNullEvent()); } catch (NLogConfigurationException ex) { if (throwConfigExceptions ?? LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions) { throw; } InternalLogger.Warn(ex, "Failed to Evaluate SimpleLayout: {0}", new ReadOnlySpan(new object[1] { text })); return text; } catch (Exception ex2) { InternalLogger.Warn(ex2, "Failed to Evaluate SimpleLayout: {0}", new ReadOnlySpan(new object[1] { text })); return text; } } public override string ToString() { if (string.IsNullOrEmpty(Text) && !IsFixedText && _layoutRenderers.Length != 0) { return ToStringWithNestedItems(_layoutRenderers, (LayoutRenderer r) => r.ToString()); } return Text; } protected override void InitializeLayout() { LayoutRenderer[] layoutRenderers = _layoutRenderers; foreach (LayoutRenderer layoutRenderer in layoutRenderers) { try { layoutRenderer.Initialize(base.LoggingConfiguration); } catch (Exception ex) { if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(ex, "Exception in '{0}.Initialize()'", new ReadOnlySpan(new object[1] { layoutRenderer.GetType() })); } if (ex.MustBeRethrown()) { throw; } } } base.InitializeLayout(); } public override void Precalculate(LogEventInfo logEvent) { if (PrecalculateMustRenderLayoutValue(logEvent)) { using (AppendBuilderCreator appendBuilderCreator = new AppendBuilderCreator(mustBeEmpty: true)) { RenderFormattedMessage(logEvent, appendBuilderCreator.Builder); logEvent.AddCachedLayoutValue(this, appendBuilderCreator.Builder.ToString()); } } } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { if (PrecalculateMustRenderLayoutValue(logEvent)) { RenderFormattedMessage(logEvent, target); logEvent.AddCachedLayoutValue(this, target.ToString()); } } private bool PrecalculateMustRenderLayoutValue(LogEventInfo logEvent) { if (!IsInitialized) { Initialize(base.LoggingConfiguration); } if (base.ThreadAgnostic && !base.ThreadAgnosticImmutable) { return false; } if (_rawValueRenderer != null && TryGetRawValue(logEvent, out object rawValue) && IsRawValueImmutable(rawValue)) { return false; } if (logEvent.TryGetCachedLayoutValue(this, out object _)) { return false; } if (IsSimpleStringText) { string formattedMessage = GetFormattedMessage(logEvent); logEvent.AddCachedLayoutValue(this, formattedMessage); return false; } return true; } private static bool IsRawValueImmutable(object? value) { if (value != null) { if (Convert.GetTypeCode(value) == TypeCode.Object) { return value.GetType().IsValueType; } return true; } return false; } internal override bool TryGetRawValue(LogEventInfo logEvent, out object? rawValue) { if (_rawValueRenderer == null) { rawValue = null; return false; } return TryGetSafeRawValue(logEvent, out rawValue); } private bool TryGetSafeRawValue(LogEventInfo logEvent, out object? rawValue) { try { if (_rawValueRenderer == null) { rawValue = null; return false; } if (!IsInitialized) { Initialize(base.LoggingConfiguration); } if ((!base.ThreadAgnostic || base.ThreadAgnosticImmutable) && logEvent.TryGetCachedLayoutValue(this, out object _)) { rawValue = null; return false; } return _rawValueRenderer.TryGetRawValue(logEvent, out rawValue); } catch (Exception ex) { if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(ex, "Exception in TryGetRawValue using '{0}.TryGetRawValue()'", new ReadOnlySpan(new object[1] { _rawValueRenderer?.GetType() })); } if (ex.MustBeRethrown()) { throw; } } rawValue = null; return false; } protected override string GetFormattedMessage(LogEventInfo logEvent) { string stringValue = FixedText; if (stringValue != null) { return stringValue; } if (_stringValueRenderer == null || !TryGetSafeStringValue(logEvent, out stringValue)) { return RenderAllocateBuilder(logEvent); } return stringValue; } private bool TryGetSafeStringValue(LogEventInfo logEvent, out string stringValue) { try { if (!IsInitialized) { Initialize(base.LoggingConfiguration); } string text = _stringValueRenderer?.GetFormattedString(logEvent); if (text == null) { stringValue = string.Empty; _stringValueRenderer = null; return false; } stringValue = text; return true; } catch (Exception ex) { if (InternalLogger.IsWarnEnabled || InternalLogger.IsErrorEnabled) { InternalLogger.Warn(ex, "Exception in '{0}.GetFormattedString()'", new ReadOnlySpan(new object[1] { _stringValueRenderer?.GetType() })); } if (ex.MustBeRethrown()) { throw; } } stringValue = string.Empty; return false; } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { string fixedText = FixedText; if (fixedText == null) { LayoutRenderer[] layoutRenderers = _layoutRenderers; for (int i = 0; i < layoutRenderers.Length; i++) { layoutRenderers[i].RenderAppendBuilder(logEvent, target); } } else { target.Append(fixedText); } } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { string text = FixedText; if (text == null) { if (!IsSimpleStringText) { return null; } text = Render(logEvent); } return text; } } [ThreadAgnostic] public sealed class Layout : Layout, ILayoutTypeValue, ILayoutTypeValue, IEquatable { private sealed class LayoutGenericTypeValue : LayoutTypeValue, ILayoutTypeValue, ILayoutTypeValue { private readonly Layout _ownerLayout; public override IPropertyTypeConverter ValueTypeConverter => _ownerLayout.ValueTypeConverter; public LayoutGenericTypeValue(Layout layout, string? parseValueFormat, CultureInfo? parseValueCulture, Layout ownerLayout) : base(layout, typeof(T), parseValueFormat, parseValueCulture, null) { _ownerLayout = ownerLayout; } public void InitializeLayout() { InitializeLayout(_ownerLayout); } public void CloseLayout() { Close(); } public bool TryRenderValue(LogEventInfo logEvent, StringBuilder? stringBuilder, out T? value) { if (RenderObjectValue(logEvent, stringBuilder) is T val) { value = val; return true; } value = default(T); return false; } } private sealed class FuncMethodValue : ILayoutTypeValue, ILayoutTypeValue { private readonly Func _layoutMethod; public bool ThreadAgnostic { get; } ILayoutTypeValue ILayoutTypeValue.InnerLayout => this; Type ILayoutTypeValue.InnerType => typeof(T); LoggingConfiguration? ILayoutTypeValue.LoggingConfiguration => null; bool ILayoutTypeValue.ThreadAgnosticImmutable => false; StackTraceUsage ILayoutTypeValue.StackTraceUsage => StackTraceUsage.None; public FuncMethodValue(Func layoutMethod, LayoutRenderOptions options) { _layoutMethod = layoutMethod; ThreadAgnostic = options == LayoutRenderOptions.ThreadAgnostic; } public void InitializeLayout() { } public void CloseLayout() { } public bool TryRenderValue(LogEventInfo logEvent, StringBuilder? stringBuilder, out T? value) { value = _layoutMethod(logEvent); return true; } public object? RenderObjectValue(LogEventInfo logEvent, StringBuilder? stringBuilder) { return _layoutMethod(logEvent); } public override string ToString() { return _layoutMethod.ToString() ?? GetType().ToString(); } } private readonly T? _fixedValue; private object? _fixedObjectValue; private readonly ILayoutTypeValue _layoutValue; private IPropertyTypeConverter? _valueTypeConverter; ILayoutTypeValue ILayoutTypeValue.InnerLayout => _layoutValue; Type ILayoutTypeValue.InnerType => typeof(T); bool ILayoutTypeValue.ThreadAgnostic => true; bool ILayoutTypeValue.ThreadAgnosticImmutable => false; StackTraceUsage ILayoutTypeValue.StackTraceUsage => StackTraceUsage.None; LoggingConfiguration? ILayoutTypeValue.LoggingConfiguration => base.LoggingConfiguration; public bool IsFixed => this == _layoutValue; public T? FixedValue => _fixedValue; private object? FixedObjectValue => _fixedObjectValue ?? (_fixedObjectValue = _fixedValue); private IPropertyTypeConverter ValueTypeConverter => _valueTypeConverter ?? (_valueTypeConverter = ResolveService()); void ILayoutTypeValue.InitializeLayout() { } void ILayoutTypeValue.CloseLayout() { } bool ILayoutTypeValue.TryRenderValue(LogEventInfo logEvent, StringBuilder? stringBuilder, out T? value) { value = _fixedValue; return true; } object? ILayoutTypeValue.RenderObjectValue(LogEventInfo logEvent, StringBuilder? stringBuilder) { return FixedObjectValue; } public Layout(Layout layout) : this(layout, (string?)null, CultureInfo.InvariantCulture) { } public Layout(Layout layout, string? parseValueFormat, CultureInfo? parseValueCulture) { if (PropertyTypeConverter.IsComplexType(typeof(T))) { throw new NLogConfigurationException("Layout<" + typeof(T).ToString() + "> not supported. Immutable value type is recommended"); } if (TryParseFixedValue(layout, parseValueFormat, parseValueCulture, ref _fixedValue)) { _layoutValue = this; } else { _layoutValue = new LayoutGenericTypeValue(layout, parseValueFormat, parseValueCulture, this); } } public Layout(T? value) { _fixedValue = value; _layoutValue = this; } private Layout(Func layoutMethod, LayoutRenderOptions options) { Guard.ThrowIfNull(layoutMethod, "layoutMethod"); _layoutValue = new FuncMethodValue(layoutMethod, options); } internal T? RenderTypedValue(LogEventInfo logEvent, T? defaultValue = default(T?)) { return RenderTypedValue(logEvent, null, defaultValue); } internal T? RenderTypedValue(LogEventInfo logEvent, StringBuilder? stringBuilder, T? defaultValue) { if (IsFixed) { return _fixedValue; } if (logEvent == null) { return defaultValue; } if (logEvent.TryGetCachedLayoutValue(this, out object value)) { if (value != null) { return (T)value; } return defaultValue; } if (!IsInitialized) { Initialize(base.LoggingConfiguration ?? _layoutValue.LoggingConfiguration); } if (_layoutValue.TryRenderValue(logEvent, stringBuilder, out T value2)) { return value2; } return defaultValue; } private object? RenderObjectValue(LogEventInfo logEvent, StringBuilder? stringBuilder) { if (logEvent == null) { return null; } if (logEvent.TryGetCachedLayoutValue(this, out object value)) { return value; } return _layoutValue.RenderObjectValue(logEvent, stringBuilder); } protected override string GetFormattedMessage(LogEventInfo logEvent) { object obj = (IsFixed ? FixedObjectValue : RenderObjectValue(logEvent, null)); return FormatHelper.TryFormatToString(obj, null, CultureInfo.InvariantCulture) ?? obj?.ToString() ?? string.Empty; } protected override void InitializeLayout() { base.InitializeLayout(); _layoutValue.InitializeLayout(); base.ThreadAgnostic = _layoutValue.ThreadAgnostic; base.ThreadAgnosticImmutable = _layoutValue.ThreadAgnosticImmutable; base.StackTraceUsage = _layoutValue.StackTraceUsage; _valueTypeConverter = null; _fixedObjectValue = null; } protected override void CloseLayout() { _layoutValue.CloseLayout(); _valueTypeConverter = null; _fixedObjectValue = null; base.CloseLayout(); } public override void Precalculate(LogEventInfo logEvent) { PrecalculateInnerLayout(logEvent, null); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder? target) { PrecalculateInnerLayout(logEvent, target); } public static Layout FromMethod(Func layoutMethod, LayoutRenderOptions options = LayoutRenderOptions.None) { return new Layout(layoutMethod, options); } private void PrecalculateInnerLayout(LogEventInfo logEvent, StringBuilder? target) { if (!IsFixed && (!_layoutValue.ThreadAgnostic || _layoutValue.ThreadAgnosticImmutable)) { object value = RenderObjectValue(logEvent, target); logEvent.AddCachedLayoutValue(this, value); } } private bool TryParseFixedValue(Layout layout, string? parseValueFormat, CultureInfo? parseValueCulture, ref T? fixedValue) { if (layout is SimpleLayout simpleLayout && simpleLayout.IsFixedText) { if (simpleLayout.FixedText != null && !string.IsNullOrEmpty(simpleLayout.FixedText)) { try { fixedValue = (T)ParseValueFromObject(simpleLayout.FixedText, parseValueFormat, parseValueCulture); return true; } catch (Exception innerException) { NLogConfigurationException ex = new NLogConfigurationException($"Failed converting into type {typeof(T)}. Value='{simpleLayout.FixedText}'", innerException); if (ex.MustBeRethrown()) { throw ex; } } } else { if (typeof(T) == typeof(string)) { fixedValue = (T)(object)(simpleLayout.FixedText ?? string.Empty); return true; } if (Nullable.GetUnderlyingType(typeof(T)) != null) { fixedValue = default(T); return true; } } } else if (layout == null) { fixedValue = default(T); return true; } fixedValue = default(T); return false; } private object? ParseValueFromObject(object rawValue, string? parseValueFormat, CultureInfo? parseValueCulture) { return ValueTypeConverter.Convert(rawValue, typeof(T), parseValueFormat, parseValueCulture); } public override string ToString() { object obj; if (IsFixed) { obj = FixedObjectValue?.ToString() ?? "null"; } else { obj = _layoutValue.ToString(); if (obj == null) { return "null"; } } return (string)obj; } public override bool Equals(object? obj) { if (IsFixed) { if (obj is Layout layout) { if (layout.IsFixed) { return object.Equals(FixedObjectValue, layout.FixedObjectValue); } return false; } if (obj is T) { return object.Equals(FixedObjectValue, obj); } return obj == FixedObjectValue; } return this == obj; } public bool Equals(T? other) { if (IsFixed) { return object.Equals(FixedObjectValue, other); } return false; } public override int GetHashCode() { if (IsFixed) { return FixedObjectValue?.GetHashCode() ?? typeof(T).GetHashCode(); } return RuntimeHelpers.GetHashCode(this); } public static implicit operator Layout(T value) { return new Layout(value); } public static implicit operator Layout([Localizable(false)] string layout) { if (layout != null || typeof(T).IsValueType) { return new Layout(layout ?? string.Empty); } return new Layout(default(T)); } public static bool operator ==(Layout left, T right) { if (left == null || !left.Equals(right)) { if (left == null) { return object.Equals(right, default(T)); } return false; } return true; } public static bool operator !=(Layout left, T right) { if (left == null || !left.Equals(right)) { if (left == null) { return !object.Equals(right, default(T)); } return true; } return false; } } internal interface ILayoutTypeValue { Type? InnerType { get; } ILayoutTypeValue InnerLayout { get; } object? RenderObjectValue(LogEventInfo logEvent, StringBuilder? stringBuilder); } internal interface ILayoutTypeValue : ILayoutTypeValue { LoggingConfiguration? LoggingConfiguration { get; } bool ThreadAgnostic { get; } bool ThreadAgnosticImmutable { get; } StackTraceUsage StackTraceUsage { get; } void InitializeLayout(); void CloseLayout(); bool TryRenderValue(LogEventInfo logEvent, StringBuilder? stringBuilder, out T? value); } internal class LayoutTypeValue : ILayoutTypeValue, IPropertyTypeConverter { private readonly Layout _innerLayout; private readonly Type _valueType; private readonly CultureInfo? _parseValueCulture; private readonly string? _parseValueFormat; private string? _previousStringValue; private object? _previousValue; public LoggingConfiguration? LoggingConfiguration => _innerLayout.LoggingConfiguration; public bool ThreadAgnostic => _innerLayout.ThreadAgnostic; public bool ThreadAgnosticImmutable => _innerLayout.ThreadAgnosticImmutable; public StackTraceUsage StackTraceUsage => _innerLayout.StackTraceUsage; public virtual IPropertyTypeConverter ValueTypeConverter { get; } ILayoutTypeValue ILayoutTypeValue.InnerLayout => this; Type ILayoutTypeValue.InnerType => _valueType; public LayoutTypeValue(Layout layout, Type valueType, string? parseValueFormat, CultureInfo? parseValueCulture, IPropertyTypeConverter? valueTypeConverter) { _innerLayout = layout; _valueType = valueType; _parseValueFormat = parseValueFormat; _parseValueCulture = parseValueCulture; ValueTypeConverter = valueTypeConverter ?? this; } public object? TryParseFixedValue() { if (_innerLayout is SimpleLayout simpleLayout && simpleLayout.FixedText != null && TryParseValueFromString(simpleLayout.FixedText, out object parsedValue)) { return parsedValue; } return null; } protected void InitializeLayout(Layout ownerLayout) { _innerLayout.Initialize(ownerLayout.LoggingConfiguration ?? _innerLayout.LoggingConfiguration); _previousStringValue = null; _previousValue = null; } protected void Close() { _innerLayout.Close(); _previousStringValue = null; _previousValue = null; } public object? RenderObjectValue(LogEventInfo logEvent, StringBuilder? stringBuilder) { if (_innerLayout.TryGetRawValue(logEvent, out object rawValue)) { if (!(rawValue is string text)) { if (rawValue == null) { return null; } TryParseValueFromObject(rawValue, out object parsedValue); return parsedValue; } if (string.IsNullOrEmpty(text)) { TryParseValueFromString(text, out object parsedValue2); return parsedValue2; } } string previousStringValue = _previousStringValue; object previousValue = _previousValue; string text2 = RenderStringValue(logEvent, stringBuilder, previousStringValue); if (previousStringValue != null && previousStringValue == text2) { return previousValue; } if (TryParseValueFromString(text2, out object parsedValue3)) { if (string.IsNullOrEmpty(previousStringValue) || (text2 != null && text2.Length < 3)) { _previousValue = parsedValue3; _previousStringValue = text2; } return parsedValue3; } return null; } private string RenderStringValue(LogEventInfo logEvent, StringBuilder? stringBuilder, string? previousStringValue) { if (_innerLayout is IStringValueRenderer stringValueRenderer) { string formattedString = stringValueRenderer.GetFormattedString(logEvent); if (formattedString != null) { return formattedString; } } if (stringBuilder != null && stringBuilder.Length == 0) { _innerLayout.Render(logEvent, stringBuilder); if (stringBuilder.Length == 0) { return string.Empty; } if (previousStringValue == null || string.IsNullOrEmpty(previousStringValue) || !stringBuilder.EqualTo(previousStringValue)) { return stringBuilder.ToString(); } return previousStringValue; } return _innerLayout.Render(logEvent); } private bool TryParseValueFromObject(object rawValue, out object? parsedValue) { try { parsedValue = ParseValueFromObject(rawValue); return true; } catch (Exception ex) { parsedValue = null; InternalLogger.Warn(ex, "Failed converting object '{0}' of type {1} into type {2}", new ReadOnlySpan(new object[3] { rawValue, rawValue?.GetType(), _valueType })); return false; } } private object? ParseValueFromObject(object rawValue) { return ValueTypeConverter.Convert(rawValue, _valueType, _parseValueFormat, _parseValueCulture); } private bool TryParseValueFromString(string stringValue, out object? parsedValue) { if (string.IsNullOrEmpty(stringValue)) { parsedValue = ((_valueType == typeof(string)) ? stringValue : null); return true; } return TryParseValueFromObject(stringValue, out parsedValue); } public override string ToString() { return _innerLayout.ToString() ?? GetType().ToString(); } object? IPropertyTypeConverter.Convert(object? propertyValue, Type propertyType, string? format, IFormatProvider? formatProvider) { return null; } } [NLogConfigurationItem] public sealed class ValueTypeLayoutInfo { private sealed class FixedLayoutTypeValue : ILayoutTypeValue { private readonly object? _fixedValue; public ILayoutTypeValue InnerLayout => this; public Type? InnerType => _fixedValue?.GetType(); public FixedLayoutTypeValue(object fixedValue) { _fixedValue = fixedValue; } public object? RenderObjectValue(LogEventInfo logEvent, StringBuilder? stringBuilder) { return _fixedValue; } public override string ToString() { return _fixedValue?.ToString() ?? "null"; } } private sealed class StringLayoutTypeValue : ILayoutTypeValue { private readonly Layout _innerLayout; public ILayoutTypeValue InnerLayout => this; public Type InnerType => typeof(string); public StringLayoutTypeValue(Layout layout) { _innerLayout = layout; } public object RenderObjectValue(LogEventInfo logEvent, StringBuilder? stringBuilder) { return _innerLayout.Render(logEvent); } public override string ToString() { return _innerLayout.ToString() ?? GetType().ToString(); } } private static readonly Layout _fixedNullValue = new Layout(null); private Layout _layout = NLog.Layouts.Layout.Empty; private Type? _valueType; private Func? _createDefaultValue; private Layout? _defaultValue; private bool _useDefaultWhenEmptyString; private string? _valueParseFormat; private CultureInfo? _valueParseCulture; private ILayoutTypeValue? _layoutValue; private ILayoutTypeValue? _defaultLayoutValue; public Layout Layout { get { return _layout; } set { _layout = value ?? NLog.Layouts.Layout.Empty; if ((object)ValueType == null && _layout is ILayoutTypeValue layoutTypeValue) { ValueType = layoutTypeValue.InnerType; } SimpleStringValue = (((object)ValueType == null) ? ResolveStringValueMethod(_layout) : null); _layoutValue = null; } } internal INoAllocationStringValueRenderer? SimpleStringValue { get; private set; } public Type? ValueType { get { return _valueType; } [UnconditionalSuppressMessage("Trimming - Allow ValueType assign from config", "IL2067")] set { Type value2 = value; _valueType = value2; SimpleStringValue = (((object)_valueType == null || typeof(string).Equals(_valueType)) ? ResolveStringValueMethod(_layout) : null); Type type = value2; if ((object)type != null && type.IsValueType) { _createDefaultValue = () => Activator.CreateInstance(value2); } else { _createDefaultValue = null; } _layoutValue = null; _defaultLayoutValue = null; _useDefaultWhenEmptyString = UseDefaultWhenEmptyString(_valueType, _defaultValue); } } public Layout? DefaultValue { get { return _defaultValue; } set { _defaultValue = value; _defaultLayoutValue = null; _useDefaultWhenEmptyString = UseDefaultWhenEmptyString(_valueType, _defaultValue); } } public bool ForceDefaultValueNull { get { return DefaultValue == _fixedNullValue; } set { if (value) { DefaultValue = _fixedNullValue; } else if (DefaultValue == _fixedNullValue) { DefaultValue = null; } _useDefaultWhenEmptyString = UseDefaultWhenEmptyString(_valueType, _defaultValue); } } public string? ValueParseFormat { get { return _valueParseFormat; } set { _valueParseFormat = value; _layoutValue = null; _defaultLayoutValue = null; } } public CultureInfo? ValueParseCulture { get { return _valueParseCulture; } set { _valueParseCulture = value; _layoutValue = null; _defaultLayoutValue = null; } } private ILayoutTypeValue LayoutValue => _layoutValue ?? (_layoutValue = BuildLayoutTypeValue(Layout)); private ILayoutTypeValue DefaultLayoutValue => _defaultLayoutValue ?? (_defaultLayoutValue = BuildLayoutTypeValue(DefaultValue)); internal static INoAllocationStringValueRenderer? ResolveStringValueMethod(Layout layout) { INoAllocationStringValueRenderer noAllocationStringValueRenderer = ((layout is SimpleLayout simpleLayout && simpleLayout.LayoutRenderers.Count() == 1) ? (simpleLayout.LayoutRenderers.First() as INoAllocationStringValueRenderer) : null); if (noAllocationStringValueRenderer != null) { if (noAllocationStringValueRenderer.GetFormattedStringNoAllocation(LogEventInfo.CreateNullEvent()) != null) { return noAllocationStringValueRenderer; } return null; } return noAllocationStringValueRenderer; } private static bool UseDefaultWhenEmptyString(Type? valueType, Layout? defaultValue) { if (((object)valueType == null || typeof(string).Equals(valueType) || typeof(object).Equals(valueType)) && (defaultValue == null || (defaultValue is SimpleLayout simpleLayout && string.Empty.Equals(simpleLayout.Text)) || (defaultValue == _fixedNullValue && !typeof(object).Equals(valueType)))) { return false; } return true; } public object? RenderValue(LogEventInfo logEvent) { object obj = LayoutValue.RenderObjectValue(logEvent, null); if (obj == null || (_useDefaultWhenEmptyString && StringHelpers.IsNullOrEmptyString(obj))) { obj = DefaultLayoutValue.RenderObjectValue(logEvent, null); } return obj; } private ILayoutTypeValue BuildLayoutTypeValue(Layout? layout) { if (layout == null) { if (_createDefaultValue != null) { return new FixedLayoutTypeValue(_createDefaultValue()); } if ((object)ValueType == null || typeof(string).Equals(ValueType)) { return new FixedLayoutTypeValue(string.Empty); } layout = NLog.Layouts.Layout.Empty; } if (layout is ILayoutTypeValue layoutTypeValue) { return layoutTypeValue.InnerLayout; } if ((object)ValueType == null || typeof(string).Equals(ValueType)) { return new StringLayoutTypeValue(layout); } IPropertyTypeConverter valueTypeConverter = (layout.LoggingConfiguration?.LogFactory ?? LogManager.LogFactory).ServiceRepository.ResolveService(); LayoutTypeValue layoutTypeValue2 = new LayoutTypeValue(layout, ValueType, ValueParseFormat, ValueParseCulture, valueTypeConverter); object obj = layoutTypeValue2.TryParseFixedValue(); if (obj == null) { return layoutTypeValue2; } return new FixedLayoutTypeValue(obj); } } [NLogConfigurationItem] public class XmlAttribute { private readonly ValueTypeLayoutInfo _layoutInfo = new ValueTypeLayoutInfo(); private string _name = string.Empty; private bool _includeEmptyValue; public string Name { get { return _name; } set { _name = XmlHelper.XmlConvertToElementName(value?.Trim() ?? string.Empty); } } public Layout Layout { get { return _layoutInfo.Layout; } set { _layoutInfo.Layout = value; } } public Type? ValueType { get { return _layoutInfo.ValueType; } set { _layoutInfo.ValueType = value; } } public Layout? DefaultValue { get { return _layoutInfo.DefaultValue; } set { _layoutInfo.DefaultValue = value; } } public bool Encode { get; set; } public bool IncludeEmptyValue { get { return _includeEmptyValue; } set { _includeEmptyValue = value; _layoutInfo.ForceDefaultValueNull = !value; } } public XmlAttribute() : this(string.Empty, NLog.Layouts.Layout.Empty, encode: true) { } public XmlAttribute(string name, Layout layout) : this(name, layout, encode: true) { } public XmlAttribute(string name, Layout layout, bool encode) { Name = name; Layout = layout; Encode = encode; IncludeEmptyValue = false; } internal bool RenderAppendXmlValue(LogEventInfo logEvent, StringBuilder builder) { if (!Encode) { int length = builder.Length; Layout?.Render(logEvent, builder); if (!IncludeEmptyValue) { return builder.Length > length; } return true; } INoAllocationStringValueRenderer simpleStringValue = _layoutInfo.SimpleStringValue; if (simpleStringValue != null) { string formattedStringNoAllocation = simpleStringValue.GetFormattedStringNoAllocation(logEvent); if (formattedStringNoAllocation != null) { if (!IncludeEmptyValue && string.IsNullOrEmpty(formattedStringNoAllocation)) { return false; } XmlHelper.EscapeXmlWhenNeeded(formattedStringNoAllocation, xmlEncodeNewlines: true, builder); return true; } } if ((object)ValueType == null) { int length2 = builder.Length; Layout?.Render(logEvent, builder); if (!IncludeEmptyValue && builder.Length <= length2) { return false; } XmlHelper.EscapeXmlWhenNeeded(builder, length2, xmlEncodeNewlines: true); } else { object objectValue = _layoutInfo.RenderValue(logEvent); if (!IncludeEmptyValue && StringHelpers.IsNullOrEmptyString(objectValue)) { return false; } EscapeXmlWhenNeeded(objectValue, builder); } return true; } private static void EscapeXmlWhenNeeded(object? objectValue, StringBuilder builder) { IConvertible convertible = objectValue as IConvertible; TypeCode typeCode = (TypeCode)(((int?)convertible?.GetTypeCode()) ?? ((objectValue != null) ? 1 : 0)); if (typeCode != TypeCode.Object) { string text = XmlHelper.XmlConvertToString(convertible, typeCode, safeConversion: true); if (typeCode == TypeCode.String || typeCode == TypeCode.Char) { XmlHelper.EscapeXmlWhenNeeded(text, xmlEncodeNewlines: true, builder); } else { builder.Append(text); } } else { XmlHelper.EscapeXmlWhenNeeded(XmlHelper.XmlConvertToStringSafe(objectValue), xmlEncodeNewlines: true, builder); } } } [ThreadAgnostic] public class XmlElement : XmlElementBase { private const string DefaultElementName = "item"; public string Name { get { return base.ElementNameInternal; } set { base.ElementNameInternal = value; } } public Layout Value { get { return LayoutWrapper.Inner; } set { LayoutWrapper.Inner = value; } } public Layout Layout { get { return Value; } set { Value = value; } } public bool Encode { get { return LayoutWrapper.XmlEncode; } set { LayoutWrapper.XmlEncode = value; } } public bool CDataEncode { get { return LayoutWrapper.CDataEncode; } set { LayoutWrapper.CDataEncode = value; } } public XmlElement() : this("item", NLog.Layouts.Layout.Empty) { } public XmlElement(string elementName, Layout elementValue) : base(elementName, elementValue) { } } public abstract class XmlElementBase : Layout { private Layout[]? _precalculateLayouts; private const string DefaultPropertyName = "property"; private const string DefaultPropertyKeyAttribute = "key"; private const string DefaultCollectionItemName = "item"; private string _elementNameInternal = string.Empty; internal readonly XmlEncodeLayoutRendererWrapper LayoutWrapper = new XmlEncodeLayoutRendererWrapper(); private readonly List _elements = new List(); private readonly List _attributes = new List(); private bool? _includeScopeProperties; private bool? _includeMdc; private bool? _includeMdlc; private string _propertiesElementName = "property"; private bool _propertiesElementNameHasFormat; private ObjectReflectionCache? _objectReflectionCache; private const int MaxXmlLength = 524288; internal string ElementNameInternal { get { return _elementNameInternal; } set { _elementNameInternal = XmlHelper.XmlConvertToElementName(value?.Trim() ?? string.Empty); } } public bool IndentXml { get; set; } [ArrayParameter(typeof(XmlElement), "element")] public IList Elements => _elements; [ArrayParameter(typeof(XmlAttribute), "attribute")] public IList Attributes => _attributes; [ArrayParameter(typeof(TargetPropertyWithContext), "contextproperty")] public List? ContextProperties { get; set; } public bool IncludeEmptyValue { get; set; } public bool IncludeEventProperties { get; set; } public bool IncludeScopeProperties { get { bool? includeScopeProperties = _includeScopeProperties; if (!includeScopeProperties.HasValue) { if (!_includeMdlc.GetValueOrDefault()) { return _includeMdc.GetValueOrDefault(); } return true; } return includeScopeProperties.GetValueOrDefault(); } set { _includeScopeProperties = value; } } [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdc { get { return _includeMdc.GetValueOrDefault(); } set { _includeMdc = value; } } [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeMdlc { get { return _includeMdlc.GetValueOrDefault(); } set { _includeMdlc = value; } } [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IncludeAllProperties { get { return IncludeEventProperties; } set { IncludeEventProperties = value; } } public ISet ExcludeProperties { get; set; } public string PropertiesElementName { get { return _propertiesElementName; } set { _propertiesElementName = value; _propertiesElementNameHasFormat = value != null && value.IndexOf('{') >= 0; if (!_propertiesElementNameHasFormat) { _propertiesElementName = XmlHelper.XmlConvertToElementName(value?.Trim() ?? string.Empty); } } } public string PropertiesElementKeyAttribute { get; set; } = "key"; public string PropertiesElementValueAttribute { get; set; } = string.Empty; public string PropertiesCollectionItemName { get; set; } = "item"; public int MaxRecursionLimit { get; set; } = 1; private ObjectReflectionCache ObjectReflectionCache => _objectReflectionCache ?? (_objectReflectionCache = new ObjectReflectionCache(base.LoggingConfiguration.GetServiceProvider())); protected XmlElementBase(string elementName, Layout elementValue) { ElementNameInternal = elementName; LayoutWrapper.Inner = elementValue; ExcludeProperties = new HashSet(StringComparer.OrdinalIgnoreCase); } protected override void InitializeLayout() { base.InitializeLayout(); if (string.IsNullOrEmpty(ElementNameInternal)) { throw new NLogConfigurationException("XmlLayout Name-property must be assigned. Name is required for valid XML element."); } if (IncludeScopeProperties) { base.ThreadAgnostic = false; } if (IncludeEventProperties) { base.ThreadAgnosticImmutable = true; } if (_attributes.Count > 0) { HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (XmlAttribute attribute in _attributes) { if (string.IsNullOrEmpty(attribute.Name)) { throw new NLogConfigurationException("XmlElement(Name=" + ElementNameInternal + "): Contains invalid XmlAttribute with unassigned Name-property"); } if (hashSet.Contains(attribute.Name)) { InternalLogger.Warn("XmlElement(ElementName={0}): Contains duplicate XmlAttribute(Name={1}) (Invalid xml)", ElementNameInternal, attribute.Name); } else { hashSet.Add(attribute.Name); } } } if (ContextProperties != null) { foreach (TargetPropertyWithContext contextProperty in ContextProperties) { if (string.IsNullOrEmpty(contextProperty.Name)) { throw new NLogConfigurationException("XmlElement(Name=" + ElementNameInternal + "): Contains invalid ContextProperty with unassigned Name-property"); } } } Layout[] second = ((LayoutWrapper.Inner == null) ? ArrayHelper.Empty() : new Layout[1] { LayoutWrapper.Inner }); _precalculateLayouts = ((IncludeEventProperties || IncludeScopeProperties) ? null : ResolveLayoutPrecalculation(_attributes.Select((XmlAttribute atr) => atr.Layout).Concat(from elm in _elements where elm.Layout != null select elm.Layout).Concat(ContextProperties?.Select((TargetPropertyWithContext ctx) => ctx.Layout) ?? Enumerable.Empty()) .Concat(second))); } protected override void CloseLayout() { _precalculateLayouts = null; base.CloseLayout(); } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target, _precalculateLayouts); } protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { int length = target.Length; RenderXmlFormattedMessage(logEvent, target); if (target.Length == length && IncludeEmptyValue && !string.IsNullOrEmpty(ElementNameInternal)) { RenderSelfClosingElement(target, ElementNameInternal); } } protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } private void RenderXmlFormattedMessage(LogEventInfo logEvent, StringBuilder sb) { int length = sb.Length; if (!string.IsNullOrEmpty(ElementNameInternal)) { foreach (XmlAttribute attribute in _attributes) { int length2 = sb.Length; if (!RenderAppendXmlAttributeValue(attribute, logEvent, sb, sb.Length == length)) { sb.Length = length2; } } if (sb.Length != length) { if (!HasNestedXmlElements(logEvent)) { sb.Append("/>"); return; } sb.Append('>'); } if (LayoutWrapper.Inner != null) { int length3 = sb.Length; if (sb.Length == length) { RenderStartElement(sb, ElementNameInternal); } int length4 = sb.Length; LayoutWrapper.RenderAppendBuilder(logEvent, sb); if (length4 == sb.Length && !IncludeEmptyValue) { sb.Length = length3; } } if (IndentXml && sb.Length != length) { sb.AppendLine(); } } foreach (XmlElement element in _elements) { int length5 = sb.Length; if (!RenderAppendXmlElementValue(element, logEvent, sb, sb.Length == length)) { sb.Length = length5; } } AppendLogEventXmlProperties(logEvent, sb, length); if (sb.Length > length && !string.IsNullOrEmpty(ElementNameInternal)) { EndXmlDocument(sb, ElementNameInternal); } } private bool HasNestedXmlElements(LogEventInfo logEvent) { Layout inner = LayoutWrapper.Inner; if (inner != null && inner != Layout.Empty) { return true; } if (_elements.Count > 0) { return true; } List? contextProperties = ContextProperties; if (contextProperties != null && contextProperties.Count > 0) { return true; } if (IncludeScopeProperties) { return true; } if (IncludeEventProperties && logEvent.HasProperties) { return true; } return false; } private void AppendLogEventXmlProperties(LogEventInfo logEventInfo, StringBuilder sb, int orgLength) { if (ContextProperties != null) { foreach (TargetPropertyWithContext contextProperty in ContextProperties) { object obj = contextProperty.RenderValue(logEventInfo); if (contextProperty.IncludeEmptyValue || !StringHelpers.IsNullOrEmptyString(obj)) { AppendXmlPropertyValue(contextProperty.Name, obj, sb, orgLength); } } } if (IncludeScopeProperties) { bool flag = ExcludeProperties.Count > 0; using ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = ScopeContext.GetAllPropertiesEnumerator(); while (scopeContextPropertyEnumerator.MoveNext()) { KeyValuePair current2 = scopeContextPropertyEnumerator.Current; if (!string.IsNullOrEmpty(current2.Key) && (!flag || !ExcludeProperties.Contains(current2.Key))) { AppendXmlPropertyValue(current2.Key, current2.Value, sb, orgLength); } } } if (IncludeEventProperties) { AppendLogEventProperties(logEventInfo, sb, orgLength); } } private void AppendLogEventProperties(LogEventInfo logEventInfo, StringBuilder sb, int orgLength) { if (!logEventInfo.HasProperties) { return; } bool flag = ExcludeProperties.Count > 0; using PropertiesDictionary.PropertyDictionaryEnumerator propertyDictionaryEnumerator = logEventInfo.CreatePropertiesInternal().GetPropertyEnumerator(); while (propertyDictionaryEnumerator.MoveNext()) { MessageTemplateParameter currentParameter = propertyDictionaryEnumerator.CurrentParameter; if (!string.IsNullOrEmpty(currentParameter.Name) && (!flag || !ExcludeProperties.Contains(currentParameter.Name))) { object obj = currentParameter.Value; if (!string.IsNullOrEmpty(currentParameter.Format) && obj is IFormattable formattable) { obj = formattable.ToString(currentParameter.Format, CultureInfo.InvariantCulture); } else if (currentParameter.CaptureType == CaptureType.Stringify) { obj = Convert.ToString(currentParameter.Value ?? string.Empty, CultureInfo.InvariantCulture); } AppendXmlPropertyObjectValue(currentParameter.Name, obj, sb, orgLength, default(SingleItemOptimizedHashSet), 0); } } } private bool AppendXmlPropertyObjectValue(string propName, object? propertyValue, StringBuilder sb, int orgLength, SingleItemOptimizedHashSet objectsInPath, int depth, bool ignorePropertiesElementName = false) { if (propertyValue is IConvertible convertible) { TypeCode typeCode = convertible.GetTypeCode(); if (typeCode != TypeCode.Object) { string xmlValueString = XmlHelper.XmlConvertToString(convertible, typeCode, safeConversion: true); AppendXmlPropertyStringValue(propName, xmlValueString, sb, orgLength, ignoreValue: false, ignorePropertiesElementName); return true; } } else if (propertyValue == null) { string xmlValueString2 = XmlHelper.XmlConvertToString(null, TypeCode.Empty, safeConversion: true); AppendXmlPropertyStringValue(propName, xmlValueString2, sb, orgLength, ignoreValue: false, ignorePropertiesElementName); return true; } if (sb.Length > 524288) { return false; } int num = ((objectsInPath.Count == 0) ? depth : (depth + 1)); if (num > MaxRecursionLimit) { return false; } if (objectsInPath.Contains(propertyValue)) { return false; } if (MaxRecursionLimit == 0 || (num == MaxRecursionLimit && !(propertyValue is IEnumerable))) { string xmlValueString3 = XmlHelper.XmlConvertToStringSafe(propertyValue); AppendXmlPropertyStringValue(propName, xmlValueString3, sb, orgLength, ignoreValue: false, ignorePropertiesElementName); return true; } if (propertyValue is IDictionary dictionary) { using (StartCollectionScope(ref objectsInPath, dictionary)) { AppendXmlDictionaryObject(propName, dictionary, sb, orgLength, objectsInPath, num, ignorePropertiesElementName); } } else if (propertyValue is IEnumerable enumerable) { if (ObjectReflectionCache.TryLookupExpandoObject(propertyValue, out var objectPropertyList)) { using (new SingleItemOptimizedHashSet.SingleItemScopedInsert(propertyValue, ref objectsInPath, forceHashSet: false)) { AppendXmlObjectPropertyValues(propName, ref objectPropertyList, sb, orgLength, ref objectsInPath, num, ignorePropertiesElementName); } } else { using (StartCollectionScope(ref objectsInPath, enumerable)) { AppendXmlCollectionObject(propName, enumerable, sb, orgLength, objectsInPath, num, ignorePropertiesElementName); } } } else { using (new SingleItemOptimizedHashSet.SingleItemScopedInsert(propertyValue, ref objectsInPath, forceHashSet: false)) { ObjectReflectionCache.ObjectPropertyList propertyValues = ObjectReflectionCache.LookupObjectProperties(propertyValue); AppendXmlObjectPropertyValues(propName, ref propertyValues, sb, orgLength, ref objectsInPath, num, ignorePropertiesElementName); } } return true; } private static SingleItemOptimizedHashSet.SingleItemScopedInsert StartCollectionScope(ref SingleItemOptimizedHashSet objectsInPath, object value) { return new SingleItemOptimizedHashSet.SingleItemScopedInsert(value, ref objectsInPath, forceHashSet: true); } private void AppendXmlCollectionObject(string propName, IEnumerable collection, StringBuilder sb, int orgLength, SingleItemOptimizedHashSet objectsInPath, int depth, bool ignorePropertiesElementName) { string text = AppendXmlPropertyValue(propName, string.Empty, sb, orgLength, ignoreValue: true); if (string.IsNullOrEmpty(text)) { return; } foreach (object item in collection) { int length = sb.Length; if (length > 524288) { break; } if (!AppendXmlPropertyObjectValue(PropertiesCollectionItemName, item, sb, orgLength, objectsInPath, depth, ignorePropertiesElementName: true)) { sb.Length = length; } } AppendClosingPropertyTag(text, sb, ignorePropertiesElementName); } private void AppendXmlDictionaryObject(string propName, IDictionary dictionary, StringBuilder sb, int orgLength, SingleItemOptimizedHashSet objectsInPath, int depth, bool ignorePropertiesElementName) { string text = AppendXmlPropertyValue(propName, string.Empty, sb, orgLength, ignoreValue: true, ignorePropertiesElementName); if (string.IsNullOrEmpty(text)) { return; } foreach (DictionaryEntry item in new DictionaryEntryEnumerable(dictionary)) { int length = sb.Length; if (length > 524288) { break; } string text2 = item.Key?.ToString() ?? string.Empty; if (!string.IsNullOrEmpty(text2) && !AppendXmlPropertyObjectValue(text2, item.Value, sb, orgLength, objectsInPath, depth)) { sb.Length = length; } } AppendClosingPropertyTag(text, sb, ignorePropertiesElementName); } private void AppendXmlObjectPropertyValues(string propName, ref ObjectReflectionCache.ObjectPropertyList propertyValues, StringBuilder sb, int orgLength, ref SingleItemOptimizedHashSet objectsInPath, int depth, bool ignorePropertiesElementName = false) { if (propertyValues.IsSimpleValue) { AppendXmlPropertyValue(propName, propertyValues.ObjectValue, sb, orgLength, ignoreValue: false, ignorePropertiesElementName); return; } string text = AppendXmlPropertyValue(propName, string.Empty, sb, orgLength, ignoreValue: true, ignorePropertiesElementName); if (string.IsNullOrEmpty(text)) { return; } foreach (ObjectReflectionCache.ObjectPropertyList.PropertyValue propertyValue in propertyValues) { int length = sb.Length; if (length > 524288) { break; } if (!string.IsNullOrEmpty(propertyValue.Name) && (IncludeEmptyValue || !StringHelpers.IsNullOrEmptyString(propertyValue.Value))) { TypeCode typeCode = propertyValue.TypeCode; if (typeCode != TypeCode.Object) { string xmlValueString = XmlHelper.XmlConvertToString((IConvertible)propertyValue.Value, typeCode, safeConversion: true); AppendXmlPropertyStringValue(propertyValue.Name, xmlValueString, sb, orgLength, ignoreValue: false, ignorePropertiesElementName); } else if (!AppendXmlPropertyObjectValue(propertyValue.Name, propertyValue.Value, sb, orgLength, objectsInPath, depth)) { sb.Length = length; } } } AppendClosingPropertyTag(text, sb, ignorePropertiesElementName); } private string AppendXmlPropertyValue(string propName, object? propertyValue, StringBuilder sb, int orgLength, bool ignoreValue = false, bool ignorePropertiesElementName = false) { string xmlValueString = (ignoreValue ? string.Empty : XmlHelper.XmlConvertToStringSafe(propertyValue)); return AppendXmlPropertyStringValue(propName, xmlValueString, sb, orgLength, ignoreValue, ignorePropertiesElementName); } private string AppendXmlPropertyStringValue(string propName, string xmlValueString, StringBuilder sb, int orgLength, bool ignoreValue = false, bool ignorePropertiesElementName = false) { if (string.IsNullOrEmpty(PropertiesElementName)) { return string.Empty; } propName = propName?.Trim() ?? string.Empty; if (string.IsNullOrEmpty(propName)) { return string.Empty; } if (sb.Length == orgLength && !string.IsNullOrEmpty(ElementNameInternal)) { BeginXmlDocument(sb, ElementNameInternal); } if (IndentXml && !string.IsNullOrEmpty(ElementNameInternal)) { sb.Append(" "); } sb.Append('<'); string text; if (ignorePropertiesElementName) { text = XmlHelper.XmlConvertToElementName(propName); sb.Append(text); } else { if (_propertiesElementNameHasFormat) { text = XmlHelper.XmlConvertToElementName(propName); sb.AppendFormat(CultureInfo.InvariantCulture, PropertiesElementName, text); } else { text = PropertiesElementName; sb.Append(PropertiesElementName); } RenderAttribute(sb, PropertiesElementKeyAttribute, propName); } if (ignoreValue) { sb.Append('>'); if (IndentXml) { sb.AppendLine(); } } else if (RenderAttribute(sb, PropertiesElementValueAttribute, xmlValueString)) { sb.Append("/>"); if (IndentXml) { sb.AppendLine(); } } else { sb.Append('>'); XmlHelper.EscapeXmlWhenNeeded(xmlValueString, xmlEncodeNewlines: false, sb); AppendClosingPropertyTag(text, sb, ignorePropertiesElementName); } return text; } private void AppendClosingPropertyTag(string propNameElement, StringBuilder sb, bool ignorePropertiesElementName = false) { sb.Append("'); if (IndentXml) { sb.AppendLine(); } } private static bool RenderAttribute(StringBuilder sb, string attributeName, string value) { if (!string.IsNullOrEmpty(attributeName)) { sb.Append(' '); sb.Append(attributeName); sb.Append("=\""); XmlHelper.EscapeXmlWhenNeeded(value, xmlEncodeNewlines: true, sb); sb.Append('"'); return true; } return false; } private bool RenderAppendXmlElementValue(XmlElementBase xmlElement, LogEventInfo logEvent, StringBuilder sb, bool beginXmlDocument) { if (string.IsNullOrEmpty(xmlElement.ElementNameInternal)) { return false; } if (beginXmlDocument && !string.IsNullOrEmpty(ElementNameInternal)) { BeginXmlDocument(sb, ElementNameInternal); } if (IndentXml && !string.IsNullOrEmpty(ElementNameInternal)) { sb.Append(" "); } int length = sb.Length; xmlElement.Render(logEvent, sb); if (sb.Length == length && !xmlElement.IncludeEmptyValue) { return false; } if (IndentXml) { sb.AppendLine(); } return true; } private bool RenderAppendXmlAttributeValue(XmlAttribute xmlAttribute, LogEventInfo logEvent, StringBuilder sb, bool beginXmlDocument) { string name = xmlAttribute.Name; if (string.IsNullOrEmpty(name)) { return false; } if (beginXmlDocument) { sb.Append('<'); sb.Append(ElementNameInternal); } sb.Append(' '); sb.Append(name); sb.Append("=\""); if (!xmlAttribute.RenderAppendXmlValue(logEvent, sb)) { return false; } sb.Append('"'); return true; } private void BeginXmlDocument(StringBuilder sb, string elementName) { RenderStartElement(sb, elementName); if (IndentXml) { sb.AppendLine(); } } private void EndXmlDocument(StringBuilder sb, string elementName) { RenderEndElement(sb, elementName); } public override string ToString() { if (_elements.Count > 0) { return ToStringWithNestedItems(_elements, (XmlElement l) => (!string.IsNullOrEmpty(l.ElementNameInternal)) ? ("TagName=" + l.ElementNameInternal) : l.ToString()); } if (!string.IsNullOrEmpty(ElementNameInternal)) { return ToStringWithNestedItems(new XmlElementBase[1] { this }, (XmlElementBase l) => "TagName=" + l.ElementNameInternal); } if (_attributes.Count > 0) { return ToStringWithNestedItems(_attributes, (XmlAttribute a) => "Attribute=" + a.Name); } if (ContextProperties != null && ContextProperties.Count > 0) { return ToStringWithNestedItems(ContextProperties, (TargetPropertyWithContext n) => "Property=" + n.Name); } return GetType().Name; } private static void RenderSelfClosingElement(StringBuilder target, string elementName) { target.Append('<'); target.Append(elementName); target.Append("/>"); } private static void RenderStartElement(StringBuilder sb, string elementName) { sb.Append('<'); sb.Append(elementName); sb.Append('>'); } private static void RenderEndElement(StringBuilder sb, string elementName) { sb.Append("'); } } [Layout("XmlLayout")] [ThreadAgnostic] public class XmlLayout : XmlElementBase { private const string DefaultRootElementName = "logevent"; public string ElementName { get { return base.ElementNameInternal; } set { base.ElementNameInternal = value; } } public Layout ElementValue { get { return LayoutWrapper.Inner; } set { LayoutWrapper.Inner = value; } } public bool ElementEncode { get { return LayoutWrapper.XmlEncode; } set { LayoutWrapper.XmlEncode = value; } } public XmlLayout() : this("logevent", Layout.Empty) { } public XmlLayout(string elementName, Layout elementValue) : base(elementName, elementValue) { } } } namespace NLog.LayoutRenderers { [LayoutRenderer("all-event-properties")] [ThreadAgnostic] [ThreadAgnosticImmutable] public class AllEventPropertiesLayoutRenderer : LayoutRenderer { private string _format; private string? _beforeKey; private string? _afterKey; private string? _afterValue; private string _separator = ", "; private string _separatorOriginal = ", "; private static readonly LayoutRenderer _disableThreadAgnostic = new FuncLayoutRenderer(string.Empty, (LogEventInfo evt, LoggingConfiguration? cfg) => string.Empty); public string Separator { get { return _separatorOriginal ?? _separator; } set { _separatorOriginal = value; _separator = SimpleLayout.Evaluate(value, base.LoggingConfiguration, null, false); } } public bool IncludeEmptyValues { get; set; } public bool IncludeScopeProperties { get; set; } public ISet Exclude { get; set; } public LayoutRenderer? DisableThreadAgnostic { get { if (!IncludeScopeProperties) { return null; } return _disableThreadAgnostic; } } public string Format { get { return _format; } set { if (string.IsNullOrEmpty(value) || value.IndexOf("[key]", StringComparison.Ordinal) < 0) { throw new ArgumentException("Invalid format: [key] placeholder is missing."); } if (value.IndexOf("[value]", StringComparison.Ordinal) < 0) { throw new ArgumentException("Invalid format: [value] placeholder is missing."); } _format = value; string[] array = _format.Split(new string[2] { "[key]", "[value]" }, StringSplitOptions.None); if (array.Length == 3) { _beforeKey = array[0]; _afterKey = array[1]; _afterValue = array[2]; } else { _beforeKey = null; _afterKey = null; _afterValue = null; } } } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; public AllEventPropertiesLayoutRenderer() { _format = (Format = "[key]=[value]"); Exclude = new HashSet(StringComparer.OrdinalIgnoreCase); } protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if (_separatorOriginal != null) { _separator = SimpleLayout.Evaluate(_separatorOriginal, base.LoggingConfiguration); } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (!logEvent.HasProperties && !IncludeScopeProperties) { return; } IFormatProvider formatProvider = GetFormatProvider(logEvent, Culture); ISet exclude = Exclude; bool checkForExclude = exclude != null && exclude.Count > 0; bool nonStandardFormat = _beforeKey == null || _afterKey == null || _afterValue == null; bool includeSeparator = false; if (logEvent.HasProperties) { using PropertiesDictionary.PropertyDictionaryEnumerator propertyDictionaryEnumerator = logEvent.CreatePropertiesInternal().GetPropertyEnumerator(); while (propertyDictionaryEnumerator.MoveNext()) { MessageTemplateParameter currentParameter = propertyDictionaryEnumerator.CurrentParameter; if (AppendProperty(builder, currentParameter.Name, currentParameter.Value, currentParameter.Format, formatProvider, includeSeparator, checkForExclude, nonStandardFormat)) { includeSeparator = true; } } } if (!IncludeScopeProperties) { return; } using ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = ScopeContext.GetAllPropertiesEnumerator(); while (scopeContextPropertyEnumerator.MoveNext()) { KeyValuePair current = scopeContextPropertyEnumerator.Current; if (AppendProperty(builder, current.Key, current.Value, null, formatProvider, includeSeparator, checkForExclude, nonStandardFormat)) { includeSeparator = true; } } } private bool AppendProperty(StringBuilder builder, object propertyKey, object? propertyValue, string? propertyFormat, IFormatProvider? formatProvider, bool includeSeparator, bool checkForExclude, bool nonStandardFormat) { if (!IncludeEmptyValues && StringHelpers.IsNullOrEmptyString(propertyValue)) { return false; } if (checkForExclude && Exclude.Contains((propertyKey as string) ?? string.Empty)) { return false; } if (includeSeparator) { builder.Append(_separator); } if (nonStandardFormat) { string newValue = Convert.ToString(propertyKey, formatProvider); string newValue2 = Convert.ToString(propertyValue, formatProvider); string value = Format.Replace("[key]", newValue).Replace("[value]", newValue2); builder.Append(value); } else { builder.Append(_beforeKey); builder.AppendFormattedValue(propertyKey, null, formatProvider, base.ValueFormatter); builder.Append(_afterKey); builder.AppendFormattedValue(propertyValue, propertyFormat, formatProvider, base.ValueFormatter); builder.Append(_afterValue); } return true; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class AmbientPropertyAttribute : NameBaseAttribute { public AmbientPropertyAttribute(string name) : base(name) { } } [LayoutRenderer("appdomain")] [AppDomainFixedOutput] [ThreadAgnostic] public class AppDomainLayoutRenderer : LayoutRenderer { private const string ShortFormat = "{0:00}"; private const string LongFormat = "{0:0000}:{1}"; private const string FriendlyFormat = "{1}"; private const string LongFormatCode = "Long"; private const string ShortFormatCode = "Short"; private const string FriendlyFormatCode = "Friendly"; private readonly IAppEnvironment _currentAppEnvironment; private string? _assemblyName; [DefaultParameter] public string Format { get; set; } = "Long"; public AppDomainLayoutRenderer() : this(LogFactory.DefaultAppEnvironment) { } internal AppDomainLayoutRenderer(IAppEnvironment appEnvironment) { _currentAppEnvironment = appEnvironment; } protected override void InitializeLayoutRenderer() { _assemblyName = null; base.InitializeLayoutRenderer(); } protected override void CloseLayoutRenderer() { _assemblyName = null; base.CloseLayoutRenderer(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (_assemblyName == null) { string formattingString = GetFormattingString(Format); _assemblyName = string.Format(CultureInfo.InvariantCulture, formattingString, _currentAppEnvironment.AppDomainId, _currentAppEnvironment.AppDomainFriendlyName); } builder.Append(_assemblyName); } private static string GetFormattingString(string format) { if (string.Equals(format, "Long", StringComparison.OrdinalIgnoreCase)) { return "{0:0000}:{1}"; } if (string.Equals(format, "Short", StringComparison.OrdinalIgnoreCase)) { return "{0:00}"; } if (string.Equals(format, "Friendly", StringComparison.OrdinalIgnoreCase)) { return "{1}"; } return format; } } [LayoutRenderer("assembly-version")] [ThreadAgnostic] public class AssemblyVersionLayoutRenderer : LayoutRenderer { private string? _default; private string _format = "major.minor.build.revision"; private const string DefaultFormat = "major.minor.build.revision"; private string? _assemblyVersion; [DefaultParameter] public string Name { get; set; } = string.Empty; public AssemblyVersionType Type { get; set; } public string Default { get { return _default ?? GenerateDefaultValue(); } set { _default = value; } } public string Format { get { return _format; } set { _format = value?.ToLowerInvariant() ?? string.Empty; } } protected override void InitializeLayoutRenderer() { _assemblyVersion = null; base.InitializeLayoutRenderer(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string text = _assemblyVersion ?? (_assemblyVersion = ApplyFormatToVersion(GetVersion())); if (text == null) { text = GenerateDefaultValue(); } builder.Append(text); } private string ApplyFormatToVersion(string version) { if (version == null) { return Default; } if (StringHelpers.IsNullOrWhiteSpace(version)) { return Default; } if (version == "0.0.0.0" && _default != null) { return Default; } if (Format.Equals("major.minor.build.revision", StringComparison.OrdinalIgnoreCase)) { return version; } string[] array = version.SplitAndTrimTokens('.'); version = Format.Replace("major", array[0]).Replace("minor", (array.Length > 1) ? array[1] : "0").Replace("build", (array.Length > 2) ? array[2] : "0") .Replace("revision", (array.Length > 3) ? array[3] : "0"); return version; } private string GenerateDefaultValue() { return string.Format("Could not find value for {0} assembly and version type {1}", string.IsNullOrEmpty(Name) ? "entry" : Name, Type); } private string GetVersion() { try { Assembly assembly = GetAssembly(); return Type switch { AssemblyVersionType.File => assembly?.GetFirstCustomAttribute()?.Version ?? string.Empty, AssemblyVersionType.Informational => assembly?.GetFirstCustomAttribute()?.InformationalVersion ?? string.Empty, _ => assembly?.GetName()?.Version?.ToString() ?? string.Empty, }; } catch (Exception ex) { InternalLogger.Warn(ex, "${assembly-version} - Failed to load assembly {0}", new ReadOnlySpan(new object[1] { Name })); if (ex.MustBeRethrown()) { throw; } return string.Empty; } } protected virtual Assembly? GetAssembly() { if (string.IsNullOrEmpty(Name)) { return Assembly.GetEntryAssembly(); } return Assembly.Load(new AssemblyName(Name)); } } public enum AssemblyVersionType { Assembly, File, Informational } [LayoutRenderer("basedir")] [AppDomainFixedOutput] [ThreadAgnostic] public class BaseDirLayoutRenderer : LayoutRenderer { private readonly string _appDomainDirectory; private string _baseDir; private readonly IAppEnvironment _appEnvironment; public bool ProcessDir { get; set; } public bool FixTempDir { get; set; } public string File { get; set; } = string.Empty; public string Dir { get; set; } = string.Empty; public BaseDirLayoutRenderer() : this(LogFactory.DefaultAppEnvironment) { } internal BaseDirLayoutRenderer(IAppEnvironment appEnvironment) { _baseDir = (_appDomainDirectory = appEnvironment.AppDomainBaseDirectory); _appEnvironment = appEnvironment; } protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); _baseDir = _appDomainDirectory; if (ProcessDir) { string processDir = GetProcessDir(); if (!string.IsNullOrEmpty(processDir)) { _baseDir = processDir; } } else if (FixTempDir) { string fixedTempBaseDir = GetFixedTempBaseDir(_appDomainDirectory); if (!string.IsNullOrEmpty(fixedTempBaseDir)) { _baseDir = fixedTempBaseDir; } } _baseDir = AppEnvironmentWrapper.FixFilePathWithLongUNC(_baseDir); _baseDir = PathHelpers.CombinePaths(_baseDir, Dir, File); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(_baseDir); } private string GetFixedTempBaseDir(string baseDir) { try { string userTempFilePath = _appEnvironment.UserTempFilePath; if (PathHelpers.IsTempDir(baseDir, userTempFilePath)) { string processDir = GetProcessDir(); if (!string.IsNullOrEmpty(processDir) && !PathHelpers.IsTempDir(processDir, userTempFilePath)) { return processDir; } } return baseDir; } catch (Exception ex) { InternalLogger.Warn(ex, "BaseDir LayoutRenderer unexpected exception"); return baseDir; } } private string GetProcessDir() { return Path.GetDirectoryName(_appEnvironment.CurrentProcessFilePath) ?? string.Empty; } } [LayoutRenderer("callsite-filename")] [ThreadAgnostic] public class CallSiteFileNameLayoutRenderer : LayoutRenderer, IUsesStackTrace, IStringValueRenderer { public bool IncludeSourcePath { get; set; } = true; public int SkipFrames { get; set; } public bool CaptureStackTrace { get; set; } = true; StackTraceUsage IUsesStackTrace.StackTraceUsage => StackTraceUsageUtils.GetStackTraceUsage(includeFileName: true, SkipFrames, CaptureStackTrace); protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetStringValue(logEvent)); } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return GetStringValue(logEvent); } private string GetStringValue(LogEventInfo logEvent) { if (logEvent.CallSiteInformation != null) { string callerFilePath = logEvent.CallSiteInformation.GetCallerFilePath(SkipFrames); if (!string.IsNullOrEmpty(callerFilePath)) { if (!IncludeSourcePath) { return Path.GetFileName(callerFilePath); } return callerFilePath; } } return string.Empty; } } [LayoutRenderer("callsite")] [ThreadAgnostic] public class CallSiteLayoutRenderer : LayoutRenderer, IUsesStackTrace { public bool ClassName { get; set; } = true; public bool IncludeNamespace { get; set; } = true; public bool MethodName { get; set; } = true; [Obsolete("Should always be enabled. Marked obsolete with v6.1")] [EditorBrowsable(EditorBrowsableState.Never)] public bool CleanNamesOfAnonymousDelegates { get; set; } = true; [Obsolete("Should always be enabled. Marked obsolete with v6.1")] [EditorBrowsable(EditorBrowsableState.Never)] public bool CleanNamesOfAsyncContinuations { get; set; } = true; public int SkipFrames { get; set; } public bool FileName { get; set; } public bool IncludeSourcePath { get; set; } = true; public bool CaptureStackTrace { get; set; } = true; StackTraceUsage IUsesStackTrace.StackTraceUsage => StackTraceUsageUtils.GetStackTraceUsage(FileName, SkipFrames, CaptureStackTrace) | (ClassName ? StackTraceUsage.WithCallSiteClassName : StackTraceUsage.None); protected override void Append(StringBuilder builder, LogEventInfo logEvent) { CallSiteInformation callSiteInformation = logEvent.CallSiteInformation; if (callSiteInformation == null) { AppendExceptionCallSite(builder, logEvent); return; } if (ClassName || MethodName) { MethodBase callerStackFrameMethod = callSiteInformation.GetCallerStackFrameMethod(SkipFrames); if (ClassName) { string callerClassName = callSiteInformation.GetCallerClassName(callerStackFrameMethod, IncludeNamespace, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates); builder.Append(string.IsNullOrEmpty(callerClassName) ? "" : callerClassName); } if (MethodName) { string callerMethodName = callSiteInformation.GetCallerMethodName(callerStackFrameMethod, includeMethodInfo: false, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates); if (ClassName) { builder.Append('.'); } builder.Append(string.IsNullOrEmpty(callerMethodName) ? "" : callerMethodName); } } if (FileName) { string callerFilePath = callSiteInformation.GetCallerFilePath(SkipFrames); if (!string.IsNullOrEmpty(callerFilePath)) { int callerLineNumber = callSiteInformation.GetCallerLineNumber(SkipFrames); AppendFileName(builder, callerFilePath, callerLineNumber); } } } private void AppendFileName(StringBuilder builder, string fileName, int lineNumber) { builder.Append('('); if (IncludeSourcePath) { builder.Append(fileName); } else { builder.Append(Path.GetFileName(fileName)); } builder.Append(':'); builder.AppendInvariant(lineNumber); builder.Append(')'); } [UnconditionalSuppressMessage("Trimming - Allow callsite logic", "IL2026")] private void AppendExceptionCallSite(StringBuilder builder, LogEventInfo logEvent) { MethodBase methodBase = logEvent?.Exception?.TargetSite; if (methodBase != null) { if (ClassName) { string stackFrameMethodClassName = StackTraceUsageUtils.GetStackFrameMethodClassName(methodBase, includeNameSpace: true, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates); builder.Append(stackFrameMethodClassName); } if (MethodName) { if (ClassName) { builder.Append('.'); } string stackFrameMethodName = StackTraceUsageUtils.GetStackFrameMethodName(methodBase, includeMethodInfo: false, CleanNamesOfAsyncContinuations, CleanNamesOfAnonymousDelegates); builder.Append(stackFrameMethodName); } } else if (ClassName || FileName) { string value = logEvent?.Exception?.Source; builder.Append(value); } } } [LayoutRenderer("callsite-linenumber")] [ThreadAgnostic] public class CallSiteLineNumberLayoutRenderer : LayoutRenderer, IUsesStackTrace, IRawValue { public int SkipFrames { get; set; } public bool CaptureStackTrace { get; set; } = true; StackTraceUsage IUsesStackTrace.StackTraceUsage => StackTraceUsageUtils.GetStackTraceUsage(includeFileName: true, SkipFrames, CaptureStackTrace); protected override void Append(StringBuilder builder, LogEventInfo logEvent) { int? lineNumber = GetLineNumber(logEvent); if (lineNumber.HasValue) { builder.AppendInvariant(lineNumber.Value); } } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object? value) { value = GetLineNumber(logEvent); return true; } private int? GetLineNumber(LogEventInfo logEvent) { if (logEvent.CallSiteInformation == null) { return null; } return logEvent.CallSiteInformation.GetCallerLineNumber(SkipFrames); } } [LayoutRenderer("counter")] [ThreadAgnostic] public class CounterLayoutRenderer : LayoutRenderer, IRawValue { private sealed class GlobalSequence { private long _value; public string Name { get; } public GlobalSequence(string sequenceName, long initialValue) { Name = sequenceName; _value = initialValue; } public long NextValue(int increment) { return Interlocked.Add(ref _value, increment); } } private static readonly ConcurrentDictionary Sequences = new ConcurrentDictionary(StringComparer.Ordinal); private static GlobalSequence? _firstSequence; private long _value; public long Value { get { return _value; } set { _value = value; } } public int Increment { get; set; } = 1; public Layout? Sequence { get; set; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { long nextValue = GetNextValue(logEvent); builder.Append(nextValue); } private long GetNextValue(LogEventInfo logEvent) { if (Sequence == null) { return Interlocked.Add(ref _value, Increment); } string sequenceName = Sequence.Render(logEvent); return GetNextGlobalValue(sequenceName); } private long GetNextGlobalValue(string sequenceName) { GlobalSequence value = _firstSequence; if (value == null) { value = new GlobalSequence(sequenceName, Value); Interlocked.CompareExchange(ref _firstSequence, value, null); value = _firstSequence; } if (value.Name.Equals(sequenceName, StringComparison.Ordinal)) { return value.NextValue(Increment); } if (!Sequences.TryGetValue(sequenceName, out value)) { value = new GlobalSequence(sequenceName, Value); if (!Sequences.TryAdd(sequenceName, value)) { Sequences.TryGetValue(sequenceName, out value); } } return value.NextValue(Increment); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetNextValue(logEvent); return true; } } [LayoutRenderer("currentdir")] [ThreadAgnostic] public class CurrentDirLayoutRenderer : LayoutRenderer, IStringValueRenderer { public string File { get; set; } = string.Empty; public string Dir { get; set; } = string.Empty; protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetStringValue()); } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return GetStringValue(); } private string GetStringValue() { return PathHelpers.CombinePaths(Directory.GetCurrentDirectory(), Dir, File); } } [LayoutRenderer("date")] [ThreadAgnostic] public class DateLayoutRenderer : LayoutRenderer, IRawValue, IStringValueRenderer { private sealed class CachedDateFormatted { public readonly DateTime Date; public readonly string FormattedDate; public CachedDateFormatted(DateTime date, string formattedDate) { Date = date; FormattedDate = formattedDate; } } private string _format; private const string _lowTimeResolutionChars = "YyMDdHh"; private CachedDateFormatted? _cachedDateFormatted; private bool _utcRoundRoundTrip; private bool? _universalTime; public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; [DefaultParameter] public string Format { get { return _format; } set { _format = value; _cachedDateFormatted = (IsLowTimeResolutionLayout(_format) ? new CachedDateFormatted(DateTime.MaxValue, string.Empty) : null); _utcRoundRoundTrip = IsUtcRoundRountTripLayout(_format, _universalTime); } } public bool UniversalTime { get { return _universalTime.GetValueOrDefault(); } set { _universalTime = value; _utcRoundRoundTrip = IsUtcRoundRountTripLayout(_format, _universalTime); } } public DateLayoutRenderer() { _format = (Format = "yyyy/MM/dd HH:mm:ss.fff"); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { DateTime value = GetValue(logEvent); if (_utcRoundRoundTrip && value.Kind != DateTimeKind.Local) { builder.AppendXmlDateTimeUtcRoundTripFixed(value); return; } IFormatProvider formatProvider = GetFormatProvider(logEvent, Culture); builder.Append(GetStringValue(value, formatProvider)); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return GetStringValue(GetValue(logEvent), GetFormatProvider(logEvent, Culture)); } private string GetStringValue(DateTime timestamp, IFormatProvider? formatProvider) { CachedDateFormatted cachedDateFormatted = _cachedDateFormatted; if (formatProvider != CultureInfo.InvariantCulture) { cachedDateFormatted = null; } else if (cachedDateFormatted != null && cachedDateFormatted.Date == timestamp.Date.AddHours(timestamp.Hour)) { return cachedDateFormatted.FormattedDate; } string text = timestamp.ToString(_format, formatProvider); if (cachedDateFormatted != null) { _cachedDateFormatted = new CachedDateFormatted(timestamp.Date.AddHours(timestamp.Hour), text); } return text; } private DateTime GetValue(LogEventInfo logEvent) { DateTime result = logEvent.TimeStamp; if (_universalTime.HasValue) { result = (_universalTime.Value ? result.ToUniversalTime() : result.ToLocalTime()); } return result; } private static bool IsLowTimeResolutionLayout(string dateTimeFormat) { foreach (char c in dateTimeFormat) { if (char.IsLetter(c) && "YyMDdHh".IndexOf(c) < 0) { return false; } } return true; } private static bool IsUtcRoundRountTripLayout(string dateTimeFormat, bool? universalTime) { if (dateTimeFormat == "o" || dateTimeFormat == "O") { if (universalTime.HasValue) { return universalTime.Value; } return true; } return false; } } [LayoutRenderer("db-null")] [ThreadAgnostic] public class DbNullLayoutRenderer : LayoutRenderer, IRawValue { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = DBNull.Value; return true; } } [LayoutRenderer("dir-separator")] [ThreadAgnostic] [AppDomainFixedOutput] public class DirectorySeparatorLayoutRenderer : LayoutRenderer, IRawValue { private readonly char _separatorChar = Path.DirectorySeparatorChar; protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(_separatorChar); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = _separatorChar; return true; } } [LayoutRenderer("environment")] [ThreadAgnostic] public class EnvironmentLayoutRenderer : LayoutRenderer, IStringValueRenderer { private KeyValuePair _cachedValue; [DefaultParameter] public string Variable { get; set; } = string.Empty; public string Default { get; set; } = string.Empty; protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if (string.IsNullOrEmpty(Variable)) { throw new NLogConfigurationException("Environment-LayoutRenderer Variable-property must be assigned. Lookup blank value not supported."); } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { GetSimpleLayout()?.Render(logEvent, builder); } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { SimpleLayout simpleLayout = GetSimpleLayout(); if (simpleLayout == null) { return string.Empty; } if (simpleLayout.IsFixedText || simpleLayout.IsSimpleStringText) { return simpleLayout.Render(logEvent); } return null; } private SimpleLayout? GetSimpleLayout() { if (Variable != null) { string text = EnvironmentHelper.GetSafeEnvironmentVariable(Variable); if (string.IsNullOrEmpty(text)) { text = Default; } if (!string.IsNullOrEmpty(text)) { KeyValuePair keyValuePair = _cachedValue; if (string.CompareOrdinal(keyValuePair.Key, text) != 0) { keyValuePair = (_cachedValue = new KeyValuePair(text, new SimpleLayout(text))); } return keyValuePair.Value; } } return null; } } [LayoutRenderer("environment-user")] public class EnvironmentUserLayoutRenderer : LayoutRenderer, IStringValueRenderer { public bool UserName { get; set; } = true; public bool Domain { get; set; } public string DefaultUser { get; set; } = "UserUnknown"; public string DefaultDomain { get; set; } = "DomainUnknown"; protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetStringValue()); } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return GetStringValue(); } private string GetStringValue() { if (UserName) { if (!Domain) { return GetUserName(); } return GetDomainName() + "\\" + GetUserName(); } if (!Domain) { return string.Empty; } return GetDomainName(); } private string GetUserName() { return GetValueSafe(() => Environment.UserName, DefaultUser); } private string GetDomainName() { return GetValueSafe(() => Environment.UserDomainName, DefaultDomain); } private static string GetValueSafe(Func getValue, string defaultValue) { try { string text = getValue(); return string.IsNullOrEmpty(text) ? (defaultValue ?? string.Empty) : text; } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to lookup Environment-User. Fallback value={0}", new ReadOnlySpan(new object[1] { defaultValue })); return defaultValue ?? string.Empty; } } } [LayoutRenderer("event-properties")] [LayoutRenderer("event-property")] [LayoutRenderer("event-context")] [ThreadAgnostic] [ThreadAgnosticImmutable] public class EventPropertiesLayoutRenderer : LayoutRenderer, IRawValue, INoAllocationStringValueRenderer, IStringValueRenderer { private ObjectReflectionCache? _objectReflectionCache; private ObjectPropertyPath _objectPropertyPath; private object _item = string.Empty; private bool _ignoreCase = true; private ObjectReflectionCache ObjectReflectionCache => _objectReflectionCache ?? (_objectReflectionCache = new ObjectReflectionCache(base.LoggingConfiguration.GetServiceProvider())); [DefaultParameter] public string Item { get { return _item?.ToString() ?? string.Empty; } set { _item = ((value == null || !IgnoreCase) ? ((object)(value ?? string.Empty)) : ((object)new PropertiesDictionary.IgnoreCasePropertyKey(value))); } } public string? Format { get; set; } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; public string ObjectPath { get { return _objectPropertyPath.Value ?? string.Empty; } set { _objectPropertyPath.Value = value; } } public bool IgnoreCase { get { return _ignoreCase; } set { if (value != _ignoreCase) { _ignoreCase = value; Item = _item?.ToString() ?? string.Empty; } } } protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if (StringHelpers.IsNullOrEmptyString(_item)) { throw new NLogConfigurationException("EventProperty-LayoutRenderer Item-property must be assigned. Lookup blank value not supported."); } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (TryGetValue(logEvent, out object value)) { AppendFormattedValue(builder, logEvent, value, Format, Culture); } } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object? value) { TryGetValue(logEvent, out value); return true; } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { if (!"@".Equals(Format)) { if (TryGetValue(logEvent, out object value)) { return FormatHelper.TryFormatToString(value, Format, GetFormatProvider(logEvent, Culture)); } return string.Empty; } return null; } string? INoAllocationStringValueRenderer.GetFormattedStringNoAllocation(LogEventInfo logEvent) { if (Format == null) { if (TryGetValue(logEvent, out object value) && value != null) { return value as string; } return string.Empty; } return null; } private bool TryGetValue(LogEventInfo logEvent, out object? value) { value = null; if (!logEvent.HasProperties) { return false; } if (!logEvent.Properties.TryGetValue(_item, out value)) { return false; } if (_objectPropertyPath.PathNames != null) { if (ObjectReflectionCache.TryGetObjectProperty(value, _objectPropertyPath.PathNames, out object foundValue)) { value = foundValue; } else { value = null; } } return true; } } [LayoutRenderer("exceptiondata")] [ThreadAgnostic] [ThreadAgnosticImmutable] public class ExceptionDataLayoutRenderer : LayoutRenderer { [DefaultParameter] public string Item { get; set; } = string.Empty; public bool BaseException { get; set; } public string? Format { get; set; } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if (string.IsNullOrEmpty(Item)) { throw new NLogConfigurationException("ExceptionData-LayoutRenderer Item-property must be assigned. Lookup blank value not supported."); } } private Exception? GetTopException(LogEventInfo logEvent) { if (!BaseException) { return logEvent.Exception; } return logEvent.Exception?.GetBaseException(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Exception topException = GetTopException(logEvent); if (topException != null) { object obj = topException.Data[Item]; if (obj != null) { AppendFormattedValue(builder, logEvent, obj, Format, Culture); } } } } [LayoutRenderer("exception")] [ThreadAgnostic] public class ExceptionLayoutRenderer : LayoutRenderer, IRawValue { private static readonly Dictionary _formatsMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "MESSAGE", ExceptionRenderingFormat.Message }, { "TYPE", ExceptionRenderingFormat.Type }, { "SHORTTYPE", ExceptionRenderingFormat.ShortType }, { "TOSTRING", ExceptionRenderingFormat.ToString }, { "METHOD", ExceptionRenderingFormat.Method }, { "TARGETSITE", ExceptionRenderingFormat.Method }, { "SOURCE", ExceptionRenderingFormat.Source }, { "STACKTRACE", ExceptionRenderingFormat.StackTrace }, { "DATA", ExceptionRenderingFormat.Data }, { "@", ExceptionRenderingFormat.Serialize }, { "HRESULT", ExceptionRenderingFormat.HResult }, { "PROPERTIES", ExceptionRenderingFormat.Properties } }; private static readonly Dictionary> _renderingfunctions = new Dictionary> { { ExceptionRenderingFormat.Message, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendMessage(sb, ex); } }, { ExceptionRenderingFormat.Type, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendType(sb, ex); } }, { ExceptionRenderingFormat.ShortType, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendShortType(sb, ex); } }, { ExceptionRenderingFormat.ToString, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendToString(sb, ex); } }, { ExceptionRenderingFormat.Method, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendMethod(sb, ex); } }, { ExceptionRenderingFormat.Source, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendSource(sb, ex); } }, { ExceptionRenderingFormat.StackTrace, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendStackTrace(sb, ex); } }, { ExceptionRenderingFormat.Data, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendData(sb, ex, aggex); } }, { ExceptionRenderingFormat.Serialize, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendSerializeObject(sb, ex); } }, { ExceptionRenderingFormat.HResult, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendHResult(sb, ex); } }, { ExceptionRenderingFormat.Properties, delegate(ExceptionLayoutRenderer layout, StringBuilder sb, Exception ex, Exception? aggex) { layout.AppendProperties(sb, ex); } } }; private static readonly HashSet ExcludeDefaultProperties = new HashSet(new string[9] { "Type", "Data", "HelpLink", "HResult", "InnerException", "Message", "Source", "StackTrace", "TargetSite" }, StringComparer.Ordinal); private ObjectReflectionCache? _objectReflectionCache; private List _formats = new List(); private List? _innerFormats; private string _format; private string? _innerFormat; private string _separator = " "; private string _separatorOriginal = " "; private string _exceptionDataSeparator = ";"; private string _exceptionDataSeparatorOriginal = ";"; private ObjectReflectionCache ObjectReflectionCache => _objectReflectionCache ?? (_objectReflectionCache = new ObjectReflectionCache(base.LoggingConfiguration.GetServiceProvider())); [DefaultParameter] public string Format { get { return _format; } set { _format = value; _formats.Clear(); } } public string? InnerFormat { get { return _innerFormat; } set { _innerFormat = value; _innerFormats = null; } } public string Separator { get { return _separatorOriginal ?? _separator; } set { _separatorOriginal = value; _separator = SimpleLayout.Evaluate(value, base.LoggingConfiguration, null, false); } } public string ExceptionDataSeparator { get { return _exceptionDataSeparatorOriginal ?? _exceptionDataSeparator; } set { _exceptionDataSeparatorOriginal = value; _exceptionDataSeparator = SimpleLayout.Evaluate(value, base.LoggingConfiguration, null, false); } } public int MaxInnerExceptionLevel { get; set; } public string InnerExceptionSeparator { get; set; } = Environment.NewLine; public bool BaseException { get; set; } public bool FlattenException { get; set; } = true; public IEnumerable Formats => _formats; public ExceptionLayoutRenderer() { _format = "TOSTRING,DATA"; } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object? value) { value = GetTopException(logEvent); return true; } private Exception? GetTopException(LogEventInfo logEvent) { if (!BaseException) { return logEvent.Exception; } return logEvent.Exception?.GetBaseException(); } protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); _formats = CompileFormat(Format, "Format"); _innerFormats = ((InnerFormat == null) ? null : CompileFormat(InnerFormat, "InnerFormat")); if (_separatorOriginal != null) { _separator = SimpleLayout.Evaluate(_separatorOriginal, base.LoggingConfiguration); } if (_exceptionDataSeparatorOriginal != null) { _exceptionDataSeparator = SimpleLayout.Evaluate(_exceptionDataSeparatorOriginal, base.LoggingConfiguration); } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Exception topException = GetTopException(logEvent); if (topException == null) { return; } int num = 0; if (logEvent.Exception is AggregateException ex) { topException = (FlattenException ? GetPrimaryException(ex) : ex); AppendException(topException, _formats, builder, ex); if (num >= MaxInnerExceptionLevel) { return; } num = AppendInnerExceptionTree(topException, num, builder); if (num < MaxInnerExceptionLevel) { ReadOnlyCollection innerExceptions = ex.InnerExceptions; if (innerExceptions != null && innerExceptions.Count > 1) { AppendAggregateException(ex, num, builder); } } } else { AppendException(topException, _formats, builder); if (num < MaxInnerExceptionLevel) { AppendInnerExceptionTree(topException, num, builder); } } } private static Exception GetPrimaryException(AggregateException aggregateException) { if (aggregateException.InnerExceptions.Count == 1) { Exception ex = aggregateException.InnerExceptions[0]; if (!(ex is AggregateException)) { return ex; } } aggregateException = aggregateException.Flatten(); if (aggregateException.InnerExceptions.Count == 1) { return aggregateException.InnerExceptions[0]; } return aggregateException; } private void AppendAggregateException(AggregateException primaryException, int currentLevel, StringBuilder builder) { AggregateException ex = primaryException.Flatten(); if (ex.InnerExceptions == null) { return; } int num = 0; while (num < ex.InnerExceptions.Count && currentLevel < MaxInnerExceptionLevel) { Exception ex2 = ex.InnerExceptions[num]; if (ex2 != primaryException.InnerException) { if (ex2 == null) { InternalLogger.Debug("Skipping rendering exception as exception is null"); } else { AppendInnerException(ex2, builder); currentLevel++; currentLevel = AppendInnerExceptionTree(ex2, currentLevel, builder); } } num++; currentLevel++; } } private int AppendInnerExceptionTree(Exception currentException, int currentLevel, StringBuilder sb) { currentException = currentException.InnerException; while (currentException != null && currentLevel < MaxInnerExceptionLevel) { AppendInnerException(currentException, sb); currentLevel++; currentException = currentException.InnerException; } return currentLevel; } private void AppendInnerException(Exception currentException, StringBuilder builder) { builder.Append(InnerExceptionSeparator); AppendException(currentException, _innerFormats ?? _formats, builder); } private void AppendException(Exception currentException, List renderFormats, StringBuilder builder, Exception? aggregateException = null) { int length = builder.Length; foreach (ExceptionRenderingFormat renderFormat in renderFormats) { int length2 = builder.Length; _renderingfunctions[renderFormat](this, builder, currentException, aggregateException); if (builder.Length != length2) { length = builder.Length; builder.Append(_separator); } } builder.Length = length; } protected virtual void AppendMessage(StringBuilder sb, Exception ex) { try { sb.Append(ex.Message); } catch (Exception ex2) { InternalLogger.Warn(ex2, "Exception-LayoutRenderer Could not output Message for Exception: {0}", new ReadOnlySpan(new object[1] { ex.GetType() })); sb.Append(ex.GetType().ToString()); sb.Append(" Message-property threw "); sb.Append(ex2.GetType().ToString()); } } [UnconditionalSuppressMessage("Trimming - Allow callsite logic", "IL2026")] protected virtual void AppendMethod(StringBuilder sb, Exception ex) { try { sb.Append(ex.TargetSite?.ToString()); } catch (Exception ex2) { InternalLogger.Warn(ex2, "Exception-LayoutRenderer Could not output TargetSite for Exception: {0}", new ReadOnlySpan(new object[1] { ex.GetType() })); sb.Append(ex.GetType().ToString()); sb.Append(" TargetSite-property threw "); sb.Append(ex2.GetType().ToString()); } } protected virtual void AppendStackTrace(StringBuilder sb, Exception ex) { try { sb.Append(ex.StackTrace); } catch (Exception ex2) { InternalLogger.Warn(ex2, "Exception-LayoutRenderer Could not output StackTrace for Exception: {0}", new ReadOnlySpan(new object[1] { ex.GetType() })); sb.Append(ex.GetType().ToString()); sb.Append(" StackTrace-property threw "); sb.Append(ex2.GetType().ToString()); } } protected virtual void AppendToString(StringBuilder sb, Exception ex) { string arg = string.Empty; Exception ex2 = null; try { ex2 = ex.InnerException; arg = ex.Message; sb.Append(ex.ToString()); } catch (Exception ex3) { InternalLogger.Warn(ex3, "Exception-LayoutRenderer Could not output ToString for Exception: {0}", new ReadOnlySpan(new object[1] { ex.GetType() })); sb.Append($"{ex.GetType()}: {arg}"); if (ex2 != null) { sb.AppendLine(); AppendToString(sb, ex2); } } } protected virtual void AppendType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().ToString()); } protected virtual void AppendShortType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().Name); } protected virtual void AppendSource(StringBuilder sb, Exception ex) { try { sb.Append(ex.Source); } catch (Exception ex2) { InternalLogger.Warn(ex2, "Exception-LayoutRenderer Could not output Source for Exception: {0}", new ReadOnlySpan(new object[1] { ex.GetType() })); sb.Append(ex.GetType().ToString()); sb.Append(" Source-property threw "); sb.Append(ex2.GetType().ToString()); } } protected virtual void AppendHResult(StringBuilder sb, Exception ex) { if (ex.HResult != 0 && ex.HResult != 1) { sb.AppendFormat("0x{0:X8}", ex.HResult); } } private void AppendData(StringBuilder builder, Exception ex, Exception? aggregateException) { if (aggregateException != null && aggregateException.Data?.Count > 0 && ex != aggregateException) { AppendData(builder, aggregateException); builder.Append(_separator); } AppendData(builder, ex); } protected virtual void AppendData(StringBuilder sb, Exception ex) { IDictionary data = ex.Data; if (data == null || data.Count <= 0) { return; } string value = string.Empty; foreach (object key in ex.Data.Keys) { sb.Append(value); try { sb.AppendFormat("{0}: ", key); value = _exceptionDataSeparator; sb.AppendFormat("{0}", ex.Data[key]); } catch (Exception ex2) { InternalLogger.Warn(ex2, "Exception-LayoutRenderer Could not output Data-collection for Exception: {0}", new ReadOnlySpan(new object[1] { ex.GetType() })); } } } protected virtual void AppendSerializeObject(StringBuilder sb, Exception ex) { base.ValueFormatter.FormatValue(ex, null, CaptureType.Serialize, null, sb); } protected virtual void AppendProperties(StringBuilder sb, Exception ex) { string value = string.Empty; foreach (ObjectReflectionCache.ObjectPropertyList.PropertyValue item in ObjectReflectionCache.LookupObjectProperties(ex)) { if (ExcludeDefaultProperties.Contains(item.Name)) { continue; } try { string text = item.Value?.ToString(); if (!string.IsNullOrEmpty(text)) { sb.Append(value); sb.Append(item.Name); value = _exceptionDataSeparator; sb.Append(": "); sb.AppendFormat("{0}", text); } } catch (Exception ex2) { InternalLogger.Warn(ex2, "Exception-LayoutRenderer Could not output Property-collection for Exception: {0}", new ReadOnlySpan(new object[1] { ex.GetType() })); } } } private List CompileFormat(string formatSpecifier, string propertyName) { List list = new List(); string[] array = formatSpecifier.SplitAndTrimTokens(','); foreach (string text in array) { if (_formatsMapping.TryGetValue(text, out var value)) { list.Add(value); continue; } NLogConfigurationException ex = new NLogConfigurationException("Exception-LayoutRenderer assigned unknown " + propertyName + ": " + text); if (ex.MustBeRethrown() || (base.LoggingConfiguration?.LogFactory?.ThrowConfigExceptions ?? base.LoggingConfiguration?.LogFactory?.ThrowExceptions).GetValueOrDefault()) { throw ex; } } return list; } } public class FuncLayoutRenderer : LayoutRenderer, IStringValueRenderer { private readonly Func _renderMethod; public string LayoutRendererName { get; } [Obsolete("Public API-property was a mistake. Marked obsolete with NLog v6.0")] [EditorBrowsable(EditorBrowsableState.Never)] public Func RenderMethod => _renderMethod; public string? Format { get; set; } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected FuncLayoutRenderer(string layoutRendererName) { LayoutRendererName = layoutRendererName; _renderMethod = (LogEventInfo evt, LoggingConfiguration? cfg) => string.Empty; } public FuncLayoutRenderer(string layoutRendererName, Func renderMethod) { _renderMethod = Guard.ThrowIfNull(renderMethod, "renderMethod"); LayoutRendererName = layoutRendererName; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object value = RenderValue(logEvent); AppendFormattedValue(builder, logEvent, value, Format, Culture); } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { if (!"@".Equals(Format)) { return FormatHelper.TryFormatToString(RenderValue(logEvent), Format, GetFormatProvider(logEvent, Culture)); } return null; } protected virtual object? RenderValue(LogEventInfo logEvent) { return _renderMethod(logEvent, base.LoggingConfiguration); } } [ThreadAgnostic] internal sealed class FuncThreadAgnosticLayoutRenderer : FuncLayoutRenderer, IRawValue { public FuncThreadAgnosticLayoutRenderer(string layoutRendererName, Func renderMethod) : base(layoutRendererName, renderMethod) { } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object? value) { value = RenderValue(logEvent); return true; } } [LayoutRenderer("gc")] public class GarbageCollectorInfoLayoutRenderer : LayoutRenderer { public GarbageCollectorProperty Property { get; set; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { long value = GetValue(); if (value >= 0 && value < uint.MaxValue) { builder.AppendInvariant((uint)value); } else { builder.Append(value); } } private long GetValue() { long result = 0L; switch (Property) { case GarbageCollectorProperty.TotalMemory: result = GC.GetTotalMemory(forceFullCollection: false); break; case GarbageCollectorProperty.TotalMemoryForceCollection: result = GC.GetTotalMemory(forceFullCollection: true); break; case GarbageCollectorProperty.CollectionCount0: result = GC.CollectionCount(0); break; case GarbageCollectorProperty.CollectionCount1: result = GC.CollectionCount(1); break; case GarbageCollectorProperty.CollectionCount2: result = GC.CollectionCount(2); break; case GarbageCollectorProperty.MaxGeneration: result = GC.MaxGeneration; break; } return result; } } public enum GarbageCollectorProperty { TotalMemory, TotalMemoryForceCollection, CollectionCount0, CollectionCount1, CollectionCount2, MaxGeneration } [LayoutRenderer("gdc")] [ThreadAgnostic] public class GdcLayoutRenderer : LayoutRenderer, IRawValue, INoAllocationStringValueRenderer, IStringValueRenderer { private sealed class CachedLookup { internal readonly object CachedDictionary; internal readonly object? CachedItemValue; public CachedLookup(object cachedDictionary, object? cachedItemValue) { CachedDictionary = cachedDictionary; CachedItemValue = cachedItemValue; } } private CachedLookup _cachedLookup = new CachedLookup(string.Empty, null); [DefaultParameter] public string Item { get; set; } = string.Empty; public string? Format { get; set; } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if (string.IsNullOrEmpty(Item)) { throw new NLogConfigurationException("Gdc-LayoutRenderer Item-property must be assigned. Lookup blank value not supported."); } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object value = GetValue(); if (value != null || !string.IsNullOrEmpty(Format)) { AppendFormattedValue(builder, logEvent, value, Format, Culture); } } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object? value) { value = GetValue(); return true; } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { if (!"@".Equals(Format)) { return FormatHelper.TryFormatToString(GetValue(), Format, GetFormatProvider(logEvent, Culture)); } return null; } string? INoAllocationStringValueRenderer.GetFormattedStringNoAllocation(LogEventInfo logEvent) { if (Format != null) { return null; } return GetValue() as string; } private object? GetValue() { CachedLookup cachedLookup = _cachedLookup; Dictionary readOnlyDict = GlobalDiagnosticsContext.GetReadOnlyDict(); if (cachedLookup.CachedDictionary == readOnlyDict) { return cachedLookup.CachedItemValue; } readOnlyDict.TryGetValue(Item, out var value); _cachedLookup = new CachedLookup(readOnlyDict, value); return value; } } [LayoutRenderer("guid")] [ThreadAgnostic] public class GuidLayoutRenderer : LayoutRenderer, IRawValue, IStringValueRenderer { public string Format { get; set; } = "N"; public bool GeneratedFromLogEvent { get; set; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetStringValue(logEvent)); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return GetStringValue(logEvent); } private string GetStringValue(LogEventInfo logEvent) { return GetValue(logEvent).ToString(Format); } private Guid GetValue(LogEventInfo logEvent) { if (GeneratedFromLogEvent) { int hashCode = logEvent.GetHashCode(); short b = (short)((hashCode >> 16) & 0xFFFF); short c = (short)(hashCode & 0xFFFF); long ticks = LogEventInfo.ZeroDate.Ticks; byte d = (byte)((ticks >> 56) & 0xFF); byte e = (byte)((ticks >> 48) & 0xFF); byte f = (byte)((ticks >> 40) & 0xFF); byte g = (byte)((ticks >> 32) & 0xFF); byte h = (byte)((ticks >> 24) & 0xFF); byte i = (byte)((ticks >> 16) & 0xFF); byte j = (byte)((ticks >> 8) & 0xFF); byte k = (byte)(ticks & 0xFF); return new Guid(logEvent.SequenceID, b, c, d, e, f, g, h, i, j, k); } return Guid.NewGuid(); } } [LayoutRenderer("hostname")] [AppDomainFixedOutput] [ThreadAgnostic] public class HostNameLayoutRenderer : LayoutRenderer { private string? _hostName; protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); try { _hostName = GetHostName(); if (string.IsNullOrEmpty(_hostName)) { InternalLogger.Info("HostName is not available."); } } catch (Exception ex) { InternalLogger.Error(ex, "Error getting host name."); if (ex.MustBeRethrown()) { throw; } _hostName = string.Empty; } } private static string GetHostName() { return TryLookupValue(() => Environment.GetEnvironmentVariable("HOSTNAME"), "HOSTNAME") ?? TryLookupValue(() => Environment.GetEnvironmentVariable("COMPUTERNAME"), "COMPUTERNAME") ?? TryLookupValue(() => Environment.GetEnvironmentVariable("MACHINENAME"), "MACHINENAME") ?? TryLookupValue(() => Environment.MachineName, "MachineName") ?? string.Empty; } private static string? TryLookupValue(Func lookupFunc, string lookupType) { try { string text = lookupFunc()?.Trim(); return string.IsNullOrEmpty(text) ? null : text; } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to lookup {0}", new ReadOnlySpan(new object[1] { lookupType })); return null; } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(_hostName); } } [LayoutRenderer("identity")] public class IdentityLayoutRenderer : LayoutRenderer { public string Separator { get; set; } = ":"; public bool Name { get; set; } = true; public bool AuthType { get; set; } = true; public bool IsAuthenticated { get; set; } = true; protected override void Append(StringBuilder builder, LogEventInfo logEvent) { IIdentity value = GetValue(); if (value != null) { string value2 = string.Empty; if (IsAuthenticated) { builder.Append(value2); value2 = Separator; builder.Append(value.IsAuthenticated ? "auth" : "notauth"); } if (AuthType) { builder.Append(value2); value2 = Separator; builder.Append(value.AuthenticationType); } if (Name) { builder.Append(value2); builder.Append(value.Name); } } } private static IIdentity? GetValue() { return Thread.CurrentPrincipal?.Identity; } } [LayoutRenderer("install-context")] public class InstallContextLayoutRenderer : LayoutRenderer { [DefaultParameter] public string Parameter { get; set; } = string.Empty; protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object value = GetValue(logEvent); if (value != null) { IFormatProvider formatProvider = GetFormatProvider(logEvent); builder.Append(Convert.ToString(value, formatProvider)); } } private object? GetValue(LogEventInfo logEvent) { if (logEvent.Properties.TryGetValue(Parameter, out object value)) { return value; } return null; } } [NLogConfigurationItem] public abstract class LayoutRenderer : ISupportsInitialize, IRenderable { private bool _isInitialized; private IValueFormatter? _valueFormatter; protected LoggingConfiguration? LoggingConfiguration { get; private set; } protected IValueFormatter ValueFormatter => _valueFormatter ?? (_valueFormatter = ResolveService()); public override string ToString() { LayoutRendererAttribute firstCustomAttribute = GetType().GetFirstCustomAttribute(); if (firstCustomAttribute != null) { return "Layout Renderer: ${" + firstCustomAttribute.Name + "}"; } return GetType().Name; } public string Render(LogEventInfo logEvent) { using AppendBuilderCreator appendBuilderCreator = new AppendBuilderCreator(mustBeEmpty: true); RenderAppendBuilder(logEvent, appendBuilderCreator.Builder); return appendBuilderCreator.Builder.ToString(); } void ISupportsInitialize.Initialize(LoggingConfiguration? configuration) { Initialize(configuration); } void ISupportsInitialize.Close() { Close(); } internal void Initialize(LoggingConfiguration? configuration) { if (LoggingConfiguration == null) { LoggingConfiguration = configuration; } if (!_isInitialized) { Initialize(); } } private void Initialize() { try { InitializeLayoutRenderer(); } catch (Exception ex) { InternalLogger.Error(ex, "Exception in layout renderer initialization."); if (ex.MustBeRethrown()) { throw; } } finally { _isInitialized = true; } } internal void Close() { if (_isInitialized) { LoggingConfiguration = null; _valueFormatter = null; _isInitialized = false; CloseLayoutRenderer(); } } internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder builder) { try { if (!_isInitialized) { Initialize(); } Append(builder, logEvent); } catch (Exception ex) { InternalLogger.Warn(ex, "Exception in '{0}.Append()'", new ReadOnlySpan(new object[1] { GetType() })); if (ex.MustBeRethrown()) { throw; } } } protected abstract void Append(StringBuilder builder, LogEventInfo logEvent); internal void AppendFormattedValue(StringBuilder builder, LogEventInfo logEvent, object? value, string? format, CultureInfo? culture) { if (format == null && value is string value2) { builder.Append(value2); return; } IFormatProvider formatProvider = GetFormatProvider(logEvent, culture); builder.AppendFormattedValue(value, format, formatProvider, ValueFormatter); } protected virtual void InitializeLayoutRenderer() { } protected virtual void CloseLayoutRenderer() { } protected IFormatProvider? GetFormatProvider(LogEventInfo logEvent, IFormatProvider? layoutCulture = null) { object obj = layoutCulture; if (obj == null) { obj = logEvent.FormatProvider; if (obj == null) { LoggingConfiguration? loggingConfiguration = LoggingConfiguration; if (loggingConfiguration == null) { return null; } obj = loggingConfiguration.DefaultCultureInfo; } } return (IFormatProvider?)obj; } protected CultureInfo GetCulture(LogEventInfo logEvent, CultureInfo? layoutCulture = null) { return layoutCulture ?? (logEvent.FormatProvider as CultureInfo) ?? LoggingConfiguration?.DefaultCultureInfo ?? CultureInfo.CurrentCulture; } [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Register<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name) where T : LayoutRenderer { Type typeFromHandle = typeof(T); Register(name, typeFromHandle); } [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Register(string name, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type layoutRendererType) { Guard.ThrowIfNull(layoutRendererType, "layoutRendererType"); Guard.ThrowIfNullOrEmpty(name, "name"); ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterDefinition(name, layoutRendererType); } [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Register(string name, Func func) { Func func2 = func; Guard.ThrowIfNull(func2, "func"); Register(name, (LogEventInfo info, LoggingConfiguration? configuration) => func2(info)); } [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Register(string name, Func func) { Guard.ThrowIfNull(func, "func"); Register(new FuncLayoutRenderer(name, func)); } [Obsolete("Instead use LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Register(FuncLayoutRenderer layoutRenderer) { Guard.ThrowIfNull(layoutRenderer, "layoutRenderer"); ConfigurationItemFactory.Default.GetLayoutRendererFactory().RegisterFuncLayout(layoutRenderer.LayoutRendererName, layoutRenderer); } protected T ResolveService() where T : class { return LoggingConfiguration.GetServiceProvider().ResolveService(_isInitialized); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class LayoutRendererAttribute : NameBaseAttribute { public LayoutRendererAttribute(string name) : base(name) { } } public enum LevelFormat { Name = 0, FirstCharacter = 1, OneLetter = 1, Ordinal = 2, FullName = 3, TriLetter = 4 } [LayoutRenderer("level")] [LayoutRenderer("loglevel")] [ThreadAgnostic] public class LevelLayoutRenderer : LayoutRenderer, IRawValue, INoAllocationStringValueRenderer, IStringValueRenderer { private static readonly string[] _defaultNames = GenerateLevelNames(LevelFormat.Name, upperCase: false); private static readonly string[] _defaultUppercaseNames = GenerateLevelNames(LevelFormat.Name, upperCase: true); private string[] _levelNames = _defaultNames; private LevelFormat _format; private bool _uppercase; public LevelFormat Format { get { return _format; } set { if (_format != value) { _format = value; _levelNames = GenerateLevelNames(_format, _uppercase); } } } public bool Uppercase { get { return _uppercase; } set { if (_uppercase != value) { _uppercase = value; if (_format == LevelFormat.Name) { _levelNames = (_uppercase ? _defaultUppercaseNames : _defaultNames); } else { _levelNames = GenerateLevelNames(_format, _uppercase); } } } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetLogLevelStringValue(logEvent)); } private string GetLogLevelStringValue(LogEventInfo logEvent) { LogLevel logLevel = GetValue(logEvent) ?? LogLevel.Trace; int ordinal = logLevel.Ordinal; if (ordinal < 0 || ordinal >= _levelNames.Length) { return GetFormattedLevelName(logLevel, _format, _uppercase); } return _levelNames[ordinal]; } private static string[] GenerateLevelNames(LevelFormat format, bool upperCase) { string[] array = new string[LogLevel.MaxLevel.Ordinal + 2]; array[LogLevel.Trace.Ordinal] = GetFormattedLevelName(LogLevel.Trace, format, upperCase); array[LogLevel.Debug.Ordinal] = GetFormattedLevelName(LogLevel.Debug, format, upperCase); array[LogLevel.Info.Ordinal] = GetFormattedLevelName(LogLevel.Info, format, upperCase); array[LogLevel.Warn.Ordinal] = GetFormattedLevelName(LogLevel.Warn, format, upperCase); array[LogLevel.Error.Ordinal] = GetFormattedLevelName(LogLevel.Error, format, upperCase); array[LogLevel.Fatal.Ordinal] = GetFormattedLevelName(LogLevel.Fatal, format, upperCase); array[LogLevel.Off.Ordinal] = GetFormattedLevelName(LogLevel.Off, format, upperCase); return array; } private static string GetFormattedLevelName(LogLevel logLevel, LevelFormat format, bool upperCase) { switch (format) { case LevelFormat.FirstCharacter: return logLevel.ToString()[0].ToString(); case LevelFormat.Ordinal: return logLevel.Ordinal.ToString(); case LevelFormat.FullName: if (!upperCase) { return GetFullNameString(logLevel); } return GetFullNameString(logLevel).ToUpperInvariant(); case LevelFormat.TriLetter: if (!upperCase) { return GetTriLetterString(logLevel); } return GetTriLetterString(logLevel).ToUpperInvariant(); default: if (!upperCase) { return logLevel.ToString(); } return logLevel.ToString().ToUpperInvariant(); } } private static string GetFullNameString(LogLevel logLevel) { if (logLevel == LogLevel.Info) { return "Information"; } if (logLevel == LogLevel.Warn) { return "Warning"; } return logLevel.ToString(); } private static string GetTriLetterString(LogLevel level) { if (level == LogLevel.Trace) { return "Trc"; } if (level == LogLevel.Debug) { return "Dbg"; } if (level == LogLevel.Info) { return "Inf"; } if (level == LogLevel.Warn) { return "Wrn"; } if (level == LogLevel.Error) { return "Err"; } if (level == LogLevel.Fatal) { return "Ftl"; } return level.ToString(); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return GetLogLevelStringValue(logEvent); } string? INoAllocationStringValueRenderer.GetFormattedStringNoAllocation(LogEventInfo logEvent) { return GetLogLevelStringValue(logEvent); } private static LogLevel GetValue(LogEventInfo logEvent) { return logEvent.Level; } } [LayoutRenderer("literal")] [ThreadAgnostic] [AppDomainFixedOutput] public class LiteralLayoutRenderer : LayoutRenderer, INoAllocationStringValueRenderer, IStringValueRenderer { [DefaultParameter] public string Text { get; set; } = string.Empty; public LiteralLayoutRenderer() { } public LiteralLayoutRenderer(string text) { Text = text; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(Text); } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return Text; } string? INoAllocationStringValueRenderer.GetFormattedStringNoAllocation(LogEventInfo logEvent) { return Text; } } [ThreadAgnostic] [AppDomainFixedOutput] internal sealed class LiteralWithRawValueLayoutRenderer : LiteralLayoutRenderer, IRawValue { private readonly object? _rawValue; public LiteralWithRawValueLayoutRenderer(string text, object? rawValue) : base(text) { _rawValue = rawValue; } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object? value) { value = _rawValue; return true; } } [LayoutRenderer("loggername")] [LayoutRenderer("logger")] [ThreadAgnostic] public class LoggerNameLayoutRenderer : LayoutRenderer, INoAllocationStringValueRenderer, IStringValueRenderer { public bool ShortName { get; set; } public bool PrefixName { get; set; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string loggerName = logEvent.LoggerName; if (ShortName) { int num = TryGetLastDotForShortName(loggerName); if (num >= 0) { builder.Append(loggerName, num + 1, loggerName.Length - num - 1); return; } } else if (PrefixName) { int num2 = TryGetLastDotForShortName(loggerName); if (num2 > 0) { builder.Append(loggerName, 0, num2); return; } } builder.Append(loggerName); } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { string loggerName = logEvent.LoggerName; if (ShortName) { int num = TryGetLastDotForShortName(loggerName); if (num >= 0) { return loggerName.Substring(num + 1); } } else if (PrefixName) { int num2 = TryGetLastDotForShortName(loggerName); if (num2 > 0) { return loggerName.Substring(0, num2); } } return loggerName ?? string.Empty; } private static int TryGetLastDotForShortName(string loggerName) { return loggerName?.LastIndexOf('.') ?? (-1); } string? INoAllocationStringValueRenderer.GetFormattedStringNoAllocation(LogEventInfo logEvent) { if (ShortName || PrefixName) { return null; } return logEvent.LoggerName ?? string.Empty; } } [LayoutRenderer("longdate")] [ThreadAgnostic] public class LongDateLayoutRenderer : LayoutRenderer, IRawValue { private bool? _universalTime; public bool UniversalTime { get { return _universalTime.GetValueOrDefault(); } set { _universalTime = value; } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { DateTime value = GetValue(logEvent); builder.Append4DigitsZeroPadded(value.Year); builder.Append('-'); builder.Append2DigitsZeroPadded(value.Month); builder.Append('-'); builder.Append2DigitsZeroPadded(value.Day); builder.Append(' '); builder.Append2DigitsZeroPadded(value.Hour); builder.Append(':'); builder.Append2DigitsZeroPadded(value.Minute); builder.Append(':'); builder.Append2DigitsZeroPadded(value.Second); builder.Append('.'); builder.Append4DigitsZeroPadded((int)(value.Ticks % 10000000) / 1000); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } private DateTime GetValue(LogEventInfo logEvent) { DateTime timeStamp = logEvent.TimeStamp; if (_universalTime.HasValue) { if (!_universalTime.Value) { return timeStamp.ToLocalTime(); } return timeStamp.ToUniversalTime(); } return timeStamp; } } [LayoutRenderer("machinename")] [AppDomainFixedOutput] [ThreadAgnostic] public class MachineNameLayoutRenderer : LayoutRenderer { private string? _machineName; protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); try { _machineName = EnvironmentHelper.GetMachineName(); if (string.IsNullOrEmpty(_machineName)) { InternalLogger.Info("MachineName is not available."); } } catch (Exception ex) { InternalLogger.Error(ex, "Error getting machine name."); if (ex.MustBeRethrown()) { throw; } _machineName = string.Empty; } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(_machineName); } } [LayoutRenderer("message")] [ThreadAgnostic] public class MessageLayoutRenderer : LayoutRenderer, INoAllocationStringValueRenderer, IStringValueRenderer { public bool WithException { get; set; } public string ExceptionSeparator { get; set; } = "|"; public bool Raw { get; set; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { int num; if (logEvent.Exception != null && WithException) { object?[]? parameters = logEvent.Parameters; if (parameters != null && parameters.Length == 1 && logEvent.Parameters[0] == logEvent.Exception) { num = ((logEvent.Message == "{0}") ? 1 : 0); goto IL_0047; } } num = 0; goto IL_0047; IL_0047: bool flag = (byte)num != 0; if (Raw) { builder.Append(logEvent.Message); } else if (!flag) { if (logEvent.MessageFormatter?.Target is ILogMessageFormatter messageFormatter) { logEvent.AppendFormattedMessage(messageFormatter, builder); } else { builder.Append(logEvent.FormattedMessage); } } if (WithException && logEvent.Exception != null) { Exception primaryException = GetPrimaryException(logEvent.Exception); if (!flag) { builder.Append(ExceptionSeparator); } AppendExceptionToString(builder, primaryException); } } private static void AppendExceptionToString(StringBuilder builder, Exception exception) { string arg = string.Empty; Exception ex = null; try { ex = exception.InnerException; arg = exception.Message; builder.Append(exception.ToString()); } catch (Exception ex2) { InternalLogger.Warn(ex2, "Message-LayoutRenderer Could not output ToString for Exception: {0}", new ReadOnlySpan(new object[1] { exception.GetType() })); builder.Append($"{exception.GetType()}: {arg}"); if (ex != null) { builder.AppendLine(); AppendExceptionToString(builder, ex); } } } private static Exception GetPrimaryException(Exception exception) { if (exception is AggregateException ex) { ReadOnlyCollection innerExceptions = ex.InnerExceptions; if (innerExceptions != null && innerExceptions.Count == 1) { Exception ex2 = ex.InnerExceptions[0]; if (!(ex2 is AggregateException)) { return ex2; } } AggregateException ex3 = ex.Flatten(); ReadOnlyCollection innerExceptions2 = ex3.InnerExceptions; if (innerExceptions2 != null && innerExceptions2.Count == 1) { return ex3.InnerExceptions[0]; } return ex3; } return exception; } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { if (WithException) { return null; } return (Raw ? logEvent.Message : logEvent.FormattedMessage) ?? string.Empty; } string? INoAllocationStringValueRenderer.GetFormattedStringNoAllocation(LogEventInfo logEvent) { if (Raw) { object obj; if (!WithException) { obj = logEvent.Message; if (obj == null) { return string.Empty; } } else { obj = null; } return (string?)obj; } object obj2; if (!WithException) { object?[]? parameters = logEvent.Parameters; if (parameters == null || parameters.Length == 0) { obj2 = logEvent.FormattedMessage; if (obj2 == null) { obj2 = logEvent.Message; if (obj2 == null) { return string.Empty; } } goto IL_0058; } } obj2 = null; goto IL_0058; IL_0058: return (string?)obj2; } } [LayoutRenderer("newline")] [ThreadAgnostic] [AppDomainFixedOutput] public class NewLineLayoutRenderer : LayoutRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.AppendLine(); } } [LayoutRenderer("nlogdir")] [AppDomainFixedOutput] [ThreadAgnostic] public class NLogDirLayoutRenderer : LayoutRenderer { private static string? _nlogDir; private string? _nlogCombinedPath; public string File { get; set; } = string.Empty; public string Dir { get; set; } = string.Empty; private static string NLogDir => _nlogDir ?? (_nlogDir = ResolveNLogDir()); protected override void InitializeLayoutRenderer() { _nlogCombinedPath = null; base.InitializeLayoutRenderer(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string value = _nlogCombinedPath ?? (_nlogCombinedPath = PathHelpers.CombinePaths(NLogDir, Dir, File)); builder.Append(value); } private static string ResolveNLogDir() { string assemblyFileLocation = AssemblyHelpers.GetAssemblyFileLocation(typeof(LogFactory).Assembly); if (!string.IsNullOrEmpty(assemblyFileLocation)) { return Path.GetDirectoryName(assemblyFileLocation) ?? string.Empty; } return string.Empty; } } [LayoutRenderer("processdir")] [AppDomainFixedOutput] [ThreadAgnostic] public class ProcessDirLayoutRenderer : LayoutRenderer { private readonly string _processDir; private string? _nlogCombinedPath; public string File { get; set; } = string.Empty; public string Dir { get; set; } = string.Empty; public ProcessDirLayoutRenderer() : this(LogFactory.DefaultAppEnvironment) { } internal ProcessDirLayoutRenderer(IAppEnvironment appEnvironment) { _processDir = Path.GetDirectoryName(appEnvironment.CurrentProcessFilePath) ?? string.Empty; } protected override void InitializeLayoutRenderer() { _nlogCombinedPath = null; base.InitializeLayoutRenderer(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string value = _nlogCombinedPath ?? (_nlogCombinedPath = PathHelpers.CombinePaths(_processDir, Dir, File)); builder.Append(value); } } [LayoutRenderer("processid")] [AppDomainFixedOutput] [ThreadAgnostic] public class ProcessIdLayoutRenderer : LayoutRenderer, IRawValue { private readonly int _processId; public ProcessIdLayoutRenderer() : this(LogFactory.DefaultAppEnvironment) { } internal ProcessIdLayoutRenderer(IAppEnvironment appEnvironment) { _processId = appEnvironment.CurrentProcessId; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.AppendInvariant(_processId); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = _processId; return true; } } [LayoutRenderer("processinfo")] public class ProcessInfoLayoutRenderer : LayoutRenderer { private Process? _process; private ReflectionHelpers.LateBoundMethod? _lateBoundPropertyGet; [DefaultParameter] public ProcessInfoProperty Property { get; set; } = ProcessInfoProperty.Id; public string? Format { get; set; } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); MethodInfo getMethod = (typeof(Process).GetProperty(Property.ToString()) ?? throw new ArgumentException($"Property '{Property}' not found in System.Diagnostics.Process")).GetGetMethod(); if ((object)getMethod == null) { throw new ArgumentException($"Property '{Property}' not found in System.Diagnostics.Process with valid getter-method"); } _lateBoundPropertyGet = ReflectionHelpers.CreateLateBoundMethod(getMethod); _process = Process.GetCurrentProcess(); } protected override void CloseLayoutRenderer() { _process?.Close(); _process = null; base.CloseLayoutRenderer(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (_process != null && _lateBoundPropertyGet != null) { object obj = _lateBoundPropertyGet(_process, ArrayHelper.Empty()); if (obj != null) { AppendFormattedValue(builder, logEvent, obj, Format, Culture); } } } } public enum ProcessInfoProperty { BasePriority, ExitCode, ExitTime, Handle, HandleCount, HasExited, Id, MachineName, MainWindowHandle, MainWindowTitle, MaxWorkingSet, MinWorkingSet, NonPagedSystemMemorySize, NonPagedSystemMemorySize64, PagedMemorySize, PagedMemorySize64, PagedSystemMemorySize, PagedSystemMemorySize64, PeakPagedMemorySize, PeakPagedMemorySize64, PeakVirtualMemorySize, PeakVirtualMemorySize64, PeakWorkingSet, PeakWorkingSet64, PriorityBoostEnabled, PriorityClass, PrivateMemorySize, PrivateMemorySize64, PrivilegedProcessorTime, ProcessName, Responding, SessionId, StartTime, TotalProcessorTime, UserProcessorTime, VirtualMemorySize, VirtualMemorySize64, WorkingSet, WorkingSet64 } [LayoutRenderer("processname")] [AppDomainFixedOutput] [ThreadAgnostic] public class ProcessNameLayoutRenderer : LayoutRenderer { private readonly string _processFilePath; private readonly string _processBaseName; public bool FullName { get; set; } public ProcessNameLayoutRenderer() : this(LogFactory.DefaultAppEnvironment) { } internal ProcessNameLayoutRenderer(IAppEnvironment appEnvironment) { _processFilePath = appEnvironment.CurrentProcessFilePath; _processBaseName = appEnvironment.CurrentProcessBaseName; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string value = (FullName ? _processFilePath : _processBaseName); builder.Append(value); } } [LayoutRenderer("processtime")] [ThreadAgnostic] public class ProcessTimeLayoutRenderer : LayoutRenderer, IRawValue { public bool Invariant { get { return Culture == CultureInfo.InvariantCulture; } set { Culture = (value ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture); } } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void Append(StringBuilder builder, LogEventInfo logEvent) { TimeSpan value = GetValue(logEvent); CultureInfo culture = GetCulture(logEvent, Culture); WriteTimestamp(builder, value, culture); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } internal static void WriteTimestamp(StringBuilder builder, TimeSpan ts, CultureInfo culture) { string value = ":"; string value2 = "."; if (culture != CultureInfo.InvariantCulture) { value = culture.DateTimeFormat.TimeSeparator; value2 = culture.NumberFormat.NumberDecimalSeparator; } builder.Append2DigitsZeroPadded(ts.Hours); builder.Append(value); builder.Append2DigitsZeroPadded(ts.Minutes); builder.Append(value); builder.Append2DigitsZeroPadded(ts.Seconds); builder.Append(value2); int milliseconds = ts.Milliseconds; if (milliseconds < 100) { builder.Append('0'); if (milliseconds < 10) { builder.Append('0'); if (milliseconds < 0) { builder.Append('0'); return; } } } builder.AppendInvariant(milliseconds); } private static TimeSpan GetValue(LogEventInfo logEvent) { return logEvent.TimeStamp.ToUniversalTime() - LogEventInfo.ZeroDate; } } [LayoutRenderer("scopeindent")] public sealed class ScopeContextIndentLayoutRenderer : LayoutRenderer { [DefaultParameter] public Layout Indent { get; set; } = Layout.FromLiteral(" "); protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string text = null; IList allNestedStateList = ScopeContext.GetAllNestedStateList(); for (int i = 0; i < allNestedStateList.Count; i++) { text = text ?? Indent?.Render(logEvent) ?? string.Empty; builder.Append(text); } } } [LayoutRenderer("scopenested")] [LayoutRenderer("ndc")] [LayoutRenderer("ndlc")] public sealed class ScopeContextNestedStatesLayoutRenderer : LayoutRenderer { private string _separator = " "; private string _separatorOriginal = " "; public int TopFrames { get; set; } = -1; public int BottomFrames { get; set; } = -1; public string Separator { get { return _separatorOriginal ?? _separator; } set { _separatorOriginal = value; _separator = SimpleLayout.Evaluate(value, base.LoggingConfiguration, null, false); } } public string? Format { get; set; } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if (_separatorOriginal != null) { _separator = SimpleLayout.Evaluate(_separatorOriginal, base.LoggingConfiguration); } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (TopFrames == 1) { object obj = ScopeContext.PeekNestedState(); if (obj != null) { AppendFormattedValue(builder, logEvent, obj, Format, Culture); } return; } IList allNestedStateList = ScopeContext.GetAllNestedStateList(); if (allNestedStateList.Count != 0) { int startPos = 0; int endPos = allNestedStateList.Count; if (TopFrames != -1) { endPos = Math.Min(TopFrames, allNestedStateList.Count); } else if (BottomFrames != -1) { startPos = allNestedStateList.Count - Math.Min(BottomFrames, allNestedStateList.Count); } AppendNestedStates(builder, allNestedStateList, startPos, endPos, logEvent); } } private void AppendNestedStates(StringBuilder builder, IList messages, int startPos, int endPos, LogEventInfo logEvent) { bool flag = "@".Equals(Format); string text = _separator ?? string.Empty; string text2 = text; if (flag) { text2 = ((text2 == " ") ? ", " : ((!string.IsNullOrEmpty(text2)) ? ("," + text2) : ",")); builder.Append('['); builder.Append(text); } try { string value = null; for (int num = endPos - 1; num >= startPos; num--) { builder.Append(value); if (flag) { AppendJsonFormattedValue(messages[num], Culture ?? CultureInfo.InvariantCulture, builder, text, text2); } else if (messages[num] is IEnumerable>) { builder.Append(Convert.ToString(messages[num], GetFormatProvider(logEvent, Culture))); } else { AppendFormattedValue(builder, logEvent, messages[num], Format, Culture); } value = text2; } } finally { if (flag) { builder.Append(text); builder.Append(']'); } } } private void AppendJsonFormattedValue(object nestedState, IFormatProvider formatProvider, StringBuilder builder, string separator, string itemSeparator) { if (nestedState is IEnumerable> enumerable && HasUniqueCollectionKeys(enumerable)) { builder.Append('{'); builder.Append(separator); string itemSeparator2 = string.Empty; using (ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = new ScopeContextPropertyEnumerator(enumerable)) { while (scopeContextPropertyEnumerator.MoveNext()) { KeyValuePair current = scopeContextPropertyEnumerator.Current; int length = builder.Length; if (!AppendJsonProperty(current.Key, current.Value, builder, itemSeparator2)) { builder.Length = length; } else { itemSeparator2 = itemSeparator; } } } builder.Append(separator); builder.Append('}'); } else { builder.AppendFormattedValue(nestedState, Format, formatProvider, base.ValueFormatter); } } private bool AppendJsonProperty(string propertyName, object? propertyValue, StringBuilder builder, string itemSeparator) { if (string.IsNullOrEmpty(propertyName)) { return false; } builder.Append(itemSeparator); if (!base.ValueFormatter.FormatValue(propertyName, null, CaptureType.Serialize, null, builder)) { return false; } builder.Append(": "); if (!base.ValueFormatter.FormatValue(propertyValue, null, CaptureType.Serialize, null, builder)) { return false; } return true; } private static bool HasUniqueCollectionKeys(IEnumerable> propertyList) { if (propertyList is IDictionary) { return true; } if (propertyList is IReadOnlyDictionary) { return true; } if (propertyList is IReadOnlyCollection> readOnlyCollection) { if (readOnlyCollection.Count <= 1) { return true; } if (readOnlyCollection.Count > 10) { return false; } } return ScopeContextPropertyEnumerator.HasUniqueCollectionKeys(propertyList, StringComparer.Ordinal); } } [LayoutRenderer("scopeproperty")] [LayoutRenderer("mdc")] [LayoutRenderer("mdlc")] public sealed class ScopeContextPropertyLayoutRenderer : LayoutRenderer, IStringValueRenderer { [DefaultParameter] public string Item { get; set; } = string.Empty; public string? Format { get; set; } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if (string.IsNullOrEmpty(Item)) { throw new NLogConfigurationException("ScopeProperty-LayoutRenderer Item-property must be assigned. Lookup blank value not supported."); } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object value = GetValue(); AppendFormattedValue(builder, logEvent, value, Format, Culture); } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { if (!"@".Equals(Format)) { return FormatHelper.TryFormatToString(GetValue(), Format, GetFormatProvider(logEvent, Culture)); } return null; } private object? GetValue() { ScopeContext.TryGetProperty(Item, out object value); return value; } } [LayoutRenderer("scopetiming")] [LayoutRenderer("ndlctiming")] public sealed class ScopeContextTimingLayoutRenderer : LayoutRenderer { public bool CurrentScope { get; set; } public bool StartTime { get; set; } [Obsolete("Replaced by StartTime. Marked obsolete on NLog 6.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool ScopeBeginTime { get { return StartTime; } set { StartTime = value; } } public string? Format { get; set; } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void Append(StringBuilder builder, LogEventInfo logEvent) { TimeSpan? timeSpan = (CurrentScope ? ScopeContext.PeekInnerNestedDuration() : ScopeContext.PeekOuterNestedDuration()); if (!timeSpan.HasValue) { return; } if (timeSpan.Value < TimeSpan.Zero) { timeSpan = TimeSpan.Zero; } if (StartTime) { builder.Append(TimeSource.Current.Time.Subtract(timeSpan.Value).ToString(Format, Culture)); } else if (string.IsNullOrEmpty(Format)) { double totalMilliseconds = timeSpan.Value.TotalMilliseconds; if (Culture == CultureInfo.InvariantCulture) { RenderAppendDurationMs(builder, totalMilliseconds); } else { builder.Append(totalMilliseconds.ToString("0.###", Culture)); } } else { builder.Append(timeSpan.Value.ToString(Format, Culture)); } } private static void RenderAppendDurationMs(StringBuilder builder, double scopeDurationMs) { long num = (long)scopeDurationMs; if (num >= 0 && num < uint.MaxValue) { builder.AppendInvariant((uint)num); } else { builder.Append(num); } int num2 = (int)((scopeDurationMs - (double)num) * 1000.0); if (num2 > 0) { builder.Append('.'); if (num2 < 100) { builder.Append('0'); } if (num2 < 10) { builder.Append('0'); } builder.AppendInvariant(num2); } else { builder.Append(".0"); } } } [LayoutRenderer("sequenceid")] [ThreadAgnostic] [Obsolete("Use ${counter:sequence=global} instead of ${sequenceid}. Marked obsolete with NLog 6.0")] [EditorBrowsable(EditorBrowsableState.Never)] public class SequenceIdLayoutRenderer : LayoutRenderer, IRawValue { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.AppendInvariant(GetValue(logEvent)); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } private static int GetValue(LogEventInfo logEvent) { return logEvent.SequenceID; } } [LayoutRenderer("shortdate")] [ThreadAgnostic] public class ShortDateLayoutRenderer : LayoutRenderer, IRawValue, IStringValueRenderer { private sealed class CachedDateFormatted { public readonly DateTime Date; public readonly string FormattedDate; public CachedDateFormatted(DateTime date, string formattedDate) { Date = date; FormattedDate = formattedDate; } } private bool? _universalTime; private CachedDateFormatted _cachedDateFormatted = new CachedDateFormatted(DateTime.MaxValue, string.Empty); public bool UniversalTime { get { return _universalTime.GetValueOrDefault(); } set { _universalTime = value; } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string stringValue = GetStringValue(logEvent); builder.Append(stringValue); } private string GetStringValue(LogEventInfo logEvent) { DateTime value = GetValue(logEvent); CachedDateFormatted cachedDateFormatted = _cachedDateFormatted; if (cachedDateFormatted.Date != value.Date) { string formattedDate = value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); cachedDateFormatted = (_cachedDateFormatted = new CachedDateFormatted(value.Date, formattedDate)); } return cachedDateFormatted.FormattedDate; } private DateTime GetValue(LogEventInfo logEvent) { DateTime result = logEvent.TimeStamp; if (_universalTime.HasValue) { result = ((!_universalTime.Value) ? result.ToLocalTime() : result.ToUniversalTime()); } return result; } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent).Date; return true; } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return GetStringValue(logEvent); } } [LayoutRenderer("userApplicationDataDir")] public class SpecialFolderApplicationDataLayoutRenderer : SpecialFolderLayoutRenderer { public SpecialFolderApplicationDataLayoutRenderer() { base.Folder = Environment.SpecialFolder.ApplicationData; } } [LayoutRenderer("commonApplicationDataDir")] public class SpecialFolderCommonApplicationDataLayoutRenderer : SpecialFolderLayoutRenderer { public SpecialFolderCommonApplicationDataLayoutRenderer() { base.Folder = Environment.SpecialFolder.CommonApplicationData; } } [LayoutRenderer("specialfolder")] [AppDomainFixedOutput] [ThreadAgnostic] public class SpecialFolderLayoutRenderer : LayoutRenderer { [DefaultParameter] public Environment.SpecialFolder Folder { get; set; } = Environment.SpecialFolder.CommonApplicationData; public string File { get; set; } = string.Empty; public string Dir { get; set; } = string.Empty; protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string value = PathHelpers.CombinePaths(GetFolderPath(Folder), Dir, File); builder.Append(value); } internal static string GetFolderPath(Environment.SpecialFolder folder) { try { string folderPath = Environment.GetFolderPath(folder); if (!string.IsNullOrEmpty(folderPath)) { return folderPath; } } catch { string folderPathFromEnvironment = GetFolderPathFromEnvironment(folder); if (!string.IsNullOrEmpty(folderPathFromEnvironment)) { return folderPathFromEnvironment; } throw; } return GetFolderPathFromEnvironment(folder); } private static string GetFolderPathFromEnvironment(Environment.SpecialFolder folder) { try { string folderWindowsEnvironmentVariable = GetFolderWindowsEnvironmentVariable(folder); if (string.IsNullOrEmpty(folderWindowsEnvironmentVariable)) { return string.Empty; } if (!PlatformDetector.IsWin32) { return string.Empty; } return Environment.GetEnvironmentVariable(folderWindowsEnvironmentVariable) ?? string.Empty; } catch { return string.Empty; } } private static string GetFolderWindowsEnvironmentVariable(Environment.SpecialFolder folder) { return folder switch { Environment.SpecialFolder.CommonApplicationData => "COMMONAPPDATA", Environment.SpecialFolder.LocalApplicationData => "LOCALAPPDATA", Environment.SpecialFolder.ApplicationData => "APPDATA", Environment.SpecialFolder.UserProfile => "USERPROFILE", _ => string.Empty, }; } } [LayoutRenderer("userLocalApplicationDataDir")] public class SpecialFolderLocalApplicationDataLayoutRenderer : SpecialFolderLayoutRenderer { public SpecialFolderLocalApplicationDataLayoutRenderer() { base.Folder = Environment.SpecialFolder.LocalApplicationData; } } public enum StackTraceFormat { Raw, Flat, DetailedFlat } [LayoutRenderer("stacktrace")] [ThreadAgnostic] public class StackTraceLayoutRenderer : LayoutRenderer, IUsesStackTrace { private readonly struct StackFrameList { private readonly StackTrace _stackTrace; private readonly int _startingFrame; private readonly int _endingFrame; private readonly bool _reverse; public int Count => _startingFrame - _endingFrame; public StackFrame? this[int index] { get { int index2 = (_reverse ? (_endingFrame + index + 1) : (_startingFrame - index)); return _stackTrace.GetFrame(index2); } } public StackFrameList(StackTrace stackTrace, int startingFrame, int endingFrame, bool reverse) { _stackTrace = stackTrace; _startingFrame = startingFrame; _endingFrame = endingFrame - 1; _reverse = reverse; } } private string _separator = " => "; private string _separatorOriginal = " => "; public StackTraceFormat Format { get; set; } = StackTraceFormat.Flat; public int TopFrames { get; set; } = 3; public int SkipFrames { get; set; } public string Separator { get { return _separatorOriginal ?? _separator; } set { _separatorOriginal = value; _separator = SimpleLayout.Evaluate(value, base.LoggingConfiguration, null, false); } } public bool CaptureStackTrace { get; set; } = true; public bool Reverse { get; set; } StackTraceUsage IUsesStackTrace.StackTraceUsage { get { if (!CaptureStackTrace) { return StackTraceUsage.None; } if (Format == StackTraceFormat.Raw) { return StackTraceUsage.WithSource; } return StackTraceUsage.WithStackTrace; } } protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if (_separatorOriginal != null) { _separator = SimpleLayout.Evaluate(_separatorOriginal, base.LoggingConfiguration); } } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (logEvent.StackTrace != null) { int num = logEvent.CallSiteInformation?.UserStackFrameNumberLegacy ?? logEvent.CallSiteInformation?.UserStackFrameNumber ?? 0; int num2 = num + TopFrames - 1; if (num2 >= logEvent.StackTrace.GetFrameCount()) { num2 = logEvent.StackTrace.GetFrameCount() - 1; } int endingFrame = num + SkipFrames; StackFrameList stackFrameList = new StackFrameList(logEvent.StackTrace, num2, endingFrame, Reverse); switch (Format) { case StackTraceFormat.Raw: AppendRaw(builder, stackFrameList); break; case StackTraceFormat.Flat: AppendFlat(builder, stackFrameList); break; case StackTraceFormat.DetailedFlat: AppendDetailedFlat(builder, stackFrameList); break; } } } private void AppendRaw(StringBuilder builder, StackFrameList stackFrameList) { string text = null; for (int i = 0; i < stackFrameList.Count; i++) { string value = stackFrameList[i]?.ToString(); if (!string.IsNullOrEmpty(value)) { builder.Append(text); builder.Append(value); text = text ?? _separator ?? string.Empty; } } } private void AppendFlat(StringBuilder builder, StackFrameList stackFrameList) { string text = null; for (int i = 0; i < stackFrameList.Count; i++) { MethodBase stackMethod = StackTraceUsageUtils.GetStackMethod(stackFrameList[i]); if ((object)stackMethod != null) { builder.Append(text); builder.Append(stackMethod.DeclaringType?.Name ?? ""); builder.Append('.'); builder.Append(stackMethod.Name); text = text ?? _separator ?? string.Empty; } } } private void AppendDetailedFlat(StringBuilder builder, StackFrameList stackFrameList) { string text = null; for (int i = 0; i < stackFrameList.Count; i++) { MethodBase stackMethod = StackTraceUsageUtils.GetStackMethod(stackFrameList[i]); if ((object)stackMethod != null) { builder.Append(text); builder.Append('['); builder.Append(stackMethod); builder.Append(']'); text = text ?? _separator ?? string.Empty; } } } } [LayoutRenderer("tempdir")] [AppDomainFixedOutput] [ThreadAgnostic] public class TempDirLayoutRenderer : LayoutRenderer { private static string? _tempDir; private string? _nlogCombinedPath; private static string TempDir => _tempDir ?? (_tempDir = Path.GetTempPath()); public string File { get; set; } = string.Empty; public string Dir { get; set; } = string.Empty; protected override void InitializeLayoutRenderer() { _nlogCombinedPath = null; base.InitializeLayoutRenderer(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { string value = _nlogCombinedPath ?? (_nlogCombinedPath = PathHelpers.CombinePaths(TempDir, Dir, File)); builder.Append(value); } } [LayoutRenderer("threadid")] public class ThreadIdLayoutRenderer : LayoutRenderer, IStringValueRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.AppendInvariant(GetValue()); } private static int GetValue() { return AsyncHelpers.GetManagedThreadId(); } string IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return GetValue().ToString(CultureInfo.InvariantCulture); } } [LayoutRenderer("threadname")] public class ThreadNameLayoutRenderer : LayoutRenderer, IStringValueRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetStringValue()); } private static string? GetStringValue() { return Thread.CurrentThread.Name; } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return GetStringValue(); } } [LayoutRenderer("ticks")] [ThreadAgnostic] public class TicksLayoutRenderer : LayoutRenderer, IRawValue { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.Append(GetValue(logEvent).ToString(CultureInfo.InvariantCulture)); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } private static long GetValue(LogEventInfo logEvent) { return logEvent.TimeStamp.Ticks; } } [LayoutRenderer("time")] [ThreadAgnostic] public class TimeLayoutRenderer : LayoutRenderer, IRawValue { private bool? _universalTime; public bool UniversalTime { get { return _universalTime.GetValueOrDefault(); } set { _universalTime = value; } } public bool Invariant { get { return Culture == CultureInfo.InvariantCulture; } set { Culture = (value ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture); } } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void Append(StringBuilder builder, LogEventInfo logEvent) { DateTime value = GetValue(logEvent); CultureInfo culture = GetCulture(logEvent, Culture); string value2 = ":"; string value3 = "."; if (culture != CultureInfo.InvariantCulture) { value2 = culture.DateTimeFormat.TimeSeparator; value3 = culture.NumberFormat.NumberDecimalSeparator; } builder.Append2DigitsZeroPadded(value.Hour); builder.Append(value2); builder.Append2DigitsZeroPadded(value.Minute); builder.Append(value2); builder.Append2DigitsZeroPadded(value.Second); builder.Append(value3); builder.Append4DigitsZeroPadded((int)(value.Ticks % 10000000) / 1000); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = GetValue(logEvent); return true; } private DateTime GetValue(LogEventInfo logEvent) { DateTime result = logEvent.TimeStamp; if (_universalTime.HasValue) { result = ((!_universalTime.Value) ? result.ToLocalTime() : result.ToUniversalTime()); } return result; } } [LayoutRenderer("var")] public class VariableLayoutRenderer : LayoutRenderer { [DefaultParameter] public string Name { get; set; } = string.Empty; public string Default { get; set; } = string.Empty; public Layout? ActiveLayout { get { if (!TryGetLayout(out Layout layout)) { return null; } return layout; } } protected override void InitializeLayoutRenderer() { if (string.IsNullOrEmpty(Name)) { throw new NLogConfigurationException("Var-LayoutRenderer Name-property must be assigned. Lookup blank value not supported."); } if (TryGetLayout(out Layout layout)) { layout?.Initialize(base.LoggingConfiguration); } base.InitializeLayoutRenderer(); } private bool TryGetLayout(out Layout? layout) { layout = null; if (Name != null) { return base.LoggingConfiguration?.TryLookupDynamicVariable(Name, out layout) ?? false; } return false; } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (Name != null) { if (TryGetLayout(out Layout layout)) { layout?.Render(logEvent, builder); } else if (Default != null) { builder.Append(Default); } } } } } namespace NLog.LayoutRenderers.Wrappers { [LayoutRenderer("cached")] [AmbientProperty("Cached")] [AmbientProperty("ClearCache")] [AmbientProperty("CachedSeconds")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class CachedLayoutRendererWrapper : WrapperLayoutRendererBase, IStringValueRenderer { [Flags] public enum ClearCacheOption { None = 0, OnInit = 1, OnClose = 2 } private readonly object _lockObject = new object(); private string? _cachedValue; private string? _renderedCacheKey; private DateTime _cachedValueExpires; private TimeSpan? _cachedValueTimeout; public bool Cached { get; set; } = true; public ClearCacheOption ClearCache { get; set; } = ClearCacheOption.OnInit | ClearCacheOption.OnClose; public Layout? CacheKey { get; set; } public int CachedSeconds { get { return (int)(_cachedValueTimeout?.TotalSeconds ?? 0.0); } set { _cachedValueTimeout = TimeSpan.FromSeconds(value); if (_cachedValueTimeout > TimeSpan.Zero) { Cached = true; } } } protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if ((ClearCache & ClearCacheOption.OnInit) == ClearCacheOption.OnInit) { _cachedValue = null; } } protected override void CloseLayoutRenderer() { base.CloseLayoutRenderer(); if ((ClearCache & ClearCacheOption.OnClose) == ClearCacheOption.OnClose) { _cachedValue = null; } } protected override string Transform(string text) { return text; } protected override string RenderInner(LogEventInfo logEvent) { if (Cached) { string text = CacheKey?.Render(logEvent) ?? string.Empty; string text2 = LookupValidCachedValue(logEvent, text); if (text2 == null) { lock (_lockObject) { text2 = LookupValidCachedValue(logEvent, text); if (text2 == null) { text2 = (_cachedValue = base.RenderInner(logEvent)); _renderedCacheKey = text; if (_cachedValueTimeout.HasValue) { _cachedValueExpires = logEvent.TimeStamp + _cachedValueTimeout.Value; } } } } return text2; } return base.RenderInner(logEvent); } private string? LookupValidCachedValue(LogEventInfo logEvent, string newCacheKey) { if (_renderedCacheKey != newCacheKey) { return null; } if (_cachedValueTimeout.HasValue && logEvent.TimeStamp > _cachedValueExpires) { return null; } return _cachedValue; } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { if (!Cached) { return null; } return RenderInner(logEvent); } } [LayoutRenderer("filesystem-normalize")] [AmbientProperty("FSNormalize")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class FileSystemNormalizeLayoutRendererWrapper : WrapperLayoutRendererBase { public bool FSNormalize { get; set; } = true; protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner.Render(logEvent, builder); if (FSNormalize && builder.Length > orgLength) { TransformFileSystemNormalize(builder, orgLength); } } protected override string Transform(string text) { throw new NotSupportedException(); } private static void TransformFileSystemNormalize(StringBuilder builder, int startPos) { for (int i = startPos; i < builder.Length; i++) { if (!IsSafeCharacter(builder[i])) { builder[i] = '_'; } } } private static bool IsSafeCharacter(char c) { if (!char.IsLetterOrDigit(c) && c != '_' && c != '-' && c != '.') { return c == ' '; } return true; } } [LayoutRenderer("json-encode")] [AmbientProperty("JsonEncode")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class JsonEncodeLayoutRendererWrapper : WrapperLayoutRendererBase { public bool JsonEncode { get; set; } = true; public bool EscapeUnicode { get; set; } = true; [Obsolete("Marked obsolete with NLog 5.5. Should never escape forward slash")] [EditorBrowsable(EditorBrowsableState.Never)] public bool EscapeForwardSlash { get; set; } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner.Render(logEvent, builder); if (JsonEncode && builder.Length > orgLength) { DefaultJsonSerializer.PerformJsonEscapeWhenNeeded(builder, orgLength, EscapeUnicode); } } protected override string Transform(string text) { throw new NotSupportedException(); } } [LayoutRenderer("left")] [AmbientProperty("Truncate")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class LeftLayoutRendererWrapper : WrapperLayoutRendererBase { public int Length { get; set; } public int Truncate { get { return Length; } set { Length = value; } } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { if (Length > 0) { base.Inner?.Render(logEvent, builder); if (builder.Length - orgLength > Length) { builder.Length = orgLength + Length; } } } protected override string Transform(string text) { throw new NotSupportedException(); } } [LayoutRenderer("lowercase")] [AmbientProperty("Lowercase")] [AmbientProperty("ToLower")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class LowercaseLayoutRendererWrapper : WrapperLayoutRendererBase { public bool Lowercase { get; set; } = true; public bool ToLower { get { return Lowercase; } set { Lowercase = value; } } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner?.Render(logEvent, builder); if (Lowercase && builder.Length > orgLength) { TransformToLowerCase(builder, logEvent, orgLength); } } protected override string Transform(string text) { throw new NotSupportedException(); } private void TransformToLowerCase(StringBuilder target, LogEventInfo logEvent, int startPos) { CultureInfo culture = GetCulture(logEvent, Culture); for (int i = startPos; i < target.Length; i++) { target[i] = char.ToLower(target[i], culture); } } } [LayoutRenderer("norawvalue")] [AmbientProperty("NoRawValue")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class NoRawValueLayoutRendererWrapper : WrapperLayoutRendererBase { public bool NoRawValue { get; set; } = true; protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner?.Render(logEvent, builder); } protected override string Transform(string text) { throw new NotSupportedException(); } } [LayoutRenderer("Object-Path")] [AmbientProperty("ObjectPath")] [ThreadAgnostic] public sealed class ObjectPathRendererWrapper : WrapperLayoutRendererBase, IRawValue { private ObjectReflectionCache? _objectReflectionCache; private ObjectPropertyPath _objectPropertyPath; private ObjectReflectionCache ObjectReflectionCache => _objectReflectionCache ?? (_objectReflectionCache = new ObjectReflectionCache(base.LoggingConfiguration.GetServiceProvider())); public string Path { get { return ObjectPath; } set { ObjectPath = value; } } public string ObjectPath { get { return _objectPropertyPath.Value ?? string.Empty; } set { _objectPropertyPath.Value = value; } } public string? Format { get; set; } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override string Transform(string text) { throw new NotSupportedException(); } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { if (TryGetRawPropertyValue(logEvent, out object propertyValue)) { AppendFormattedValue(builder, logEvent, propertyValue, Format, Culture); } } private bool TryGetRawPropertyValue(LogEventInfo logEvent, out object? propertyValue) { Layout inner = base.Inner; if (inner != null && inner.TryGetRawValue(logEvent, out object rawValue) && rawValue != null && TryGetPropertyValue(rawValue, out propertyValue)) { return true; } propertyValue = null; return false; } public bool TryGetPropertyValue(object sourceObject, out object? propertyValue) { return ObjectReflectionCache.TryGetObjectProperty(sourceObject, _objectPropertyPath.PathNames, out propertyValue); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object? value) { return TryGetRawPropertyValue(logEvent, out value); } } [LayoutRenderer("onexception")] [ThreadAgnostic] public sealed class OnExceptionLayoutRendererWrapper : WrapperLayoutRendererBase { public Layout Else { get; set; } = Layout.Empty; protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { if (logEvent.Exception != null) { base.Inner?.Render(logEvent, builder); } else { Else?.Render(logEvent, builder); } } protected override string Transform(string text) { return text; } } [LayoutRenderer("onhasproperties")] [ThreadAgnostic] public sealed class OnHasPropertiesLayoutRendererWrapper : WrapperLayoutRendererBase { public Layout Else { get; set; } = Layout.Empty; protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { if (logEvent.HasProperties) { base.Inner?.Render(logEvent, builder); } else { Else?.Render(logEvent, builder); } } protected override string Transform(string text) { return text; } } public enum PaddingHorizontalAlignment { Left, Right } [LayoutRenderer("pad")] [AmbientProperty("Padding")] [AmbientProperty("PadCharacter")] [AmbientProperty("FixedLength")] [AmbientProperty("AlignmentOnTruncation")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class PaddingLayoutRendererWrapper : WrapperLayoutRendererBase { public int Padding { get; set; } public char PadCharacter { get; set; } = ' '; public bool FixedLength { get; set; } public PaddingHorizontalAlignment AlignmentOnTruncation { get; set; } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner?.Render(logEvent, builder); if (Padding == 0) { return; } int num = Padding; if (num < 0) { num = -num; } int num2 = AppendPadding(builder, orgLength, num); if (FixedLength && num2 > num) { if (AlignmentOnTruncation == PaddingHorizontalAlignment.Left) { builder.Length = orgLength + num; } else { builder.Remove(orgLength, num2 - num); } } } private int AppendPadding(StringBuilder builder, int orgLength, int absolutePadding) { int num = builder.Length - orgLength; if (Padding > 0) { if (num < 10 || num >= absolutePadding) { for (int i = num; i < absolutePadding; i++) { builder.Append(PadCharacter); for (int num2 = builder.Length - 1; num2 > orgLength; num2--) { builder[num2] = builder[num2 - 1]; } builder[orgLength] = PadCharacter; num++; } } else { string value = builder.ToString(orgLength, num); builder.Length = orgLength; for (int j = num; j < absolutePadding; j++) { builder.Append(PadCharacter); num++; } builder.Append(value); } } else { for (int k = num; k < absolutePadding; k++) { builder.Append(PadCharacter); num++; } } return num; } protected override string Transform(string text) { throw new NotSupportedException(); } } [LayoutRenderer("replace")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class ReplaceLayoutRendererWrapper : WrapperLayoutRendererBase { private string _searchFor = string.Empty; private string _searchForOriginal = string.Empty; private string _replaceWith = string.Empty; private string _replaceWithOriginal = string.Empty; public string SearchFor { get { return _searchForOriginal ?? _searchFor; } set { _searchForOriginal = value; _searchFor = SimpleLayout.Evaluate(value, base.LoggingConfiguration, null, false); } } public string ReplaceWith { get { return _replaceWithOriginal ?? _replaceWith; } set { _replaceWithOriginal = value; _replaceWith = SimpleLayout.Evaluate(value, base.LoggingConfiguration, null, false); } } public bool IgnoreCase { get; set; } public bool WholeWords { get; set; } protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); if (string.IsNullOrEmpty(SearchFor)) { throw new NLogConfigurationException("Replace-LayoutRenderer SearchFor-property must be assigned. Searching for blank value not supported."); } if (_searchForOriginal != null) { _searchFor = SimpleLayout.Evaluate(_searchForOriginal, base.LoggingConfiguration); } if (_replaceWithOriginal != null) { _replaceWith = SimpleLayout.Evaluate(_replaceWithOriginal, base.LoggingConfiguration); } } protected override string Transform(string text) { if (IgnoreCase || WholeWords) { StringComparison comparison = (IgnoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture); return StringHelpers.Replace(text, _searchFor, _replaceWith, comparison, WholeWords); } return text.Replace(_searchFor, _replaceWith); } } [LayoutRenderer("replace-newlines")] [AmbientProperty("ReplaceNewLines")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class ReplaceNewLinesLayoutRendererWrapper : WrapperLayoutRendererBase { public string Replacement { get; set; } = " "; public string ReplaceNewLines { get { return Replacement; } set { Replacement = value; } } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner?.Render(logEvent, builder); if (builder.Length <= orgLength) { return; } int num = IndexOfLineEndCharacters(builder, orgLength); if (num <= -1) { return; } orgLength = ((num > orgLength) ? (num - 1) : orgLength); string text = builder.ToString(orgLength, builder.Length - orgLength); builder.Length = orgLength; bool flag = false; string text2 = text; foreach (char c in text2) { if (IsLineEndCharacter(c)) { if (!flag || c != '\n') { builder.Append(Replacement); } flag = c == '\r'; } else { builder.Append(c); flag = false; } } } private static bool IsLineEndCharacter(char ch) { switch (ch) { case '\n': case '\f': case '\r': case '\u0085': case '\u2028': case '\u2029': return true; default: return false; } } private static int IndexOfLineEndCharacters(StringBuilder builder, int startPosition) { for (int i = startPosition; i < builder.Length; i++) { if (IsLineEndCharacter(builder[i])) { return i; } } return -1; } protected override string Transform(string text) { throw new NotSupportedException(); } } [LayoutRenderer("right")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class RightLayoutRendererWrapper : WrapperLayoutRendererBase { public int Length { get; set; } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { if (Length > 0) { base.Inner.Render(logEvent, builder); if (builder.Length - orgLength > Length) { string value = builder.ToString(builder.Length - Length, Length); builder.Length = orgLength; builder.Append(value); } } } protected override string Transform(string text) { throw new NotSupportedException(); } } [LayoutRenderer("rot13")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class Rot13LayoutRendererWrapper : WrapperLayoutRendererBase { [Obsolete("Replaced by Inner. Marked obsolete with NLog 2.0")] public Layout Text { get { return base.Inner; } set { base.Inner = value; } } public static string DecodeRot13(string encodedValue) { StringBuilder stringBuilder = new StringBuilder(encodedValue.Length); stringBuilder.Append(encodedValue); DecodeRot13(stringBuilder, 0); return stringBuilder.ToString(); } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner.Render(logEvent, builder); if (builder.Length > orgLength) { DecodeRot13(builder, orgLength); } } protected override string Transform(string text) { throw new NotSupportedException(); } internal static void DecodeRot13(StringBuilder encodedValue, int startPos) { if (encodedValue != null) { for (int i = startPos; i < encodedValue.Length; i++) { encodedValue[i] = DecodeRot13Char(encodedValue[i]); } } } private static char DecodeRot13Char(char c) { if (c >= 'A' && c <= 'M') { return (char)(78 + (c - 65)); } if (c >= 'a' && c <= 'm') { return (char)(110 + (c - 97)); } if (c >= 'N' && c <= 'Z') { return (char)(65 + (c - 78)); } if (c >= 'n' && c <= 'z') { return (char)(97 + (c - 110)); } return c; } } [LayoutRenderer("substring")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class SubstringLayoutRendererWrapper : WrapperLayoutRendererBase { public int Start { get; set; } public int? Length { get; set; } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { if (Length != 0) { base.Inner?.Render(logEvent, builder); int num = builder.Length - orgLength; if (num > 0) { int num2 = CalcStart(num); int num3 = CalcLength(num, num2); string value = builder.ToString(orgLength + num2, num3); builder.Length = orgLength; builder.Append(value); } } } protected override string Transform(string text) { throw new NotSupportedException(); } private int CalcStart(int textLength) { int num = Start; if (num > textLength) { num = textLength; } if (num < 0) { num = textLength + num; if (num < 0) { num = 0; } } return num; } private int CalcLength(int textLength, int start) { int num = textLength - start; if (Length.HasValue && textLength > Length.Value + start) { num = Length.Value; } if (num < 0) { num = 0; } return num; } } [LayoutRenderer("trim-whitespace")] [AmbientProperty("TrimWhiteSpace")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class TrimWhiteSpaceLayoutRendererWrapper : WrapperLayoutRendererBase { public bool TrimWhiteSpace { get; set; } = true; protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner.Render(logEvent, builder); if (TrimWhiteSpace && builder.Length > orgLength) { TransformTrimWhiteSpaces(builder, orgLength); } } protected override string Transform(string text) { throw new NotSupportedException(); } private static void TransformTrimWhiteSpaces(StringBuilder builder, int startPos) { builder.TrimRight(startPos); if (builder.Length > startPos && char.IsWhiteSpace(builder[startPos])) { string text = builder.ToString(startPos, builder.Length - startPos); builder.Length = startPos; builder.Append(text.Trim()); } } } [LayoutRenderer("uppercase")] [AmbientProperty("Uppercase")] [AmbientProperty("ToUpper")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class UppercaseLayoutRendererWrapper : WrapperLayoutRendererBase { public bool Uppercase { get; set; } = true; public bool ToUpper { get { return Uppercase; } set { Uppercase = value; } } public CultureInfo Culture { get; set; } = CultureInfo.InvariantCulture; protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner.Render(logEvent, builder); if (Uppercase && builder.Length > orgLength) { TransformToUpperCase(builder, logEvent, orgLength); } } protected override string Transform(string text) { throw new NotSupportedException(); } private void TransformToUpperCase(StringBuilder target, LogEventInfo logEvent, int startPos) { CultureInfo culture = GetCulture(logEvent, Culture); for (int i = startPos; i < target.Length; i++) { target[i] = char.ToUpper(target[i], culture); } } } [LayoutRenderer("url-encode")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class UrlEncodeLayoutRendererWrapper : WrapperLayoutRendererBase { public bool SpaceAsPlus { get; set; } = true; public bool EscapeDataRfc3986 { get; set; } [Obsolete("Instead use default Rfc2396 or EscapeDataRfc3986. Marked obsolete with NLog v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public bool EscapeDataNLogLegacy { get; set; } protected override string Transform(string text) { if (!string.IsNullOrEmpty(text)) { UrlHelper.EscapeEncodingOptions uriStringEncodingFlags = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, SpaceAsPlus, EscapeDataRfc3986); StringBuilder stringBuilder = new StringBuilder(text.Length + 20); UrlHelper.EscapeDataEncode(text, stringBuilder, uriStringEncodingFlags); return stringBuilder.ToString(); } return string.Empty; } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner.Render(logEvent, builder); if (builder.Length > orgLength) { string source = builder.ToString(orgLength, builder.Length - orgLength); builder.Length = orgLength; UrlHelper.EscapeEncodingOptions uriStringEncodingFlags = UrlHelper.GetUriStringEncodingFlags(EscapeDataNLogLegacy, SpaceAsPlus, EscapeDataRfc3986); UrlHelper.EscapeDataEncode(source, builder, uriStringEncodingFlags); } } } [LayoutRenderer("whenEmpty")] [AmbientProperty("WhenEmpty")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class WhenEmptyLayoutRendererWrapper : WrapperLayoutRendererBase, IRawValue, IStringValueRenderer { private Func? _stringValueRenderer; public Layout WhenEmpty { get; set; } = Layout.Empty; protected override void InitializeLayoutRenderer() { _stringValueRenderer = null; if (WhenEmpty == null || WhenEmpty == Layout.Empty) { throw new NLogConfigurationException("WhenEmpty-LayoutRenderer WhenEmpty-property must be assigned."); } base.InitializeLayoutRenderer(); WhenEmpty.Initialize(base.LoggingConfiguration); Layout inner = base.Inner; SimpleLayout innerLayout = inner as SimpleLayout; if (innerLayout == null) { return; } inner = WhenEmpty; SimpleLayout whenEmptyLayout = inner as SimpleLayout; if (whenEmptyLayout == null) { return; } if (innerLayout.IsFixedText) { _stringValueRenderer = ResolveFixedWhenEmpty(innerLayout, whenEmptyLayout); } else if (innerLayout.IsSimpleStringText && (whenEmptyLayout.IsFixedText || whenEmptyLayout.IsSimpleStringText)) { _stringValueRenderer = delegate(LogEventInfo logEvent) { string text = innerLayout.Render(logEvent); return (!string.IsNullOrEmpty(text)) ? text : whenEmptyLayout.Render(logEvent); }; } } private static Func? ResolveFixedWhenEmpty(SimpleLayout innerLayout, SimpleLayout whenEmptyLayout) { SimpleLayout innerLayout2 = innerLayout; SimpleLayout whenEmptyLayout2 = whenEmptyLayout; if (!string.IsNullOrEmpty(innerLayout2.FixedText)) { return (LogEventInfo logEvent) => innerLayout2.FixedText ?? string.Empty; } if (whenEmptyLayout2.IsFixedText) { return (LogEventInfo logEvent) => whenEmptyLayout2.FixedText ?? string.Empty; } if (whenEmptyLayout2.IsSimpleStringText) { return (LogEventInfo logEvent) => whenEmptyLayout2.Render(logEvent); } return null; } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { base.Inner?.Render(logEvent, builder); if (builder.Length <= orgLength) { WhenEmpty.Render(logEvent, builder); } } protected override string Transform(string text) { throw new NotSupportedException(); } string? IStringValueRenderer.GetFormattedString(LogEventInfo logEvent) { return _stringValueRenderer?.Invoke(logEvent); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object? value) { Layout inner = base.Inner; if (inner != null && inner.TryGetRawValue(logEvent, out object rawValue)) { if (rawValue != null && !rawValue.Equals(string.Empty)) { value = rawValue; return true; } } else if (!string.IsNullOrEmpty(base.Inner?.Render(logEvent))) { value = null; return false; } return WhenEmpty.TryGetRawValue(logEvent, out value); } } [LayoutRenderer("when")] [AmbientProperty("When")] [ThreadAgnostic] public sealed class WhenLayoutRendererWrapper : WrapperLayoutRendererBase, IRawValue { public ConditionExpression? When { get; set; } public Layout Else { get; set; } = Layout.Empty; protected override void InitializeLayoutRenderer() { if (When == null) { throw new NLogConfigurationException("When-LayoutRenderer When-property must be assigned."); } base.InitializeLayoutRenderer(); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { int length = builder.Length; try { if (ShouldRenderInner(logEvent)) { base.Inner?.Render(logEvent, builder); } else { Else?.Render(logEvent, builder); } } catch { builder.Length = length; throw; } } protected override string Transform(string text) { throw new NotSupportedException(); } private bool ShouldRenderInner(LogEventInfo logEvent) { if (When != null) { return true.Equals(When.Evaluate(logEvent)); } return true; } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object? value) { if (ShouldRenderInner(logEvent)) { return TryGetRawValueFromLayout(logEvent, base.Inner, out value); } return TryGetRawValueFromLayout(logEvent, Else, out value); } private static bool TryGetRawValueFromLayout(LogEventInfo logEvent, Layout layout, out object? value) { if (layout == null) { value = null; return false; } return layout.TryGetRawValue(logEvent, out value); } } [LayoutRenderer("wrapline")] [AmbientProperty("WrapLine")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class WrapLineLayoutRendererWrapper : WrapperLayoutRendererBase { public int WrapLine { get; set; } = 80; protected override string Transform(string text) { if (WrapLine <= 0) { return text; } int num = WrapLine; if (text.Length <= num) { return text; } StringBuilder stringBuilder = new StringBuilder(text.Length + text.Length / num * Environment.NewLine.Length); for (int i = 0; i < text.Length; i += num) { if (num + i > text.Length) { num = text.Length - i; } stringBuilder.Append(text.AsSpan(i, num)); if (num + i < text.Length) { stringBuilder.AppendLine(); } } return stringBuilder.ToString(); } } public abstract class WrapperLayoutRendererBase : LayoutRenderer { [DefaultParameter] public Layout Inner { get; set; } = Layout.Empty; protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); Inner?.Initialize(base.LoggingConfiguration); } protected override void Append(StringBuilder builder, LogEventInfo logEvent) { int length = builder.Length; try { RenderInnerAndTransform(logEvent, builder, length); } catch { builder.Length = length; throw; } } protected virtual void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { string text = RenderInner(logEvent); builder.Append(Transform(logEvent, text)); } protected virtual string Transform(LogEventInfo logEvent, string text) { return Transform(text); } protected abstract string Transform(string text); protected virtual string RenderInner(LogEventInfo logEvent) { return Inner?.Render(logEvent) ?? string.Empty; } } [Obsolete("Inherit from WrapperLayoutRendererBase and override RenderInnerAndTransform() instead. Marked obsolete in NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public abstract class WrapperLayoutRendererBuilderBase : WrapperLayoutRendererBase { protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { if (builder.Length > 0) { using (AppendBuilderCreator appendBuilderCreator = new AppendBuilderCreator(mustBeEmpty: true)) { RenderFormattedMessage(logEvent, appendBuilderCreator.Builder); TransformFormattedMesssage(logEvent, appendBuilderCreator.Builder); appendBuilderCreator.Builder.CopyTo(builder); return; } } RenderFormattedMessage(logEvent, builder); TransformFormattedMesssage(logEvent, builder); } [Obsolete("Inherit from WrapperLayoutRendererBase and override RenderInnerAndTransform() instead. Marked obsolete in NLog 4.6")] protected virtual void TransformFormattedMesssage(LogEventInfo logEvent, StringBuilder target) { TransformFormattedMesssage(target); } [Obsolete("Inherit from WrapperLayoutRendererBase and override RenderInnerAndTransform() instead. Marked obsolete in NLog 4.6")] protected abstract void TransformFormattedMesssage(StringBuilder target); [Obsolete("Inherit from WrapperLayoutRendererBase and override RenderInnerAndTransform() instead. Marked obsolete in NLog 4.6")] protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { base.Inner?.Render(logEvent, target); } protected sealed override string Transform(string text) { throw new NotSupportedException("Inherit from WrapperLayoutRendererBase and override RenderInnerAndTransform()"); } protected sealed override string RenderInner(LogEventInfo logEvent) { throw new NotSupportedException("Inherit from WrapperLayoutRendererBase and override RenderInnerAndTransform()"); } } [LayoutRenderer("xml-encode")] [AmbientProperty("XmlEncode")] [AppDomainFixedOutput] [ThreadAgnostic] public sealed class XmlEncodeLayoutRendererWrapper : WrapperLayoutRendererBase { private INoAllocationStringValueRenderer? _stringValueRenderer; private Layout? _orgInner; public bool XmlEncode { get; set; } = true; public bool CDataEncode { get; set; } public bool XmlEncodeNewlines { get; set; } protected override void InitializeLayoutRenderer() { base.InitializeLayoutRenderer(); _stringValueRenderer = ValueTypeLayoutInfo.ResolveStringValueMethod(base.Inner); _orgInner = ((_stringValueRenderer == null) ? null : base.Inner); } protected override void RenderInnerAndTransform(LogEventInfo logEvent, StringBuilder builder, int orgLength) { if (_stringValueRenderer != null && base.Inner == _orgInner) { string formattedStringNoAllocation = _stringValueRenderer.GetFormattedStringNoAllocation(logEvent); if (formattedStringNoAllocation != null) { if (CDataEncode) { XmlHelper.EscapeCData(formattedStringNoAllocation, builder); } else if (XmlEncode) { XmlHelper.EscapeXmlWhenNeeded(formattedStringNoAllocation, XmlEncodeNewlines, builder); } else { builder.Append(formattedStringNoAllocation); } return; } } if (CDataEncode) { builder.Append(""); } else if (XmlEncode) { XmlHelper.EscapeXmlWhenNeeded(builder, orgLength, XmlEncodeNewlines); } } protected override string Transform(string text) { if (CDataEncode) { return XmlHelper.EscapeCData(text); } if (XmlEncode) { return XmlHelper.EscapeXmlWhenNeeded(text, XmlEncodeNewlines); } return text; } } } namespace NLog.Internal { internal struct AppendBuilderCreator : IDisposable { private static readonly StringBuilderPool _builderPool = new StringBuilderPool(Environment.ProcessorCount * 2); private StringBuilderPool.ItemHolder _builder; public StringBuilder Builder => _builder.Item; public AppendBuilderCreator(bool mustBeEmpty) { _builder = _builderPool.Acquire(); } public void Dispose() { _builder.Dispose(); } } internal static class ArrayHelper { internal static T[] Empty() { return Array.Empty(); } } internal static class AssemblyHelpers { [UnconditionalSuppressMessage("Returns empty string for assemblies embedded in a single-file app", "IL3000")] public static string GetAssemblyFileLocation(Assembly? assembly) { return assembly?.Location ?? string.Empty; } public static void LogAssemblyVersion(Assembly assembly) { try { if (InternalLogger.IsInfoEnabled) { string text = assembly.GetFirstCustomAttribute()?.Version; string text2 = assembly.GetFirstCustomAttribute()?.InformationalVersion; bool flag = false; InternalLogger.Info("{0}. File version: {1}. Product version: {2}. GlobalAssemblyCache: {3}", new ReadOnlySpan(new object[4] { assembly.FullName, text, text2, flag })); } } catch (Exception ex) { InternalLogger.Error(ex, "Error logging version of assembly {0}.", new ReadOnlySpan(new object[1] { assembly?.FullName })); } } } internal sealed class AsyncOperationCounter { private int _pendingOperationCounter; private readonly LinkedList _pendingCompletionList = new LinkedList(); public void BeginOperation() { Interlocked.Increment(ref _pendingOperationCounter); } public void CompleteOperation(Exception? exception) { NotifyCompletion(exception); } private int NotifyCompletion(Exception? exception) { int result = Interlocked.Decrement(ref _pendingOperationCounter); if (_pendingCompletionList.Count > 0) { lock (_pendingCompletionList) { LinkedListNode linkedListNode = _pendingCompletionList.First; while (linkedListNode != null) { AsyncContinuation value = linkedListNode.Value; linkedListNode = linkedListNode.Next; value?.Invoke(exception); } } } return result; } public AsyncContinuation RegisterCompletionNotification(AsyncContinuation asyncContinuation) { AsyncContinuation asyncContinuation2 = asyncContinuation; int remainingCompletionCounter = Interlocked.Increment(ref _pendingOperationCounter); if (remainingCompletionCounter <= 1) { if (NotifyCompletion(null) < 0) { Interlocked.Exchange(ref _pendingOperationCounter, 0); } return asyncContinuation2; } lock (_pendingCompletionList) { if (NotifyCompletion(null) <= 0) { return asyncContinuation2; } LinkedListNode pendingCompletion = new LinkedListNode(null); _pendingCompletionList.AddLast(pendingCompletion); remainingCompletionCounter = Interlocked.Increment(ref _pendingOperationCounter); if (remainingCompletionCounter <= 0) { remainingCompletionCounter = 1; } pendingCompletion.Value = delegate(Exception? ex) { if (Interlocked.Decrement(ref remainingCompletionCounter) == 0) { lock (_pendingCompletionList) { _pendingCompletionList.Remove(pendingCompletion); NotifyCompletion(ex); } asyncContinuation2(ex); } }; return pendingCompletion.Value; } } public void Clear() { _pendingCompletionList.Clear(); Interlocked.Exchange(ref _pendingOperationCounter, 0); } } internal sealed class CallSiteInformation { private static readonly object lockObject = new object(); private static ICollection _hiddenAssemblies = ArrayHelper.Empty(); private static ICollection _hiddenTypes = ArrayHelper.Empty(); [Obsolete("Instead use ${callsite} or CallerMemberName. Marked obsolete on NLog 5.3")] public StackFrame? UserStackFrame => StackTrace?.GetFrame(UserStackFrameNumberLegacy ?? UserStackFrameNumber); public int UserStackFrameNumber { get; private set; } public int? UserStackFrameNumberLegacy { get; private set; } public StackTrace? StackTrace { get; private set; } public string? CallerClassName { get; internal set; } public string? CallerMethodName { get; private set; } public string? CallerFilePath { get; private set; } public int? CallerLineNumber { get; private set; } internal static bool IsHiddenAssembly(Assembly assembly) { if (_hiddenAssemblies.Count != 0) { return _hiddenAssemblies.Contains(assembly); } return false; } internal static bool IsHiddenClassType(Type type) { if (_hiddenTypes.Count != 0) { return _hiddenTypes.Contains(type); } return false; } public static void AddCallSiteHiddenAssembly(Assembly assembly) { if (_hiddenAssemblies.Contains(assembly) || (object)assembly == null) { return; } lock (lockObject) { if (_hiddenAssemblies.Contains(assembly)) { return; } _hiddenAssemblies = new HashSet(_hiddenAssemblies) { assembly }; } InternalLogger.Trace("Assembly '{0}' will be hidden in callsite stacktrace", assembly.FullName); } public static void AddCallSiteHiddenClassType(Type classType) { if (_hiddenTypes.Contains(classType) || (object)classType == null) { return; } lock (lockObject) { if (_hiddenTypes.Contains(classType)) { return; } _hiddenTypes = new HashSet(_hiddenTypes) { classType }; } InternalLogger.Trace("Type '{0}' will be hidden in callsite stacktrace", classType); } public void SetStackTrace(StackTrace stackTrace, int? userStackFrame = null, Type? loggerType = null) { StackTrace = stackTrace; if (!userStackFrame.HasValue && stackTrace != null) { StackFrame[] frames = stackTrace.GetFrames(); int? num = ((loggerType != null) ? FindCallingMethodOnStackTrace(frames, loggerType) : new int?(0)); int? num2 = (num.HasValue ? new int?(SkipToUserStackFrameLegacy(frames, num.Value)) : num); UserStackFrameNumber = num.GetValueOrDefault(); UserStackFrameNumberLegacy = ((num2 != num) ? num2 : null); } else { UserStackFrameNumber = userStackFrame.GetValueOrDefault(); UserStackFrameNumberLegacy = null; } } public void SetCallerInfo(string? callerClassName, string? callerMethodName, string? callerFilePath, int callerLineNumber) { CallerClassName = callerClassName; CallerMethodName = callerMethodName; CallerFilePath = callerFilePath; CallerLineNumber = callerLineNumber; } public MethodBase? GetCallerStackFrameMethod(int skipFrames) { return StackTraceUsageUtils.GetStackMethod(StackTrace?.GetFrame(UserStackFrameNumber + skipFrames)); } public string GetCallerClassName(MethodBase? method, bool includeNameSpace, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { string text = CallerClassName ?? string.Empty; if (!string.IsNullOrEmpty(text)) { if (includeNameSpace) { return text; } int num = text.LastIndexOf('.'); if (num < 0 || num >= text.Length - 1) { return text; } return text.Substring(num + 1); } method = method ?? GetCallerStackFrameMethod(0); if ((object)method == null) { return string.Empty; } cleanAsyncMoveNext = cleanAsyncMoveNext || UserStackFrameNumberLegacy.HasValue; cleanAnonymousDelegates = cleanAnonymousDelegates || UserStackFrameNumberLegacy.HasValue; return StackTraceUsageUtils.GetStackFrameMethodClassName(method, includeNameSpace, cleanAsyncMoveNext, cleanAnonymousDelegates) ?? string.Empty; } public string GetCallerMethodName(MethodBase? method, bool includeMethodInfo, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { string text = CallerMethodName ?? string.Empty; if (!string.IsNullOrEmpty(text)) { return text; } method = method ?? GetCallerStackFrameMethod(0); if ((object)method == null) { return string.Empty; } cleanAsyncMoveNext = cleanAsyncMoveNext || UserStackFrameNumberLegacy.HasValue; cleanAnonymousDelegates = cleanAnonymousDelegates || UserStackFrameNumberLegacy.HasValue; return StackTraceUsageUtils.GetStackFrameMethodName(method, includeMethodInfo, cleanAsyncMoveNext, cleanAnonymousDelegates) ?? string.Empty; } public string GetCallerFilePath(int skipFrames) { string text = CallerFilePath ?? string.Empty; if (!string.IsNullOrEmpty(text)) { return text; } return (StackTrace?.GetFrame(UserStackFrameNumber + skipFrames))?.GetFileName() ?? string.Empty; } public int GetCallerLineNumber(int skipFrames) { if (CallerLineNumber.HasValue) { return CallerLineNumber.Value; } return (StackTrace?.GetFrame(UserStackFrameNumber + skipFrames))?.GetFileLineNumber() ?? 0; } private static int? FindCallingMethodOnStackTrace(StackFrame[] stackFrames, Type loggerType) { if (stackFrames == null || stackFrames.Length == 0) { return null; } int? num = null; int? num2 = null; for (int i = 0; i < stackFrames.Length; i++) { MethodBase stackMethod = StackTraceUsageUtils.GetStackMethod(stackFrames[i]); if (!SkipStackFrameWhenHidden(stackMethod)) { if (!num2.HasValue) { num2 = i; } if (SkipStackFrameWhenLoggerType(stackMethod, loggerType)) { num = null; } else if (!num.HasValue) { num = i; } } } return num ?? num2; } private static int SkipToUserStackFrameLegacy(StackFrame[] stackFrames, int firstUserStackFrame) { for (int i = firstUserStackFrame; i < stackFrames.Length; i++) { MethodBase stackMethod = StackTraceUsageUtils.GetStackMethod(stackFrames[i]); if (SkipStackFrameWhenHidden(stackMethod)) { continue; } if (stackMethod?.Name == "MoveNext" && stackFrames.Length > i) { Type type = StackTraceUsageUtils.GetStackMethod(stackFrames[i + 1])?.DeclaringType; if (type?.Namespace == "System.Runtime.CompilerServices" || type == typeof(ExecutionContext)) { continue; } } return i; } return firstUserStackFrame; } private static bool SkipStackFrameWhenHidden(MethodBase? stackMethod) { if ((object)stackMethod == null) { return true; } Assembly assembly = StackTraceUsageUtils.LookupAssemblyFromMethod(stackMethod); if ((object)assembly == null || IsHiddenAssembly(assembly)) { return true; } Type declaringType = stackMethod.DeclaringType; if (declaringType != null && IsHiddenClassType(declaringType)) { return true; } return false; } private static bool SkipStackFrameWhenLoggerType(MethodBase? stackMethod, Type loggerType) { Type type = stackMethod?.DeclaringType; if (type != null) { if (!(loggerType == type) && !type.IsSubclassOf(loggerType)) { return loggerType.IsAssignableFrom(type); } return true; } return false; } } internal static class CollectionExtensions { public static IList Filter(this IList items, TState state, Func filter) { bool flag = false; List list = null; for (int i = 0; i < items.Count; i++) { TItem val = items[i]; if (filter(val, state)) { if (flag && list == null) { list = new List(); } list?.Add(val); continue; } if (!flag && i > 0) { list = new List(); for (int j = 0; j < i; j++) { list.Add(items[j]); } } flag = true; } IList list2 = list; IList list3 = list2; if (list3 == null) { if (!flag) { return items; } list2 = ArrayHelper.Empty(); list3 = list2; } return list3; } } [DebuggerDisplay("Count = {Count}")] internal sealed class ConfigVariablesDictionary : IDictionary, ICollection>, IEnumerable>, IEnumerable { private readonly ThreadSafeDictionary _variables = new ThreadSafeDictionary(StringComparer.OrdinalIgnoreCase); private readonly LoggingConfiguration _configuration; private ThreadSafeDictionary? _dynamicVariables; private ThreadSafeDictionary? _apiVariables; public int Count => _variables.Count; public ICollection Keys => _variables.Keys; public ICollection Values => _variables.Values; public Layout this[string key] { get { return _variables[key]; } set { _variables[key] = value; RegisterApiVariable(key); } } bool ICollection>.IsReadOnly => false; public ConfigVariablesDictionary(LoggingConfiguration configuration) { _configuration = configuration; } public void InsertParsedConfigVariable(string key, Layout value, bool keepVariablesOnReload) { if (keepVariablesOnReload) { ThreadSafeDictionary? apiVariables = _apiVariables; if (apiVariables != null && apiVariables.ContainsKey(key) && _variables.ContainsKey(key)) { return; } } _variables[key] = value; _dynamicVariables?.Remove(key); } public bool TryLookupDynamicVariable(string key, out Layout dynamicLayout) { if (_dynamicVariables == null) { if (!_variables.TryGetValue(key, out dynamicLayout)) { return false; } Interlocked.CompareExchange(ref _dynamicVariables, new ThreadSafeDictionary(_variables.Comparer), null); } bool result = true; if (!_dynamicVariables.TryGetValue(key, out dynamicLayout)) { result = false; if (_variables.TryGetValue(key, out dynamicLayout)) { result = true; if (dynamicLayout != null) { dynamicLayout.Initialize(_configuration); _dynamicVariables[key] = dynamicLayout; } } } return result; } public void PrepareForReload(ConfigVariablesDictionary oldVariables) { if (oldVariables._apiVariables == null) { return; } foreach (KeyValuePair apiVariable in oldVariables._apiVariables) { if (oldVariables._variables.TryGetValue(apiVariable.Key, out Layout value)) { _variables[apiVariable.Key] = value; RegisterApiVariable(apiVariable.Key); } } } public bool ContainsKey(string key) { return _variables.ContainsKey(key); } public bool TryGetValue(string key, out Layout value) { return _variables.TryGetValue(key, out value); } IEnumerator> IEnumerable>.GetEnumerator() { return _variables.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _variables.GetEnumerator(); } public ThreadSafeDictionary.Enumerator GetEnumerator() { return _variables.GetEnumerator(); } public void Add(string key, Layout value) { _variables.Add(key, value); RegisterApiVariable(key); } public bool Remove(string key) { _apiVariables?.Remove(key); _dynamicVariables?.Remove(key); return _variables.Remove(key); } public void Clear() { _variables.Clear(); _apiVariables?.Clear(); _dynamicVariables?.Clear(); } bool ICollection>.Contains(KeyValuePair item) { return _variables.Contains(item); } void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { _variables.CopyTo(array, arrayIndex); } void ICollection>.Add(KeyValuePair item) { Add(item.Key, item.Value); } bool ICollection>.Remove(KeyValuePair item) { return Remove(item.Key); } private void RegisterApiVariable(string key) { if (_apiVariables == null) { Interlocked.CompareExchange(ref _apiVariables, new ThreadSafeDictionary(_variables.Comparer), null); } _apiVariables[key] = true; _dynamicVariables?.Remove(key); } } internal readonly struct DictionaryEntryEnumerable : IEnumerable, IEnumerable { internal readonly struct DictionaryEntryEnumerator : IEnumerator, IEnumerator, IDisposable { private readonly IDictionaryEnumerator _entryEnumerator; public DictionaryEntry Current => _entryEnumerator.Entry; object IEnumerator.Current => Current; public DictionaryEntryEnumerator(IDictionary? dictionary) { _entryEnumerator = ((dictionary != null && dictionary.Count > 0) ? dictionary.GetEnumerator() : EmptyDictionaryEnumerator.Default); } public void Dispose() { if (_entryEnumerator is IDisposable disposable) { disposable.Dispose(); } } public bool MoveNext() { return _entryEnumerator.MoveNext(); } public void Reset() { _entryEnumerator.Reset(); } } private sealed class EmptyDictionaryEnumerator : IDictionaryEnumerator, IEnumerator { public static readonly IDictionaryEnumerator Default = new EmptyDictionaryEnumerator(); public DictionaryEntry Entry => default(DictionaryEntry); public object Key => string.Empty; public object? Value => null; object? IEnumerator.Current => Entry; public bool MoveNext() { return false; } public void Reset() { } } private readonly IDictionary? _dictionary; public DictionaryEntryEnumerable(IDictionary? dictionary) { _dictionary = dictionary; } public DictionaryEntryEnumerator GetEnumerator() { return new DictionaryEntryEnumerator(_dictionary); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal static class EnvironmentHelper { internal static string GetMachineName() { try { return Environment.MachineName; } catch (SecurityException) { return string.Empty; } } internal static string GetSafeEnvironmentVariable(string name) { try { return Environment.GetEnvironmentVariable(name) ?? string.Empty; } catch (SecurityException) { return string.Empty; } } } internal static class ExceptionHelper { private const string LoggedKey = "NLog.ExceptionLoggedToInternalLogger"; public static void MarkAsLoggedToInternalLogger(this Exception exception) { if (exception != null) { exception.Data["NLog.ExceptionLoggedToInternalLogger"] = true; } } public static bool IsLoggedToInternalLogger(this Exception exception) { if (exception != null && exception.Data?.Count > 0) { return (exception.Data["NLog.ExceptionLoggedToInternalLogger"] as bool?).GetValueOrDefault(); } return false; } public static bool MustBeRethrown(this Exception exception, IInternalLoggerContext? loggerContext = null, string? callerMemberName = null) { if (exception.MustBeRethrownImmediately()) { return true; } bool num = exception is NLogConfigurationException; LogFactory logFactory = loggerContext?.LogFactory; bool flag = (logFactory != null && logFactory.ThrowExceptions) || LogManager.ThrowExceptions; bool flag2 = ((!num) ? flag : (logFactory?.ThrowConfigExceptions ?? LogManager.ThrowConfigExceptions.GetValueOrDefault(flag))); if (!exception.IsLoggedToInternalLogger()) { LogLevel level = (flag2 ? LogLevel.Error : LogLevel.Warn); if (loggerContext != null) { if (string.IsNullOrEmpty(callerMemberName)) { InternalLogger.Log(exception, level, "{0}: Error has been raised.", new ReadOnlySpan(new object[1] { loggerContext })); } else { InternalLogger.Log(exception, level, "{0}: Exception in {1}", new ReadOnlySpan(new object[2] { loggerContext, callerMemberName })); } } else { InternalLogger.Log(exception, level, "Error has been raised."); } } return flag2; } public static bool MustBeRethrownImmediately(this Exception exception) { if (exception is StackOverflowException) { return true; } if (exception is ThreadAbortException) { return true; } if (exception is OutOfMemoryException) { return true; } return false; } } internal sealed class ExceptionMessageFormatProvider : IFormatProvider, ICustomFormatter { internal static readonly ExceptionMessageFormatProvider Instance = new ExceptionMessageFormatProvider(); string ICustomFormatter.Format(string? format, object? arg, IFormatProvider? formatProvider) { if (arg is Exception exception) { Exception primaryException = GetPrimaryException(exception); return primaryException.GetType().ToString() + ": " + primaryException.Message; } return $"{arg}"; } private static Exception GetPrimaryException(Exception exception) { if (exception is AggregateException ex) { ReadOnlyCollection innerExceptions = ex.InnerExceptions; if (innerExceptions != null && innerExceptions.Count == 1) { Exception ex2 = ex.InnerExceptions[0]; if (!(ex2 is AggregateException)) { return ex2; } } AggregateException ex3 = ex.Flatten(); ReadOnlyCollection innerExceptions2 = ex3.InnerExceptions; if (innerExceptions2 != null && innerExceptions2.Count == 1) { return ex3.InnerExceptions[0]; } } return exception; } object? IFormatProvider.GetFormat(Type? formatType) { if (!(formatType == typeof(ICustomFormatter))) { return null; } return this; } } internal static class FileInfoHelper { internal const int MinReliableBirthYear = 1980; public static DateTime LookupValidFileCreationTimeUtc(this FileInfo fileInfo) { return LookupValidFileCreationTimeUtc(fileInfo, (FileInfo f) => f.CreationTimeUtc, (FileInfo f) => f.LastWriteTimeUtc); } private static DateTime LookupValidFileCreationTimeUtc(T fileInfo, Func primary, Func fallback, Func? finalFallback = null) { DateTime result = primary(fileInfo); if (result.Year < 1980 && !PlatformDetector.IsWin32) { result = fallback(fileInfo); if (finalFallback != null && result.Year < 1980) { result = finalFallback(fileInfo); } } return result; } public static bool IsRelativeFilePath(string filepath) { filepath = filepath?.TrimStart(ArrayHelper.Empty()) ?? string.Empty; if (string.IsNullOrEmpty(filepath)) { return false; } char c = filepath[0]; if (c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar) { return false; } if (c == '.') { return true; } if (filepath.Length >= 2 && filepath[1] == Path.VolumeSeparatorChar && Path.VolumeSeparatorChar != Path.DirectorySeparatorChar) { return false; } return true; } } internal static class FormatHelper { internal static string ConvertToString(object? value, IFormatProvider? formatProvider) { if (value is string result) { return result; } if (value == null) { return string.Empty; } if (formatProvider == null && value is IFormattable) { formatProvider = LogManager.LogFactory.DefaultCultureInfo; } return Convert.ToString(value, formatProvider) ?? string.Empty; } internal static string? TryFormatToString(object? value, string? format, IFormatProvider? formatProvider) { if (value is IFormattable formattable) { return formattable.ToString(format, formatProvider); } if (value is IConvertible convertible) { return convertible.ToString(formatProvider); } if (value == null) { return string.Empty; } return null; } } internal static class Guard { internal static T ThrowIfNull(T arg, [CallerArgumentExpression("arg")] string param = "") where T : class { if (arg == null) { throw new ArgumentNullException(string.IsNullOrEmpty(param) ? typeof(T).Name : param); } return arg; } internal static string ThrowIfNullOrEmpty(string arg, [CallerArgumentExpression("arg")] string param = "") { if (string.IsNullOrEmpty(arg)) { throw new ArgumentNullException(string.IsNullOrEmpty(param) ? "arg" : param); } return arg; } } internal interface ILogMessageFormatter { bool? EnableMessageTemplateParser { get; } string FormatMessage(LogEventInfo logEvent); bool HasProperties(LogEventInfo logEvent); void AppendFormattedMessage(LogEventInfo logEvent, StringBuilder builder); } internal interface INoAllocationStringValueRenderer : IStringValueRenderer { string? GetFormattedStringNoAllocation(LogEventInfo logEvent); } internal interface IRawValue { bool TryGetRawValue(LogEventInfo logEvent, out object? value); } internal interface IRenderable { string Render(LogEventInfo logEvent); } internal interface IStringValueRenderer { string? GetFormattedString(LogEventInfo logEvent); } internal interface ISupportsInitialize { void Initialize(LoggingConfiguration? configuration); void Close(); } internal interface ITargetWithFilterChain { void WriteToLoggerTargets(Type loggerType, LogEventInfo logEvent, LogFactory logFactory); } internal sealed class LogMessageStringFormatter : ILogMessageFormatter { public static readonly LogMessageStringFormatter Default = new LogMessageStringFormatter(); public LogMessageFormatter MessageFormatter { get; } public bool? EnableMessageTemplateParser => false; private LogMessageStringFormatter() { MessageFormatter = FormatMessage; } public void AppendFormattedMessage(LogEventInfo logEvent, StringBuilder builder) { builder.Append(logEvent.FormattedMessage); } public string FormatMessage(LogEventInfo logEvent) { if (HasParameters(logEvent)) { return string.Format(logEvent.FormatProvider ?? CultureInfo.CurrentCulture, logEvent.Message, logEvent.Parameters); } return logEvent.Message; } internal static bool HasParameters(LogEventInfo logEvent) { object?[]? parameters = logEvent.Parameters; if (parameters != null && parameters.Length != 0) { return !string.IsNullOrEmpty(logEvent.Message); } return false; } public bool HasProperties(LogEventInfo logEvent) { return false; } } internal sealed class LogMessageTemplateFormatter : ILogMessageFormatter { private static readonly StringBuilderPool _builderPool = new StringBuilderPool(Environment.ProcessorCount * 2); private readonly LogFactory _logFactory; private IValueFormatter? _valueFormatter; private readonly bool _forceMessageTemplateRenderer; private readonly bool _singleTargetOnly; private IValueFormatter ValueFormatter => _valueFormatter ?? (_valueFormatter = _logFactory.ServiceRepository.GetService()); public LogMessageFormatter MessageFormatter { get; } public bool? EnableMessageTemplateParser { get { if (!_forceMessageTemplateRenderer) { return null; } return true; } } public LogMessageTemplateFormatter(LogFactory logFactory, bool forceMessageTemplateRenderer, bool singleTargetOnly) { _logFactory = logFactory; _forceMessageTemplateRenderer = forceMessageTemplateRenderer; _singleTargetOnly = singleTargetOnly; MessageFormatter = FormatMessage; } public bool HasProperties(LogEventInfo logEvent) { if (!LogMessageStringFormatter.HasParameters(logEvent)) { return false; } if (_singleTargetOnly) { TemplateEnumerator templateEnumerator = new TemplateEnumerator(logEvent.Message); if (!templateEnumerator.MoveNext() || templateEnumerator.Current.MaybePositionalTemplate) { return false; } } return true; } public void AppendFormattedMessage(LogEventInfo logEvent, StringBuilder builder) { if (_singleTargetOnly) { object?[]? parameters = logEvent.Parameters; if (parameters != null && parameters.Length != 0) { Render(logEvent.Message, logEvent.FormatProvider ?? _logFactory.DefaultCultureInfo ?? CultureInfo.CurrentCulture, logEvent.Parameters, builder, out IList _); return; } } builder.Append(logEvent.FormattedMessage); } public string FormatMessage(LogEventInfo logEvent) { object[] parameters = logEvent.Parameters; if (parameters != null && parameters.Length != 0 && !string.IsNullOrEmpty(logEvent.Message)) { StringBuilderPool.ItemHolder itemHolder = _builderPool.Acquire(); try { AppendToBuilder(logEvent, parameters, itemHolder.Item); return itemHolder.Item.ToString(); } finally { ((IDisposable)itemHolder).Dispose(); } } return logEvent.Message; } private void AppendToBuilder(LogEventInfo logEvent, object?[] parameters, StringBuilder builder) { Render(logEvent.Message, logEvent.FormatProvider ?? _logFactory.DefaultCultureInfo ?? CultureInfo.CurrentCulture, parameters, builder, out IList messageTemplateParameters); logEvent.TryCreatePropertiesInternal(messageTemplateParameters ?? ArrayHelper.Empty()); } private void Render(string template, IFormatProvider? formatProvider, object?[] parameters, StringBuilder sb, out IList? messageTemplateParameters) { messageTemplateParameters = null; TemplateEnumerator templateEnumerator = new TemplateEnumerator(template); if (!templateEnumerator.MoveNext() || (templateEnumerator.Current.MaybePositionalTemplate && !_forceMessageTemplateRenderer)) { sb.AppendFormat(formatProvider, template, parameters); return; } int num = 0; int num2 = 0; int holeStartPosition = 0; int length = sb.Length; do { Literal literal = templateEnumerator.Current.Literal; sb.Append(template, num, literal.Print); num += literal.Print; if (literal.Skip == 0) { num++; continue; } num += literal.Skip; Hole hole = templateEnumerator.Current.Hole; if (hole.Alignment != 0) { holeStartPosition = sb.Length; } if (hole.Index != -1 && messageTemplateParameters == null) { num2++; RenderHolePositional(sb, in hole, formatProvider, parameters[hole.Index]); } else { object value = parameters[num2]; if (messageTemplateParameters == null) { messageTemplateParameters = new MessageTemplateParameter[parameters.Length]; if (num2 != 0) { templateEnumerator = new TemplateEnumerator(template); sb.Length = length; num2 = 0; num = 0; continue; } } messageTemplateParameters[num2++] = new MessageTemplateParameter(hole.Name, value, hole.Format, hole.CaptureType); RenderHole(sb, in hole, formatProvider, value); } if (hole.Alignment != 0) { RenderPadding(sb, hole.Alignment, holeStartPosition); } } while (templateEnumerator.MoveNext()); messageTemplateParameters = VerifyMessageTemplateParameters(messageTemplateParameters, num2); } internal string Render(ref TemplateEnumerator templateEnumerator, IFormatProvider? formatProvider, in ReadOnlySpan parameters, out IList? messageTemplateParameters) { messageTemplateParameters = null; StringBuilderPool.ItemHolder itemHolder = _builderPool.Acquire(); try { StringBuilder item = itemHolder.Item; string template = templateEnumerator.Template; int num = 0; int holeStartPosition = 0; int num2 = 0; do { Literal literal = templateEnumerator.Current.Literal; item.Append(template, num, literal.Print); num += literal.Print; if (literal.Skip == 0) { num++; continue; } num += literal.Skip; Hole hole = templateEnumerator.Current.Hole; if (hole.Alignment != 0) { holeStartPosition = item.Length; } if (hole.Index != -1 && messageTemplateParameters == null) { num2++; RenderHolePositional(item, in hole, formatProvider, parameters[hole.Index]); } else { object value = parameters[num2]; if (messageTemplateParameters == null) { messageTemplateParameters = new MessageTemplateParameter[parameters.Length]; if (num2 != 0) { templateEnumerator = new TemplateEnumerator(template); item.ClearBuilder(); num2 = 0; num = 0; continue; } } messageTemplateParameters[num2++] = new MessageTemplateParameter(hole.Name, value, hole.Format, hole.CaptureType); RenderHole(item, in hole, formatProvider, value); } if (hole.Alignment != 0) { RenderPadding(item, hole.Alignment, holeStartPosition); } } while (templateEnumerator.MoveNext()); messageTemplateParameters = VerifyMessageTemplateParameters(messageTemplateParameters, num2); return item.ToString(); } finally { ((IDisposable)itemHolder).Dispose(); } } private static IList? VerifyMessageTemplateParameters(IList? messageTemplateParameters, int holeIndex) { if (messageTemplateParameters != null && holeIndex != messageTemplateParameters.Count) { MessageTemplateParameter[] array = new MessageTemplateParameter[holeIndex]; for (int i = 0; i < array.Length; i++) { array[i] = messageTemplateParameters[i]; } messageTemplateParameters = array; } return messageTemplateParameters; } private void RenderHolePositional(StringBuilder sb, in Hole hole, IFormatProvider? formatProvider, object? value) { if (hole.CaptureType == CaptureType.Serialize || (value == null && hole.CaptureType != CaptureType.Stringify)) { RenderHole(sb, hole.CaptureType, hole.Format, formatProvider, value); } else { ValueFormatter.FormatValue(value, hole.Format, CaptureType.Stringify, formatProvider, sb); } } private void RenderHole(StringBuilder sb, in Hole hole, IFormatProvider? formatProvider, object? value) { RenderHole(sb, hole.CaptureType, hole.Format, formatProvider, value); } private void RenderHole(StringBuilder sb, CaptureType captureType, string? holeFormat, IFormatProvider? formatProvider, object? value) { if (captureType == CaptureType.Stringify) { sb.Append('"'); ValueFormatter.FormatValue(value, holeFormat, captureType, formatProvider, sb); sb.Append('"'); } else if (value == null) { sb.Append("NULL"); } else { ValueFormatter.FormatValue(value, holeFormat, captureType, formatProvider, sb); } } private static void RenderPadding(StringBuilder sb, int holeAlignment, int holeStartPosition) { int num = sb.Length - holeStartPosition; int num2 = Math.Abs(holeAlignment) - num; if (num2 > 0) { if (holeAlignment < 0 || num == 0) { sb.Append(' ', num2); return; } string value = sb.ToString(holeStartPosition, num); sb.Length = holeStartPosition; sb.Append(' ', num2); sb.Append(value); } } } internal sealed class MruCache where TKey : notnull { private readonly struct MruCacheItem { public readonly TValue Value; public readonly long Version; public readonly bool Virgin; public MruCacheItem(TValue value, long version, bool virgin) { Value = value; Version = version; Virgin = virgin; } } private readonly Dictionary _dictionary; private readonly int _maxCapacity; private long _currentVersion; public MruCache(int maxCapacity) { _maxCapacity = maxCapacity; _dictionary = new Dictionary(_maxCapacity / 4); _currentVersion = 1L; } public bool TryAddValue(TKey key, TValue value) { lock (_dictionary) { if (_dictionary.TryGetValue(key, out var value2)) { long currentVersion = _currentVersion; if (value2.Version != currentVersion || !EqualityComparer.Default.Equals(value, value2.Value)) { _dictionary[key] = new MruCacheItem(value, currentVersion, virgin: false); } return false; } if (_dictionary.Count >= _maxCapacity) { _currentVersion++; PruneCache(); } _dictionary.Add(key, new MruCacheItem(value, _currentVersion, virgin: true)); return true; } } private void PruneCache() { long num = _currentVersion - 2; long num2 = 1L; List list = new List((int)((double)_dictionary.Count / 2.5)); for (int i = 0; i < 3; i++) { long num3 = _currentVersion - 5; switch (i) { case 0: num3 = _currentVersion - (int)((double)_maxCapacity / 1.5); break; case 1: num3 = _currentVersion - 10; break; } if (num3 < num2) { num3 = num2; } num2 = long.MaxValue; foreach (KeyValuePair item in _dictionary) { long version = item.Value.Version; if (version <= num3 || (item.Value.Virgin && (i != 0 || version < num))) { list.Add(item.Key); if ((double)(_dictionary.Count - list.Count) < (double)_maxCapacity / 1.5) { i = 3; break; } } else if (version < num2) { num2 = version; } } } foreach (TKey item2 in list) { _dictionary.Remove(item2); } if (_dictionary.Count >= _maxCapacity) { _dictionary.Clear(); } } public bool TryGetValue(TKey key, out TValue? value) { MruCacheItem value2; try { if (!_dictionary.TryGetValue(key, out value2)) { value = default(TValue); return false; } } catch { value2 = default(MruCacheItem); } if (value2.Version != _currentVersion || value2.Virgin) { lock (_dictionary) { long num = _currentVersion; if (!_dictionary.TryGetValue(key, out value2)) { value = default(TValue); return false; } if (value2.Version != num || value2.Virgin) { if (value2.Virgin) { num = ++_currentVersion; } _dictionary[key] = new MruCacheItem(value2.Value, num, virgin: false); } } } value = value2.Value; return true; } } internal sealed class MultiFileWatcher : IDisposable { private readonly Dictionary _watcherMap = new Dictionary(); public NotifyFilters NotifyFilters { get; set; } public event FileSystemEventHandler? FileChanged; public MultiFileWatcher() : this(NotifyFilters.Attributes | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.Security) { } public MultiFileWatcher(NotifyFilters notifyFilters) { NotifyFilters = notifyFilters; } public void Dispose() { this.FileChanged = null; StopWatching(); } public void StopWatching() { lock (_watcherMap) { foreach (KeyValuePair item in _watcherMap) { StopWatching(item.Value); } _watcherMap.Clear(); } } public void Watch(IEnumerable fileNames) { if (fileNames == null) { return; } foreach (string fileName in fileNames) { Watch(fileName); } } public void Watch(string fileName) { try { string path = Path.GetDirectoryName(fileName) ?? string.Empty; string fileName2 = Path.GetFileName(fileName); path = Path.GetFullPath(path); if (!Directory.Exists(path)) { InternalLogger.Warn("Cannot watch file-filter '{0}' when non-existing directory: {1}", fileName2, path); } else if (TryAddWatch(fileName, path, fileName2)) { InternalLogger.Debug("Start watching file-filter '{0}' in directory: {1}", fileName2, path); } } catch (Exception ex) { InternalLogger.Debug(ex, "Failed to start FileSystemWatcher with file-path: {0}", new ReadOnlySpan(new object[1] { fileName })); if (LogManager.ThrowExceptions) { throw; } } } private bool TryAddWatch(string fileName, string directory, string fileFilter) { lock (_watcherMap) { if (_watcherMap.ContainsKey(fileName)) { return false; } FileSystemWatcher fileSystemWatcher = null; try { fileSystemWatcher = new FileSystemWatcher { Path = directory, Filter = fileFilter, NotifyFilter = NotifyFilters }; fileSystemWatcher.Created += OnFileChanged; fileSystemWatcher.Changed += OnFileChanged; fileSystemWatcher.Deleted += OnFileChanged; fileSystemWatcher.Renamed += OnFileChanged; fileSystemWatcher.Error += OnWatcherError; fileSystemWatcher.EnableRaisingEvents = true; _watcherMap.Add(fileName, fileSystemWatcher); return true; } catch (Exception ex) { InternalLogger.Error(ex, "Failed to start FileSystemWatcher with file-filter '{0}' in directory: {1}", new ReadOnlySpan(new object[2] { fileFilter, directory })); if (ex is SecurityException || ex is UnauthorizedAccessException || ex is NotSupportedException || ex is NotImplementedException || ex is PlatformNotSupportedException) { return false; } if (LogManager.ThrowExceptions) { throw; } if (fileSystemWatcher != null) { StopWatching(fileSystemWatcher); } return false; } } } private void StopWatching(FileSystemWatcher watcher) { string text = string.Empty; string text2 = string.Empty; try { text = watcher.Filter; text2 = watcher.Path; InternalLogger.Debug("Stop watching file-filter '{0}' in directory: {1}", text, text2); watcher.EnableRaisingEvents = false; watcher.Created -= OnFileChanged; watcher.Changed -= OnFileChanged; watcher.Deleted -= OnFileChanged; watcher.Renamed -= OnFileChanged; watcher.Error -= OnWatcherError; watcher.Dispose(); } catch (Exception ex) { InternalLogger.Error(ex, "Failed to stop FileSystemWatcher with file-filter '{0}' in directory: {1}", new ReadOnlySpan(new object[2] { text, text2 })); if (LogManager.ThrowExceptions) { throw; } } } private static void OnWatcherError(object source, ErrorEventArgs e) { FileSystemWatcher obj = source as FileSystemWatcher; string text = obj?.Filter ?? string.Empty; string text2 = obj?.Path ?? string.Empty; InternalLogger.Warn(e.GetException(), "Error from FileSystemWatcher with file-filter '{0}' in directory: {1}", new ReadOnlySpan(new object[2] { text, text2 })); } private void OnFileChanged(object source, FileSystemEventArgs e) { FileSystemEventHandler fileChanged = this.FileChanged; if (fileChanged != null) { try { fileChanged(source, e); } catch (Exception ex) { InternalLogger.Error(ex, "Error handling event from FileSystemWatcher with file-filter: '{0}' in directory: {1}", new ReadOnlySpan(new object[2] { e.Name, e.FullPath })); } } } } internal static class ObjectGraphScanner { public static List FindReachableObjects(ConfigurationItemFactory configFactory, bool aggressiveSearch, params object[] rootObjects) where T : class { if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("FindReachableObject<{0}>:", typeof(T)); } List result = new List(); HashSet visitedObjects = new HashSet(SingleItemOptimizedHashSet.ReferenceEqualityComparer.Default); foreach (object obj in rootObjects) { if (PropertyHelper.IsConfigurationItemType(configFactory, obj.GetType())) { ScanProperties(configFactory, aggressiveSearch, obj, result, 0, visitedObjects); } } return result; } private static void ScanProperties(ConfigurationItemFactory configFactory, bool aggressiveSearch, object? targetObject, List result, int level, HashSet visitedObjects) where T : class { if (targetObject == null || visitedObjects.Contains(targetObject)) { return; } if (targetObject is T item) { result.Add(item); if (!aggressiveSearch) { return; } } Type type = targetObject.GetType(); if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("{0}Scanning {1} '{2}'", new string(' ', level), type.Name, targetObject); } foreach (KeyValuePair allConfigItemProperty in PropertyHelper.GetAllConfigItemProperties(configFactory, type)) { if (string.IsNullOrEmpty(allConfigItemProperty.Key)) { continue; } PropertyInfo value = allConfigItemProperty.Value; if (PropertyHelper.IsConfigurationItemType(configFactory, value.PropertyType)) { object obj = ScanPropertyValue(targetObject, type, value); if (obj != null) { visitedObjects.Add(targetObject); ScanPropertyForObject(configFactory, aggressiveSearch, obj, value, result, level, visitedObjects); } } } } private static object? ScanPropertyValue(object targetObject, Type type, PropertyInfo propInfo) { try { return propInfo.GetValue(targetObject, null); } catch (Exception ex) { InternalLogger.Warn(ex, "Failed scanning property: {0}.{1}", new ReadOnlySpan(new object[2] { type, propInfo.Name })); if (ex.MustBeRethrownImmediately()) { throw; } return null; } } private static void ScanPropertyForObject(ConfigurationItemFactory configFactory, bool aggressiveSearch, object propValue, PropertyInfo prop, List result, int level, HashSet visitedObjects) where T : class { if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("{0}Scanning Property {1} '{2}' {3}", new ReadOnlySpan(new object[4] { new string(' ', level + 1), prop.Name, propValue, prop.PropertyType })); } if (propValue is IEnumerable enumerable) { IList list = ConvertEnumerableToList(enumerable, visitedObjects); if (list.Count > 0) { ScanPropertiesList(configFactory, aggressiveSearch, list, result, level + 1, visitedObjects); } } else { ScanProperties(configFactory, aggressiveSearch, propValue, result, level + 1, visitedObjects); } } private static void ScanPropertiesList(ConfigurationItemFactory configFactory, bool aggressiveSearch, IList list, List result, int level, HashSet visitedObjects) where T : class { object obj = list[0]; if (obj == null || PropertyHelper.IsConfigurationItemType(configFactory, obj.GetType())) { ScanProperties(configFactory, aggressiveSearch, obj, result, level, visitedObjects); for (int i = 1; i < list.Count; i++) { object targetObject = list[i]; ScanProperties(configFactory, aggressiveSearch, targetObject, result, level, visitedObjects); } } } private static IList ConvertEnumerableToList(IEnumerable enumerable, HashSet visitedObjects) { if (enumerable is ICollection collection && collection.Count == 0) { return ArrayHelper.Empty(); } if (visitedObjects.Contains(enumerable)) { return ArrayHelper.Empty(); } visitedObjects.Add(enumerable); if (enumerable is IList list) { if (!list.IsReadOnly && !(list is Array)) { List list2 = new List(list.Count); lock (list.SyncRoot) { for (int i = 0; i < list.Count; i++) { object obj = list[i]; if (obj != null) { list2.Add(obj); } } return list2; } } return list; } return (from object o in enumerable where o != null select o).ToList(); } } internal struct ObjectPropertyPath { public string[]? PathNames { get; private set; } public string? Value { get { string[]? pathNames = PathNames; if (pathNames == null || pathNames.Length == 0) { return null; } return string.Join(".", PathNames); } set { PathNames = (StringHelpers.IsNullOrWhiteSpace(value) ? null : value?.SplitAndTrimTokens('.')); } } } internal sealed class ObjectReflectionCache : IObjectTypeTransformer { internal readonly struct ObjectPropertyList : IEnumerable, IEnumerable { public readonly struct PropertyValue { public readonly string Name; public readonly object? Value; private readonly TypeCode _typecode; public TypeCode TypeCode { get { if (Value != null) { return _typecode; } return TypeCode.Empty; } } public bool HasNameAndValue { get { if (Name != null) { return Value != null; } return false; } } public PropertyValue(string name, object value, TypeCode typeCode) { Name = name; Value = value; _typecode = typeCode; } public PropertyValue(object owner, PropertyInfo propertyInfo) { Name = propertyInfo.Name; _typecode = TypeCode.Object; try { Value = propertyInfo.GetValue(owner, null); } catch { Value = null; } } public PropertyValue(object owner, FastPropertyLookup fastProperty) { Name = fastProperty.Name; _typecode = fastProperty.TypeCode; try { Value = fastProperty.ValueLookup(owner, ArrayHelper.Empty()); } catch { Value = null; } } public override string ToString() { return $"{Name}={Value}"; } } public struct Enumerator : IEnumerator, IEnumerator, IDisposable { private readonly object _owner; private readonly PropertyInfo[]? _properties; private readonly FastPropertyLookup[]? _fastLookup; private readonly IEnumerator>? _enumerator; private int _index; public PropertyValue Current { get { try { if (_fastLookup != null) { return new PropertyValue(_owner, _fastLookup[_index]); } if (_properties != null) { return new PropertyValue(_owner, _properties[_index]); } if (_enumerator != null) { return new PropertyValue(_enumerator.Current.Key, _enumerator.Current.Value, TypeCode.Object); } return default(PropertyValue); } catch (Exception ex) { InternalLogger.Debug(ex, "Failed to get property value for object: {0}", new ReadOnlySpan(new object[1] { _owner })); return default(PropertyValue); } } } object IEnumerator.Current => Current; internal Enumerator(object owner, PropertyInfo[] properties, FastPropertyLookup[]? fastLookup) { _owner = owner; _properties = properties; _fastLookup = fastLookup; _index = -1; _enumerator = null; } internal Enumerator(IEnumerator> enumerator) { _owner = enumerator; _properties = null; _fastLookup = null; _index = 0; _enumerator = enumerator; } public void Dispose() { _enumerator?.Dispose(); } public bool MoveNext() { if (_properties != null) { int num = ++_index; FastPropertyLookup[]? fastLookup = _fastLookup; return num < ((fastLookup != null) ? fastLookup.Length : _properties.Length); } return _enumerator?.MoveNext() ?? false; } public void Reset() { if (_properties != null) { _index = -1; } else { _enumerator?.Reset(); } } } internal static readonly StringComparer NameComparer = StringComparer.Ordinal; private static readonly FastPropertyLookup[] CreateIDictionaryEnumerator = new FastPropertyLookup[1] { new FastPropertyLookup(string.Empty, TypeCode.Object, (object o, object?[] p) => ((IDictionary)o).GetEnumerator()) }; private readonly object _object; private readonly PropertyInfo[] _properties; private readonly FastPropertyLookup[]? _fastLookup; public bool IsSimpleValue { get { if (_properties.Length == 0) { if (_fastLookup != null) { return _fastLookup.Length == 0; } return true; } return false; } } public object ObjectValue => _object; internal ObjectPropertyList(object value, PropertyInfo[] properties, FastPropertyLookup[]? fastLookup) { _object = value; _properties = properties; _fastLookup = fastLookup; } public ObjectPropertyList(IDictionary value) { _object = value; _properties = ArrayHelper.Empty(); _fastLookup = CreateIDictionaryEnumerator; } public bool TryGetPropertyValue(string name, out PropertyValue propertyValue) { if (_properties.Length == 0) { if (_object is IDictionary dictionary) { if (dictionary.TryGetValue(name, out var value)) { propertyValue = new PropertyValue(name, value, TypeCode.Object); return true; } propertyValue = default(PropertyValue); return false; } return TryListLookupPropertyValue(name, out propertyValue); } if (_fastLookup != null) { int hashCode = NameComparer.GetHashCode(name); FastPropertyLookup[] fastLookup = _fastLookup; for (int i = 0; i < fastLookup.Length; i++) { FastPropertyLookup fastProperty = fastLookup[i]; if (fastProperty.NameHashCode == hashCode && NameComparer.Equals(fastProperty.Name, name)) { propertyValue = new PropertyValue(_object, fastProperty); return true; } } propertyValue = default(PropertyValue); return false; } return TrySlowLookupPropertyValue(name, out propertyValue); } private bool TrySlowLookupPropertyValue(string name, out PropertyValue propertyValue) { PropertyInfo[] properties = _properties; foreach (PropertyInfo propertyInfo in properties) { if (NameComparer.Equals(propertyInfo.Name, name)) { propertyValue = new PropertyValue(_object, propertyInfo); return true; } } propertyValue = default(PropertyValue); return false; } private bool TryListLookupPropertyValue(string name, out PropertyValue propertyValue) { using (Enumerator enumerator = GetEnumerator()) { while (enumerator.MoveNext()) { PropertyValue current = enumerator.Current; if (NameComparer.Equals(current.Name, name)) { propertyValue = current; return true; } } } propertyValue = default(PropertyValue); return false; } public override string ToString() { return _object?.ToString() ?? "null"; } public Enumerator GetEnumerator() { if (_properties.Length != 0 || _fastLookup == null || _fastLookup.Length == 0) { return new Enumerator(_object, _properties, _fastLookup); } object obj = _fastLookup[0].ValueLookup(_object, ArrayHelper.Empty()); if (obj != null) { return new Enumerator((IEnumerator>)obj); } return default(Enumerator); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal readonly struct FastPropertyLookup { public readonly string Name; public readonly ReflectionHelpers.LateBoundMethod ValueLookup; public readonly TypeCode TypeCode; public readonly int NameHashCode; public FastPropertyLookup(string name, TypeCode typeCode, ReflectionHelpers.LateBoundMethod valueLookup) { Name = name; ValueLookup = valueLookup; TypeCode = typeCode; NameHashCode = ObjectPropertyList.NameComparer.GetHashCode(name); } } private readonly struct ObjectPropertyInfos : IEquatable { public readonly PropertyInfo[] Properties; public readonly FastPropertyLookup[]? FastLookup; public static readonly ObjectPropertyInfos SimpleToString = new ObjectPropertyInfos(ArrayHelper.Empty(), ArrayHelper.Empty()); public bool HasFastLookup => FastLookup != null; public ObjectPropertyInfos(PropertyInfo[] properties, FastPropertyLookup[]? fastLookup) { Properties = properties; FastLookup = fastLookup; } public bool Equals(ObjectPropertyInfos other) { if (Properties == other.Properties) { return FastLookup?.Length == other.FastLookup?.Length; } return false; } } private interface IDictionaryEnumerator { IEnumerator> GetEnumerator(object value); } private sealed class DictionaryEnumerator : IDictionaryEnumerator { [CompilerGenerated] private sealed class d__6 : IEnumerator>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair <>2__current; public IEnumerator enumerator; public ReflectionHelpers.LateBoundMethod getKeyProperty; public ReflectionHelpers.LateBoundMethod getValueProperty; KeyValuePair IEnumerator>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__6(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -3; if (!enumerator.MoveNext()) { <>m__Finally1(); return false; } } else { <>1__state = -1; <>1__state = -3; } object current = enumerator.Current; object obj = getKeyProperty(current, ArrayHelper.Empty()); object value = getValueProperty(current, ArrayHelper.Empty()); <>2__current = new KeyValuePair(obj?.ToString() ?? string.Empty, value); <>1__state = 1; return true; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; (enumerator as IDisposable)?.Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__4 : IEnumerator>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair <>2__current; public IDictionary dictionary; private DictionaryEntryEnumerable.DictionaryEntryEnumerator <>7__wrap1; KeyValuePair IEnumerator>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__4(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = default(DictionaryEntryEnumerable.DictionaryEntryEnumerator); <>1__state = -2; } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = new DictionaryEntryEnumerable(dictionary).GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { DictionaryEntry current = <>7__wrap1.Current; <>2__current = new KeyValuePair(current.Key?.ToString() ?? string.Empty, current.Value); <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = default(DictionaryEntryEnumerable.DictionaryEntryEnumerator); return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; ((IDisposable)<>7__wrap1).Dispose(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private readonly Func>> _enumerateCollection; public DictionaryEnumerator(Func>> enumerateCollection) { _enumerateCollection = enumerateCollection; } IEnumerator> IDictionaryEnumerator.GetEnumerator(object value) { return _enumerateCollection(value); } public static IEnumerator> BuildDictionaryEnumerator(object collection) { if (collection is IDictionary dictionary) { if (dictionary.Count == 0) { return EmptyDictionaryEnumerator.Default; } return YieldEnumerator(dictionary); } return EmptyDictionaryEnumerator.Default; } [IteratorStateMachine(typeof(d__4))] private static IEnumerator> YieldEnumerator(IDictionary dictionary) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__4(0) { dictionary = dictionary }; } [UnconditionalSuppressMessage("Trimming - Allow reflection of message args", "IL2075")] [UnconditionalSuppressMessage("Trimming - Allow reflection of message args", "IL2070")] public static Func>>? BuildEnumerator(Type dictionaryType, Type dictionaryItemType) { Type dictionaryType2 = dictionaryType; MethodInfo method = dictionaryType2.GetMethod("GetEnumerator"); MethodInfo methodInfo = dictionaryItemType.GetProperty("Key")?.GetGetMethod(); MethodInfo methodInfo2 = dictionaryItemType.GetProperty("Value")?.GetGetMethod(); if (method != null && methodInfo != null && methodInfo2 != null) { ReflectionHelpers.LateBoundMethod enumeratorGetter = ReflectionHelpers.CreateLateBoundMethod(method); ReflectionHelpers.LateBoundMethod keyGetter = ReflectionHelpers.CreateLateBoundMethod(methodInfo); ReflectionHelpers.LateBoundMethod valueGetter = ReflectionHelpers.CreateLateBoundMethod(methodInfo2); return delegate(object collection) { if (collection is IEnumerable && dictionaryType2.IsInstanceOfType(collection)) { IEnumerator enumerator = (IEnumerator)enumeratorGetter(collection, ArrayHelper.Empty()); if (enumerator == null || !enumerator.MoveNext()) { (enumerator as IDisposable)?.Dispose(); return EmptyDictionaryEnumerator.Default; } return EnumerateItems(enumerator, keyGetter, valueGetter); } return EmptyDictionaryEnumerator.Default; }; } return null; } [IteratorStateMachine(typeof(d__6))] private static IEnumerator> EnumerateItems(IEnumerator enumerator, ReflectionHelpers.LateBoundMethod getKeyProperty, ReflectionHelpers.LateBoundMethod getValueProperty) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__6(0) { enumerator = enumerator, getKeyProperty = getKeyProperty, getValueProperty = getValueProperty }; } } private sealed class DictionaryEnumerator : IDictionaryEnumerator { [CompilerGenerated] private sealed class d__1 : IEnumerator>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair <>2__current; public IDictionary dictionary; private IEnumerator> <>7__wrap1; KeyValuePair IEnumerator>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__1(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = dictionary.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { KeyValuePair current = <>7__wrap1.Current; TKey key = current.Key; <>2__current = new KeyValuePair(((key != null) ? key.ToString() : null) ?? string.Empty, current.Value); <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__2 : IEnumerator>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair <>2__current; public IReadOnlyDictionary dictionary; private IEnumerator> <>7__wrap1; KeyValuePair IEnumerator>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__2(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = dictionary.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { KeyValuePair current = <>7__wrap1.Current; TKey key = current.Key; <>2__current = new KeyValuePair(((key != null) ? key.ToString() : null) ?? string.Empty, current.Value); <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } public IEnumerator> GetEnumerator(object value) { if (value is IDictionary dictionary) { if (dictionary.Count > 0) { return YieldEnumerator(dictionary); } } else if (value is IReadOnlyDictionary readOnlyDictionary && readOnlyDictionary.Count > 0) { return YieldEnumerator(readOnlyDictionary); } return EmptyDictionaryEnumerator.Default; } [IteratorStateMachine(typeof(DictionaryEnumerator<, >.d__1))] private static IEnumerator> YieldEnumerator(IDictionary dictionary) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__1(0) { dictionary = dictionary }; } [IteratorStateMachine(typeof(DictionaryEnumerator<, >.d__2))] private static IEnumerator> YieldEnumerator(IReadOnlyDictionary dictionary) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__2(0) { dictionary = dictionary }; } } private sealed class EmptyDictionaryEnumerator : IEnumerator>, IEnumerator, IDisposable { public static readonly EmptyDictionaryEnumerator Default = new EmptyDictionaryEnumerator(); KeyValuePair IEnumerator>.Current => default(KeyValuePair); object IEnumerator.Current => default(KeyValuePair); bool IEnumerator.MoveNext() { return false; } void IDisposable.Dispose() { } void IEnumerator.Reset() { } } private MruCache? _objectTypeCache; private readonly IServiceProvider _serviceProvider; private IObjectTypeTransformer? _objectTypeTransformation; private MruCache ObjectTypeCache => _objectTypeCache ?? Interlocked.CompareExchange(ref _objectTypeCache, new MruCache(10000), null) ?? _objectTypeCache; private IObjectTypeTransformer ObjectTypeTransformation => _objectTypeTransformation ?? (_objectTypeTransformation = _serviceProvider?.GetService() ?? this); public ObjectReflectionCache(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } object? IObjectTypeTransformer.TryTransformObject(object? obj) { return null; } public ObjectPropertyList LookupObjectProperties(object value) { if (TryLookupExpandoObject(value, out var objectPropertyList)) { return objectPropertyList; } if (ObjectTypeTransformation != this) { object obj = ObjectTypeTransformation.TryTransformObject(value); if (obj != null) { if (ConvertSimpleToString(obj)) { return new ObjectPropertyList(obj, ObjectPropertyInfos.SimpleToString.Properties, ObjectPropertyInfos.SimpleToString.FastLookup); } if (TryLookupExpandoObject(obj, out objectPropertyList)) { return objectPropertyList; } value = obj; } } Type type = value.GetType(); ObjectPropertyInfos value2 = (CheckForObjectProperties(value) ? BuildObjectPropertyInfos(value) : ObjectPropertyInfos.SimpleToString); ObjectTypeCache.TryAddValue(type, value2); return new ObjectPropertyList(value, value2.Properties, value2.FastLookup); } public bool TryGetObjectProperty(object? value, string[]? objectPath, out object? foundValue) { foundValue = null; if (objectPath == null) { return false; } for (int i = 0; i < objectPath.Length; i++) { if (value == null) { return false; } if (LookupObjectProperties(value).TryGetPropertyValue(objectPath[i], out var propertyValue)) { value = propertyValue.Value; continue; } foundValue = null; return false; } foundValue = value; return true; } public bool TryLookupExpandoObject(object value, out ObjectPropertyList objectPropertyList) { if (value is IDictionary value2) { objectPropertyList = new ObjectPropertyList(value2); return true; } Type type = value.GetType(); if (ObjectTypeCache.TryGetValue(type, out var value3)) { if (!value3.HasFastLookup) { FastPropertyLookup[] fastLookup = BuildFastLookup(value3.Properties, includeType: false); value3 = new ObjectPropertyInfos(value3.Properties, fastLookup); ObjectTypeCache.TryAddValue(type, value3); } objectPropertyList = new ObjectPropertyList(value, value3.Properties, value3.FastLookup); return true; } IDictionaryEnumerator dictionaryEnumerator = TryGetDictionaryEnumerator(value); if (dictionaryEnumerator != null) { value3 = new ObjectPropertyInfos(ArrayHelper.Empty(), new FastPropertyLookup[1] { new FastPropertyLookup(string.Empty, TypeCode.Object, (object o, object?[] p) => dictionaryEnumerator.GetEnumerator(o)) }); ObjectTypeCache.TryAddValue(type, value3); objectPropertyList = new ObjectPropertyList(value, value3.Properties, value3.FastLookup); return true; } objectPropertyList = default(ObjectPropertyList); return false; } [UnconditionalSuppressMessage("Trimming - Allow reflection of message args", "IL2072")] private static ObjectPropertyInfos BuildObjectPropertyInfos(object value) { PropertyInfo[] publicProperties = GetPublicProperties(value.GetType()); if (value is Exception) { FastPropertyLookup[] fastLookup = BuildFastLookup(publicProperties, includeType: true); return new ObjectPropertyInfos(publicProperties, fastLookup); } if (publicProperties.Length == 0) { return ObjectPropertyInfos.SimpleToString; } return new ObjectPropertyInfos(publicProperties, null); } private static bool CheckForObjectProperties(object objectValue) { if (ConvertSimpleToString(objectValue)) { return false; } if (objectValue is Uri) { return false; } if (objectValue is Delegate) { return false; } if (objectValue is MemberInfo) { return false; } if (objectValue is Assembly) { return false; } if (objectValue is Module) { return false; } if (objectValue is Stream) { return false; } return true; } private static bool ConvertSimpleToString(object objectValue) { if (objectValue is IFormattable) { return true; } if (objectValue is IConvertible convertible) { return convertible.GetTypeCode() != TypeCode.Object; } return false; } private static PropertyInfo[] GetPublicProperties([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type) { PropertyInfo[] array = null; try { array = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to get object properties for type: {0}", new ReadOnlySpan(new object[1] { type })); } if (array != null) { PropertyInfo[] array2 = array; for (int i = 0; i < array2.Length; i++) { if (!array2[i].IsValidPublicProperty()) { array = array.Where((PropertyInfo p) => p.IsValidPublicProperty()).ToArray(); break; } } } return array ?? ArrayHelper.Empty(); } private static FastPropertyLookup[] BuildFastLookup(PropertyInfo[] properties, bool includeType) { int num = (includeType ? 1 : 0); FastPropertyLookup[] array = new FastPropertyLookup[properties.Length + num]; if (includeType) { array[0] = new FastPropertyLookup("Type", TypeCode.String, (object o, object?[] p) => o.GetType().ToString()); } foreach (PropertyInfo propertyInfo in properties) { MethodInfo getMethod = propertyInfo.GetGetMethod(); Type type = getMethod?.ReturnType; if ((object)getMethod == null || (object)type == null) { array[num++] = new FastPropertyLookup(propertyInfo.Name, TypeCode.String, (object o, object?[] p) => null); } else { ReflectionHelpers.LateBoundMethod valueLookup = ReflectionHelpers.CreateLateBoundMethod(getMethod); TypeCode typeCode = Type.GetTypeCode(type); array[num++] = new FastPropertyLookup(propertyInfo.Name, typeCode, valueLookup); } } return array; } private static IDictionaryEnumerator? TryGetDictionaryEnumerator(object value) { if (!(value is IEnumerable) || value is string) { return null; } if (value is IDictionary) { return new DictionaryEnumerator(); } if (value is IDictionary) { return new DictionaryEnumerator(); } if (value is IReadOnlyDictionary) { return new DictionaryEnumerator(); } if (value is IReadOnlyDictionary) { return new DictionaryEnumerator(); } if (value is IDictionary && value.GetType().IsGenericType) { if (value.GetType().GetGenericArguments()[0] == typeof(string)) { return new DictionaryEnumerator(DictionaryEnumerator.BuildDictionaryEnumerator); } return null; } return TryBuildDictionaryEnumerator(value); } [UnconditionalSuppressMessage("Trimming - Allow reflection of message args", "IL2075")] private static IDictionaryEnumerator? TryBuildDictionaryEnumerator(object value) { Type[] interfaces = value.GetType().GetInterfaces(); foreach (Type type in interfaces) { if (!type.IsGenericType || (!(type.GetGenericTypeDefinition() == typeof(IDictionary<, >)) && !(type.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<, >))) || !(type.GetGenericArguments()[0] == typeof(string))) { continue; } Type[] interfaces2 = value.GetType().GetInterfaces(); foreach (Type type2 in interfaces2) { if (type2.IsGenericType && type2.GetGenericTypeDefinition() == typeof(IEnumerable<>) && type2.GetGenericArguments()[0].IsGenericType && type2.GetGenericArguments()[0].GetGenericTypeDefinition() == typeof(KeyValuePair<, >) && type2.GetGenericArguments()[0].GetGenericArguments()[0] == typeof(string)) { Func>> func = DictionaryEnumerator.BuildEnumerator(type2, type2.GetGenericArguments()[0]); if (func != null) { return new DictionaryEnumerator(func); } } } } return null; } } internal static class PathHelpers { private static readonly char[] DirectorySeparatorChars = new char[2] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; internal static string CombinePaths(string path, string dir, string file) { if (!string.IsNullOrEmpty(dir)) { path = Path.Combine(path, dir); } if (!string.IsNullOrEmpty(file)) { path = Path.Combine(path, file); } return path; } public static string TrimDirectorySeparators(string path) { string text = path?.TrimEnd(DirectorySeparatorChars) ?? string.Empty; if (text.EndsWith(":", StringComparison.Ordinal)) { return path ?? string.Empty; } return text; } public static bool IsTempDir(string directory, string tempDir) { tempDir = TrimDirectorySeparators(tempDir); if (string.IsNullOrEmpty(directory) || string.IsNullOrEmpty(tempDir)) { return false; } string fullPath = Path.GetFullPath(directory); if (string.IsNullOrEmpty(fullPath)) { return false; } if (fullPath.StartsWith(tempDir, StringComparison.OrdinalIgnoreCase)) { return true; } if (tempDir.StartsWith("/tmp", StringComparison.Ordinal) && directory.StartsWith("/var/tmp/", StringComparison.Ordinal)) { return true; } return false; } } internal static class PlatformDetector { private static RuntimeOS? _currentOS; public static RuntimeOS CurrentOS { get { RuntimeOS? currentOS = _currentOS; if (!currentOS.HasValue) { RuntimeOS? runtimeOS = (_currentOS = GetCurrentRuntimeOS()); return runtimeOS.Value; } return currentOS.GetValueOrDefault(); } } public static bool IsWin32 { get { if (CurrentOS != RuntimeOS.WindowsNT) { return CurrentOS == RuntimeOS.Windows9x; } return true; } } public static bool IsUnix { get { if (CurrentOS != RuntimeOS.Linux) { return CurrentOS == RuntimeOS.MacOSX; } return true; } } private static RuntimeOS GetCurrentRuntimeOS() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return RuntimeOS.Linux; } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return RuntimeOS.MacOSX; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return RuntimeOS.WindowsNT; } return RuntimeOS.Unknown; } } [DebuggerDisplay("Count = {Count}")] internal sealed class PropertiesDictionary : IDictionary, ICollection>, IEnumerable>, IEnumerable { private readonly struct PropertyValue { public readonly object? Value; public readonly bool IsMessageProperty; public PropertyValue(object? value, bool isMessageProperty) { Value = value; IsMessageProperty = isMessageProperty; } } public struct PropertyDictionaryEnumerator : IEnumerator>, IEnumerator, IDisposable { private readonly PropertiesDictionary _dictionary; private Dictionary.Enumerator _eventEnumerator; private int _messagePropertiesIndex; public KeyValuePair Current { get { if (_messagePropertiesIndex >= 0) { MessageTemplateParameter messageTemplateParameter = _dictionary.MessageProperties[_messagePropertiesIndex]; return new KeyValuePair(messageTemplateParameter.Name, messageTemplateParameter.Value); } return new KeyValuePair(_eventEnumerator.Current.Key, _eventEnumerator.Current.Value.Value); } } public MessageTemplateParameter CurrentParameter { get { if (_messagePropertiesIndex >= 0) { return _dictionary.MessageProperties[_messagePropertiesIndex]; } return new MessageTemplateParameter(XmlHelper.XmlConvertToString(_eventEnumerator.Current.Key ?? string.Empty) ?? string.Empty, _eventEnumerator.Current.Value.Value, null, CaptureType.Unknown); } } public KeyValuePair CurrentProperty { get { if (_messagePropertiesIndex >= 0) { MessageTemplateParameter messageTemplateParameter = _dictionary.MessageProperties[_messagePropertiesIndex]; return new KeyValuePair(messageTemplateParameter.Name, messageTemplateParameter.Value); } return new KeyValuePair(XmlHelper.XmlConvertToString(_eventEnumerator.Current.Key ?? string.Empty) ?? string.Empty, _eventEnumerator.Current.Value.Value); } } object IEnumerator.Current => Current; public PropertyDictionaryEnumerator(PropertiesDictionary dictionary) { _dictionary = dictionary; IList? messageProperties = dictionary._messageProperties; _messagePropertiesIndex = ((messageProperties != null && messageProperties.Count > 0 && dictionary._eventProperties == null) ? (-1) : int.MinValue); _eventEnumerator = dictionary._eventProperties?.GetEnumerator() ?? default(Dictionary.Enumerator); } public bool MoveNext() { if (_messagePropertiesIndex >= -1) { if (_messagePropertiesIndex + 1 < _dictionary._messageProperties?.Count) { _messagePropertiesIndex++; return true; } return false; } if (_dictionary._eventProperties == null) { return false; } return _eventEnumerator.MoveNext(); } public void Dispose() { } public void Reset() { IList? messageProperties = _dictionary._messageProperties; _messagePropertiesIndex = ((messageProperties != null && messageProperties.Count > 0 && _dictionary._eventProperties == null) ? (-1) : int.MinValue); _eventEnumerator = _dictionary._eventProperties?.GetEnumerator() ?? default(Dictionary.Enumerator); } } [DebuggerDisplay("Count = {Count}")] private sealed class ValueCollection : ICollection, IEnumerable, IEnumerable { private sealed class ValueCollectionEnumerator : IEnumerator, IEnumerator, IDisposable { private PropertyDictionaryEnumerator _enumerator; public object? Current => _enumerator.Current.Value; public ValueCollectionEnumerator(PropertiesDictionary dictionary) { _enumerator = dictionary.GetPropertyEnumerator(); } public void Dispose() { _enumerator.Dispose(); } public bool MoveNext() { return _enumerator.MoveNext(); } public void Reset() { _enumerator.Reset(); } } private readonly PropertiesDictionary _dictionary; public int Count => _dictionary.Count; public bool IsReadOnly => true; public ValueCollection(PropertiesDictionary dictionary) { _dictionary = dictionary; } public void Add(object? item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Remove(object? item) { throw new NotSupportedException(); } public bool Contains(object? item) { if (!_dictionary.IsEmpty) { Dictionary eventProperties = _dictionary.GetEventProperties(); if (eventProperties.ContainsValue(new PropertyValue(item, isMessageProperty: false))) { return true; } if (eventProperties.ContainsValue(new PropertyValue(item, isMessageProperty: true))) { return true; } } return false; } public void CopyTo(object?[] array, int arrayIndex) { Guard.ThrowIfNull(array, "array"); if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex"); } if (_dictionary.IsEmpty) { return; } foreach (KeyValuePair item in _dictionary) { array[arrayIndex++] = item.Value; } } public IEnumerator GetEnumerator() { return new ValueCollectionEnumerator(_dictionary); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [DebuggerDisplay("Count = {Count}")] private sealed class KeyCollection : ICollection, IEnumerable, IEnumerable { private sealed class KeyCollectionEnumerator : IEnumerator, IEnumerator, IDisposable { private PropertyDictionaryEnumerator _enumerator; public object Current => _enumerator.Current.Key; public KeyCollectionEnumerator(PropertiesDictionary dictionary) { _enumerator = dictionary.GetPropertyEnumerator(); } public void Dispose() { _enumerator.Dispose(); } public bool MoveNext() { return _enumerator.MoveNext(); } public void Reset() { _enumerator.Reset(); } } private readonly PropertiesDictionary _dictionary; public int Count => _dictionary.Count; public bool IsReadOnly => true; public KeyCollection(PropertiesDictionary dictionary) { _dictionary = dictionary; } public void Add(object item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Remove(object item) { throw new NotSupportedException(); } public bool Contains(object item) { return _dictionary.ContainsKey(item); } public void CopyTo(object[] array, int arrayIndex) { Guard.ThrowIfNull(array, "array"); if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex"); } if (_dictionary.IsEmpty) { return; } foreach (KeyValuePair item in _dictionary) { array[arrayIndex++] = item.Key; } } public IEnumerator GetEnumerator() { return new KeyCollectionEnumerator(_dictionary); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal sealed class IgnoreCasePropertyKey { private readonly string _propertyName; public IgnoreCasePropertyKey(string propertyName) { _propertyName = propertyName; } public bool Equals(string propertyName) { return Equals(_propertyName, propertyName); } public override bool Equals(object? obj) { if (obj is string y) { return Equals(_propertyName, y); } if (obj is IgnoreCasePropertyKey ignoreCasePropertyKey) { return Equals(_propertyName, ignoreCasePropertyKey._propertyName); } return false; } public override int GetHashCode() { return GetHashCode(_propertyName); } public override string ToString() { return _propertyName; } internal static int GetHashCode(string propertyName) { return StringComparer.OrdinalIgnoreCase.GetHashCode(propertyName); } internal static bool Equals(string x, string y) { return string.Equals(x, y, StringComparison.OrdinalIgnoreCase); } } private sealed class PropertyKeyComparer : IEqualityComparer { public static readonly PropertyKeyComparer Default = new PropertyKeyComparer(); public new bool Equals(object x, object y) { if (y is IgnoreCasePropertyKey ignoreCasePropertyKey && x is string propertyName) { return ignoreCasePropertyKey.Equals(propertyName); } if (x is IgnoreCasePropertyKey ignoreCasePropertyKey2 && y is string propertyName2) { return ignoreCasePropertyKey2.Equals(propertyName2); } return EqualityComparer.Default.Equals(x, y); } public int GetHashCode(object obj) { if (obj is string propertyName) { return IgnoreCasePropertyKey.GetHashCode(propertyName); } return EqualityComparer.Default.GetHashCode(obj); } } private Dictionary? _eventProperties; private IList? _messageProperties; private static readonly KeyCollection EmptyKeyCollection = new KeyCollection(new PropertiesDictionary()); private static readonly ValueCollection EmptyValueCollection = new ValueCollection(new PropertiesDictionary()); private bool IsEmpty { get { if (_eventProperties == null || _eventProperties.Count == 0) { if (_messageProperties != null) { return _messageProperties.Count == 0; } return true; } return false; } } public IList MessageProperties => _messageProperties ?? ArrayHelper.Empty(); public object? this[object key] { get { if (TryGetValue(key, out object value)) { return value; } throw new KeyNotFoundException(); } set { GetEventProperties(prepareForInsert: true)[key] = new PropertyValue(value, isMessageProperty: false); } } public ICollection Keys { get { if (!IsEmpty) { return new KeyCollection(this); } return EmptyKeyCollection; } } public ICollection Values { get { if (!IsEmpty) { return new ValueCollection(this); } return EmptyValueCollection; } } public int Count => _eventProperties?.Count ?? _messageProperties?.Count ?? 0; public bool IsReadOnly => false; public PropertiesDictionary(IList? messageParameters = null) { if (messageParameters != null && messageParameters.Count > 0) { _messageProperties = SetMessageProperties(messageParameters, null); } } public PropertiesDictionary(int initialCapacity) { if (initialCapacity > 3) { _eventProperties = new Dictionary(initialCapacity, PropertyKeyComparer.Default); } } private Dictionary GetEventProperties(bool prepareForInsert = false) { if (_eventProperties == null) { Interlocked.CompareExchange(ref _eventProperties, InitializeEventPropertiesDictionary(_messageProperties, prepareForInsert), null); } return _eventProperties; } public void ResetMessageProperties(IList? newMessageProperties = null) { _messageProperties = SetMessageProperties(newMessageProperties, _messageProperties); } private IList? SetMessageProperties(IList? newMessageProperties, IList? oldMessageProperties) { if (_eventProperties == null && VerifyUniqueMessageTemplateParametersFast(newMessageProperties)) { return newMessageProperties; } Dictionary dictionary = _eventProperties; if (dictionary == null) { dictionary = (_eventProperties = new Dictionary(newMessageProperties?.Count ?? 0, PropertyKeyComparer.Default)); } if (oldMessageProperties != null && dictionary.Count > 0) { RemoveOldMessageProperties(oldMessageProperties, dictionary); } if (newMessageProperties != null) { InsertMessagePropertiesIntoEmptyDictionary(newMessageProperties, dictionary); } return newMessageProperties; } private static void RemoveOldMessageProperties(IList oldMessageProperties, Dictionary eventProperties) { for (int i = 0; i < oldMessageProperties.Count; i++) { if (eventProperties.TryGetValue(oldMessageProperties[i].Name, out var value) && value.IsMessageProperty) { eventProperties.Remove(oldMessageProperties[i].Name); } } } private static Dictionary InitializeEventPropertiesDictionary(IList? messageProperties, bool prepareForInsert) { if (messageProperties != null && messageProperties.Count > 0) { Dictionary dictionary = new Dictionary(prepareForInsert ? (messageProperties.Count + 2) : messageProperties.Count, PropertyKeyComparer.Default); InsertMessagePropertiesIntoEmptyDictionary(messageProperties, dictionary); return dictionary; } return new Dictionary(PropertyKeyComparer.Default); } public void Add(object key, object? value) { GetEventProperties(prepareForInsert: true).Add(key, new PropertyValue(value, isMessageProperty: false)); } public void Add(KeyValuePair item) { Add(item.Key, item.Value); } public void Clear() { if (_eventProperties != null) { _eventProperties = null; } if (_messageProperties != null) { _messageProperties = ArrayHelper.Empty(); } } public bool Contains(KeyValuePair item) { if (!IsEmpty && (_eventProperties != null || ContainsKey(item.Key))) { IDictionary eventProperties = GetEventProperties(); if (eventProperties.Contains(new KeyValuePair(item.Key, new PropertyValue(item.Value, isMessageProperty: false)))) { return true; } if (eventProperties.Contains(new KeyValuePair(item.Key, new PropertyValue(item.Value, isMessageProperty: true)))) { return true; } } return false; } public bool ContainsKey(object key) { object value; return TryGetValue(key, out value); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { Guard.ThrowIfNull(array, "array"); if (arrayIndex < 0) { throw new ArgumentOutOfRangeException("arrayIndex"); } if (IsEmpty) { return; } using IEnumerator> enumerator = GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair current = enumerator.Current; array[arrayIndex++] = current; } } internal PropertyDictionaryEnumerator GetPropertyEnumerator() { return new PropertyDictionaryEnumerator(this); } public IEnumerator> GetEnumerator() { if (!IsEmpty) { return new PropertyDictionaryEnumerator(this); } return Enumerable.Empty>().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool Remove(object key) { if (!IsEmpty && (_eventProperties != null || ContainsKey(key))) { return GetEventProperties().Remove(key); } return false; } public bool Remove(KeyValuePair item) { if (!IsEmpty && (_eventProperties != null || ContainsKey(item.Key))) { ICollection> eventProperties = GetEventProperties(); if (eventProperties.Remove(new KeyValuePair(item.Key, new PropertyValue(item.Value, isMessageProperty: false)))) { return true; } if (eventProperties.Remove(new KeyValuePair(item.Key, new PropertyValue(item.Value, isMessageProperty: true)))) { return true; } } return false; } public bool TryGetValue(object key, out object? value) { if (_eventProperties == null) { return TryLookupMessagePropertyValue(key, out value); } if (_eventProperties.TryGetValue(key, out var value2)) { value = value2.Value; return true; } value = null; return false; } private bool TryLookupMessagePropertyValue(object key, out object? propertyValue) { if (_messageProperties == null || _messageProperties.Count == 0) { propertyValue = null; return false; } if (_messageProperties.Count > 10) { if (GetEventProperties().TryGetValue(key, out var value)) { propertyValue = value.Value; return true; } } else if (key is string text) { for (int i = 0; i < _messageProperties.Count; i++) { if (text.Equals(_messageProperties[i].Name, StringComparison.Ordinal)) { propertyValue = _messageProperties[i].Value; return true; } } } else if (key is IgnoreCasePropertyKey ignoreCasePropertyKey) { for (int j = 0; j < _messageProperties.Count; j++) { if (ignoreCasePropertyKey.Equals(_messageProperties[j].Name)) { propertyValue = _messageProperties[j].Value; return true; } } } propertyValue = null; return false; } private static bool VerifyUniqueMessageTemplateParametersFast(IList? parameterList) { if (parameterList == null) { return true; } int count = parameterList.Count; if (count <= 1) { return true; } if (count > 10) { return false; } for (int i = 0; i < count - 1; i++) { string name = parameterList[i].Name; for (int j = i + 1; j < count; j++) { if (name == parameterList[j].Name) { return false; } } } return true; } private static void InsertMessagePropertiesIntoEmptyDictionary(IList messageProperties, Dictionary eventProperties) { for (int i = 0; i < messageProperties.Count; i++) { try { eventProperties.Add(messageProperties[i].Name, new PropertyValue(messageProperties[i].Value, isMessageProperty: true)); } catch (ArgumentException) { MessageTemplateParameter messageTemplateParameter = messageProperties[i]; if (eventProperties.TryGetValue(messageTemplateParameter.Name, out var value) && value.IsMessageProperty) { string text = GenerateUniquePropertyName(messageTemplateParameter.Name, eventProperties, (string newkey, IDictionary props) => props.ContainsKey(newkey)); eventProperties.Add(text, new PropertyValue(messageProperties[i].Value, isMessageProperty: true)); messageProperties[i] = new MessageTemplateParameter(text, messageTemplateParameter.Value, messageTemplateParameter.Format, messageTemplateParameter.CaptureType); } } } } internal static string GenerateUniquePropertyName(string originalName, IDictionary properties, Func, bool> containsKey) { originalName = originalName ?? string.Empty; int num = 1; string text = originalName + "_1"; while (containsKey(text, properties)) { string text2 = originalName; int num2 = ++num; text = text2 + "_" + num2; } return text; } } internal static class PropertyHelper { private static readonly Dictionary?> _parameterInfoCache = new Dictionary>(); private static readonly Dictionary> _propertyConversionMapper = BuildPropertyConversionMapper(); private static readonly ArrayParameterAttribute _arrayParameterAttribute = new ArrayParameterAttribute(typeof(string), string.Empty); private static readonly DefaultParameterAttribute _defaultParameterAttribute = new DefaultParameterAttribute(); private static readonly NLogConfigurationIgnorePropertyAttribute _ignorePropertyAttribute = new NLogConfigurationIgnorePropertyAttribute(); private static readonly NLogConfigurationItemAttribute _configPropertyAttribute = new NLogConfigurationItemAttribute(); private static readonly FlagsAttribute _flagsAttribute = new FlagsAttribute(); private static Dictionary> BuildPropertyConversionMapper() { return new Dictionary> { { typeof(Layout), TryParseLayoutValue }, { typeof(SimpleLayout), TryParseLayoutValue }, { typeof(ConditionExpression), TryParseConditionValue }, { typeof(Encoding), (string stringvalue, ConfigurationItemFactory factory) => PropertyTypeConverter.ConvertToEncoding(stringvalue) }, { typeof(string), (string stringvalue, ConfigurationItemFactory factory) => stringvalue }, { typeof(int), (string stringvalue, ConfigurationItemFactory factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Int32, CultureInfo.InvariantCulture) }, { typeof(bool), (string stringvalue, ConfigurationItemFactory factory) => Convert.ChangeType(stringvalue.Trim(), TypeCode.Boolean, CultureInfo.InvariantCulture) }, { typeof(CultureInfo), (string stringvalue, ConfigurationItemFactory factory) => PropertyTypeConverter.ConvertToCultureInfo(stringvalue) }, { typeof(Type), (string stringvalue, ConfigurationItemFactory factory) => PropertyTypeConverter.ConvertToType(stringvalue.Trim(), throwOnError: true) }, { typeof(LineEndingMode), (string stringvalue, ConfigurationItemFactory factory) => LineEndingMode.FromString(stringvalue.Trim()) }, { typeof(Uri), (string stringvalue, ConfigurationItemFactory factory) => new Uri(stringvalue.Trim()) } }; } internal static void SetPropertyFromString(object targetObject, PropertyInfo propInfo, string stringValue, ConfigurationItemFactory configurationItemFactory) { object newValue = null; try { Type type = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType; if (((object)type == propInfo.PropertyType || !StringHelpers.IsNullOrWhiteSpace(stringValue)) && !TryNLogSpecificConversion(type, stringValue, configurationItemFactory, out newValue)) { if (propInfo.IsDefined(_arrayParameterAttribute.GetType(), inherit: false)) { throw new NotSupportedException("'" + targetObject?.GetType()?.Name + "' cannot assign property '" + propInfo.Name + "', because property of type array and not scalar value: '" + stringValue + "'."); } if (!TryGetEnumValue(type, stringValue, out newValue) && !TryImplicitConversion(type, stringValue, out newValue) && !TryFlatListConversion(targetObject, propInfo, stringValue, configurationItemFactory, out newValue) && !TryTypeConverterConversion(type, stringValue, out newValue)) { newValue = Convert.ChangeType(stringValue, type, CultureInfo.InvariantCulture); } } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } throw new NLogConfigurationException("'" + targetObject?.GetType()?.Name + "' cannot assign property '" + propInfo.Name + "'='" + stringValue + "'. Error: " + ex.Message, ex); } SetPropertyValueForObject(targetObject, newValue, propInfo); } internal static void SetPropertyValueForObject(object targetObject, object? value, PropertyInfo propInfo) { try { propInfo.SetValue(targetObject, value, null); } catch (TargetInvocationException ex) { throw new NLogConfigurationException("'" + targetObject?.GetType()?.Name + "' cannot assign property '" + propInfo.Name + "'", ex.InnerException ?? ex); } catch (Exception ex2) { if (ex2.MustBeRethrownImmediately()) { throw; } throw new NLogConfigurationException("'" + targetObject?.GetType()?.Name + "' cannot assign property '" + propInfo.Name + "'. Error=" + ex2.Message, ex2); } } internal static bool TryGetPropertyInfo(ConfigurationItemFactory configFactory, object obj, string propertyName, out PropertyInfo? result) { Dictionary dictionary = TryLookupConfigItemProperties(configFactory, obj.GetType()); if (dictionary == null) { if (!string.IsNullOrEmpty(propertyName)) { return TryGetPropertyInfo(obj, propertyName, out result); } result = null; return false; } return dictionary.TryGetValue(propertyName, out result); } [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2075")] [Obsolete("Instead use RegisterType, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private static bool TryGetPropertyInfo(object obj, string propertyName, out PropertyInfo? result) { InternalLogger.Debug("Object reflection needed to configure instance of type: {0} (Lookup property={1})", obj.GetType(), propertyName); PropertyInfo property = obj.GetType().GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); if ((object)property == null) { result = null; return false; } result = property; return true; } internal static Type? GetArrayItemType(PropertyInfo propInfo) { return propInfo.GetFirstCustomAttribute()?.ItemType; } internal static bool IsConfigurationItemType(ConfigurationItemFactory configFactory, Type? type) { if ((object)type == null || IsSimplePropertyType(type)) { return false; } if (typeof(ISupportsInitialize).IsAssignableFrom(type)) { return true; } if (typeof(IEnumerable).IsAssignableFrom(type)) { return true; } return TryLookupConfigItemProperties(configFactory, type) != null; } internal static Dictionary GetAllConfigItemProperties(ConfigurationItemFactory configFactory, Type type) { return TryLookupConfigItemProperties(configFactory, type) ?? new Dictionary(); } private static Dictionary? TryLookupConfigItemProperties(ConfigurationItemFactory configFactory, Type type) { lock (_parameterInfoCache) { if (!_parameterInfoCache.TryGetValue(type, out Dictionary value)) { if (TryCreatePropertyInfoDictionary(configFactory, type, out value)) { _parameterInfoCache[type] = value; } else { _parameterInfoCache[type] = null; } } return value; } } internal static bool IsSimplePropertyType(Type type) { if (Type.GetTypeCode(type) != TypeCode.Object) { return true; } if (type == typeof(CultureInfo)) { return true; } if (type == typeof(Type)) { return true; } if (type == typeof(Encoding)) { return true; } if (type == typeof(LogLevel)) { return true; } return false; } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2070")] private static bool TryImplicitConversion(Type resultType, string value, out object? result) { try { if (IsSimplePropertyType(resultType)) { result = null; return false; } MethodInfo method = resultType.GetMethod("op_Implicit", BindingFlags.Static | BindingFlags.Public, null, new Type[1] { value.GetType() }, null); if ((object)method == null || !resultType.IsAssignableFrom(method.ReturnType)) { result = null; return false; } result = method.Invoke(null, new object[1] { value }); return true; } catch (Exception ex) { InternalLogger.Warn(ex, "Implicit Conversion Failed of {0} to {1}", new ReadOnlySpan(new object[2] { value, resultType })); } result = null; return false; } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2067")] private static bool TryNLogSpecificConversion(Type propertyType, string value, ConfigurationItemFactory configurationItemFactory, out object? newValue) { if (_propertyConversionMapper.TryGetValue(propertyType, out Func value2)) { newValue = value2(value, configurationItemFactory); return true; } if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Layout<>)) { SimpleLayout simpleLayout = (string.IsNullOrEmpty(value) ? SimpleLayout.Default : new SimpleLayout(value, configurationItemFactory)); newValue = Activator.CreateInstance(propertyType, BindingFlags.Instance | BindingFlags.Public, null, new object[1] { simpleLayout }, null); return true; } newValue = null; return false; } private static bool TryGetEnumValue(Type resultType, string value, out object? result) { if (!resultType.IsEnum) { result = null; return false; } if (!StringHelpers.IsNullOrWhiteSpace(value)) { try { result = (Enum)Enum.Parse(resultType, value, ignoreCase: true); return true; } catch (ArgumentException innerException) { throw new ArgumentException("Failed parsing Enum " + resultType.Name + " from value: " + value, innerException); } } result = null; return false; } private static object TryParseLayoutValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { if (!string.IsNullOrEmpty(stringValue)) { return new SimpleLayout(stringValue, configurationItemFactory); } return Layout.Empty; } private static object TryParseConditionValue(string stringValue, ConfigurationItemFactory configurationItemFactory) { try { return ConditionParser.ParseExpression(stringValue, configurationItemFactory); } catch (ConditionParseException ex) { throw new NLogConfigurationException("Cannot parse ConditionExpression '" + stringValue + "'. Error: " + ex.Message, ex); } } private static bool TryFlatListConversion(object obj, PropertyInfo propInfo, string valueRaw, ConfigurationItemFactory configurationItemFactory, out object? newValue) { Type propertyType = propInfo.PropertyType; if (!propertyType.IsGenericType || !typeof(IEnumerable).IsAssignableFrom(propertyType)) { newValue = null; return false; } try { if (TryCreateCollectionObject(obj, propInfo, out object collectionObject, out MethodInfo collectionAddMethod, out Type collectionItemType) && collectionAddMethod != null && collectionItemType != null) { foreach (string item in valueRaw.SplitQuoted(',', '\'', '\\')) { if (!TryNLogSpecificConversion(collectionItemType, item, configurationItemFactory, out newValue) && !TryGetEnumValue(collectionItemType, item, out newValue) && !TryImplicitConversion(collectionItemType, item, out newValue) && !TryTypeConverterConversion(collectionItemType, item, out newValue)) { newValue = Convert.ChangeType(item, collectionItemType, CultureInfo.InvariantCulture); } collectionAddMethod.Invoke(collectionObject, new object[1] { newValue }); } newValue = collectionObject; return true; } newValue = null; return false; } catch (Exception innerException) { throw new NLogConfigurationException($"Failed to parse collection for property '{propInfo.Name}' on {obj.GetType()} with value '{valueRaw}'", innerException); } } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2072")] [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2075")] private static bool TryCreateCollectionObject(object obj, PropertyInfo propInfo, out object? collectionObject, out MethodInfo? collectionAddMethod, out Type? collectionItemType) { collectionObject = null; collectionAddMethod = null; collectionItemType = null; Type propertyType = propInfo.PropertyType; if (TryCreateListCollection(propertyType, out collectionObject, out collectionAddMethod, out collectionItemType)) { return true; } if (TryCreateListCollection(propertyType, out collectionObject, out collectionAddMethod, out collectionItemType)) { return true; } Type genericTypeDefinition = propertyType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(List<>)) { collectionObject = Activator.CreateInstance(propertyType); collectionAddMethod = propertyType.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); collectionItemType = propertyType.GetGenericArguments()[0]; return true; } if (genericTypeDefinition != typeof(IList<>) && genericTypeDefinition != typeof(IEnumerable<>) && genericTypeDefinition != typeof(HashSet<>) && genericTypeDefinition != typeof(ISet<>)) { return false; } object obj2 = (propInfo.IsValidPublicProperty() ? propInfo.GetPropertyValue(obj) : null); if (obj2 != null && obj2.GetType().IsGenericType) { if (obj2.GetType().GetGenericTypeDefinition() == typeof(List<>)) { Type type = obj2.GetType(); collectionObject = Activator.CreateInstance(type); collectionAddMethod = type.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); collectionItemType = type.GetGenericArguments()[0]; return true; } if (obj2.GetType().GetGenericTypeDefinition() == typeof(HashSet<>)) { object obj3 = null; Type type2 = obj2.GetType(); PropertyInfo property = type2.GetProperty("Comparer", BindingFlags.Instance | BindingFlags.Public); if (property != null && property.IsValidPublicProperty()) { obj3 = property.GetPropertyValue(obj2); } if (obj3 != null) { ConstructorInfo constructor = type2.GetConstructor(new Type[1] { obj3.GetType() }); if (constructor != null) { collectionObject = constructor.Invoke(new object[1] { obj3 }); } else { collectionObject = Activator.CreateInstance(type2); } } else { collectionObject = Activator.CreateInstance(type2); } collectionAddMethod = type2.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); collectionItemType = type2.GetGenericArguments()[0]; return true; } } if (TryCreateHashSetCollection(propertyType, out collectionObject, out collectionAddMethod, out collectionItemType)) { return true; } if (TryCreateHashSetCollection(propertyType, out collectionObject, out collectionAddMethod, out collectionItemType)) { return true; } if (genericTypeDefinition == typeof(HashSet<>)) { collectionObject = Activator.CreateInstance(propertyType); collectionAddMethod = propertyType.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); collectionItemType = propertyType.GetGenericArguments()[0]; return true; } InternalLogger.Debug("Object type reflection needed to configure instance of type: {0}", propertyType); return TryCreateTypeCollection(propertyType, out collectionObject, out collectionAddMethod, out collectionItemType); } private static bool TryCreateListCollection(Type collectionType, out object? collectionObject, out MethodInfo? collectionAddMethod, out Type? collectionItemType) { if (collectionType.IsAssignableFrom(typeof(List))) { collectionObject = new List(); collectionAddMethod = typeof(List).GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); collectionItemType = typeof(T); return true; } collectionObject = null; collectionAddMethod = null; collectionItemType = null; return false; } private static bool TryCreateHashSetCollection(Type collectionType, out object? collectionObject, out MethodInfo? collectionAddMethod, out Type? collectionItemType) { if (collectionType.IsAssignableFrom(typeof(HashSet))) { collectionObject = new HashSet(); collectionAddMethod = typeof(HashSet).GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); collectionItemType = typeof(T); return true; } collectionObject = null; collectionAddMethod = null; collectionItemType = null; return false; } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL3050")] private static bool TryCreateTypeCollection(Type propertyType, out object collectionObject, out MethodInfo collectionAddMethod, out Type collectionItemType) { if (propertyType.GetGenericTypeDefinition() == typeof(ISet<>)) { Type type = typeof(HashSet<>).MakeGenericType(propertyType.GetGenericArguments()); collectionAddMethod = type.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); collectionItemType = propertyType.GetGenericArguments()[0]; collectionObject = Activator.CreateInstance(type); return true; } Type type2 = typeof(List<>).MakeGenericType(propertyType.GetGenericArguments()); collectionAddMethod = type2.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public); collectionItemType = propertyType.GetGenericArguments()[0]; collectionObject = Activator.CreateInstance(type2); return true; } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2026")] [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2067")] [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2072")] internal static bool TryTypeConverterConversion(Type type, string value, out object? newValue) { if (typeof(IConvertible).IsAssignableFrom(type) || type.IsAssignableFrom(typeof(string))) { newValue = null; return false; } try { InternalLogger.Debug("Object reflection needed for creating external type: {0} from string-value: {1}", type, value); TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(typeof(string))) { newValue = converter.ConvertFromInvariantString(value); return true; } newValue = null; return false; } catch (MissingMethodException ex) { InternalLogger.Error(ex, "Error in lookup of TypeDescriptor for type={0} to convert value '{1}'", new ReadOnlySpan(new object[2] { type, value })); newValue = null; return false; } } private static bool TryCreatePropertyInfoDictionary(ConfigurationItemFactory configFactory, Type objectType, out Dictionary? result) { result = null; try { if (!typeof(ISupportsInitialize).IsAssignableFrom(objectType) && !objectType.IsDefined(_configPropertyAttribute.GetType(), inherit: true)) { return false; } Dictionary dictionary = configFactory.TryGetTypeProperties(objectType); if (dictionary == null) { return false; } if (dictionary.Count == 0) { result = dictionary; return true; } if (!HasCustomConfigurationProperties(objectType, dictionary)) { result = dictionary; return true; } bool checkDefaultValue = typeof(LayoutRenderer).IsAssignableFrom(objectType); result = new Dictionary(dictionary.Count + 4, StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair item in dictionary) { PropertyInfo value = item.Value; if (IncludeConfigurationPropertyInfo(objectType, value, checkDefaultValue, out string overridePropertyName)) { result[value.Name] = value; if (overridePropertyName != null) { result[overridePropertyName] = value; } } } } catch (Exception ex) { InternalLogger.Debug(ex, "Type reflection not possible for type {0}. Maybe because of .NET Native.", new ReadOnlySpan(new object[1] { objectType })); } return result != null; } private static bool HasCustomConfigurationProperties(Type objectType, Dictionary objectProperties) { bool checkDefaultValue = typeof(LayoutRenderer).IsAssignableFrom(objectType); foreach (KeyValuePair objectProperty in objectProperties) { if (!IncludeConfigurationPropertyInfo(objectType, objectProperty.Value, checkDefaultValue, out string overridePropertyName) || overridePropertyName != null) { return true; } } return false; } private static bool IncludeConfigurationPropertyInfo(Type objectType, PropertyInfo propInfo, bool checkDefaultValue, out string? overridePropertyName) { overridePropertyName = null; try { Type propertyType = propInfo.PropertyType; if ((object)propertyType == null) { return false; } if (checkDefaultValue && propInfo.IsDefined(_defaultParameterAttribute.GetType(), inherit: false)) { overridePropertyName = string.Empty; return true; } if (IsSimplePropertyType(propertyType)) { return true; } if (typeof(ISupportsInitialize).IsAssignableFrom(propertyType)) { return true; } if (propInfo.IsDefined(_ignorePropertyAttribute.GetType(), inherit: false)) { return false; } if (typeof(IEnumerable).IsAssignableFrom(propertyType)) { ArrayParameterAttribute firstCustomAttribute = propInfo.GetFirstCustomAttribute(); if (firstCustomAttribute != null) { overridePropertyName = firstCustomAttribute.ElementName; return true; } } return true; } catch (Exception ex) { InternalLogger.Debug(ex, "Type reflection not possible for property {0} on type {1}. Maybe because of .NET Native.", new ReadOnlySpan(new object[2] { propInfo.Name, objectType })); return false; } } } internal static class ReflectionHelpers { public delegate object? LateBoundMethod(object target, object?[] arguments); public static bool IsStaticClass(this Type type) { if (type.IsClass && type.IsAbstract) { return type.IsSealed; } return false; } public static LateBoundMethod CreateLateBoundMethod(MethodInfo methodInfo) { MethodInfo methodInfo2 = methodInfo; if (!RuntimeFeature.IsDynamicCodeSupported) { return delegate(object target, object?[] args) { try { return methodInfo2.Invoke(target, args); } catch (TargetInvocationException ex) { throw ex.InnerException ?? ex; } }; } return CompileLateBoundMethod(methodInfo2); } private static LateBoundMethod CompileLateBoundMethod(MethodInfo methodInfo) { ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "instance"); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(object[]), "parameters"); IEnumerable parameterExpressions = BuildParameterList(methodInfo, parameterExpression2); MethodCallExpression methodCallExpression = BuildMethodCall(methodInfo, parameterExpression, parameterExpressions); if (methodCallExpression.Type == typeof(void)) { Expression> expression = Expression.Lambda>(methodCallExpression, new ParameterExpression[2] { parameterExpression, parameterExpression2 }); Action execute = expression.Compile(); return delegate(object instance, object?[] parameters) { execute(instance, parameters); return null; }; } return Expression.Lambda(Expression.Convert(methodCallExpression, typeof(object)), new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile(); } private static IEnumerable BuildParameterList(MethodBase methodInfo, ParameterExpression parametersParameter) { List list = new List(); ParameterInfo[] parameters = methodInfo.GetParameters(); for (int i = 0; i < parameters.Length; i++) { BinaryExpression expression = Expression.ArrayIndex(parametersParameter, Expression.Constant(i)); UnaryExpression item = CreateParameterExpression(parameters[i], expression); list.Add(item); } return list; } private static MethodCallExpression BuildMethodCall(MethodInfo methodInfo, ParameterExpression instanceParameter, IEnumerable parameterExpressions) { return Expression.Call(methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType), methodInfo, parameterExpressions); } private static UnaryExpression CreateParameterExpression(ParameterInfo parameterInfo, Expression expression) { Type type = parameterInfo.ParameterType; if (type.IsByRef) { type = type.GetElementType(); } return Expression.Convert(expression, type); } public static TAttr? GetFirstCustomAttribute(this Type type) where TAttr : Attribute { return Attribute.GetCustomAttributes(type, typeof(TAttr)).FirstOrDefault() as TAttr; } public static TAttr? GetFirstCustomAttribute(this PropertyInfo info) where TAttr : Attribute { return Attribute.GetCustomAttributes(info, typeof(TAttr)).FirstOrDefault() as TAttr; } public static TAttr? GetFirstCustomAttribute(this Assembly assembly) where TAttr : Attribute { return Attribute.GetCustomAttributes(assembly, typeof(TAttr)).FirstOrDefault() as TAttr; } public static IEnumerable GetCustomAttributes(this Type type, bool inherit) where TAttr : Attribute { return (TAttr[])type.GetCustomAttributes(typeof(TAttr), inherit); } public static bool IsValidPublicProperty(this PropertyInfo? p) { if (p != null && p.CanRead && p.GetIndexParameters().Length == 0) { return p.GetGetMethod() != null; } return false; } public static object? GetPropertyValue(this PropertyInfo p, object instance) { return p.GetValue(instance); } } internal sealed class ReusableAsyncLogEventList : ReusableObjectCreator> { public ReusableAsyncLogEventList(int initialCapacity) : base((Func>)(() => new List(initialCapacity)), (Action>)delegate(IList l) { l.Clear(); }) { } } internal sealed class ReusableBufferCreator : ReusableObjectCreator { public ReusableBufferCreator(int initialCapacity) : base((Func)(() => new char[initialCapacity]), (Action)delegate { }) { } } internal sealed class ReusableBuilderCreator : ReusableObjectCreator { private const int MaxBuilderCapacity = 40960; public ReusableBuilderCreator() : base((Func)(() => new StringBuilder(512)), (Action)delegate(StringBuilder sb) { ResetCapacity(sb); }) { } private static void ResetCapacity(StringBuilder stringBuilder) { if (stringBuilder.Length > 40960 && stringBuilder.Capacity > 409600) { stringBuilder.Remove(0, stringBuilder.Length - 1); stringBuilder.Capacity = 40960; } stringBuilder.ClearBuilder(); } } internal class ReusableObjectCreator where T : class { public readonly struct LockOject : IDisposable { public readonly T Result; private readonly ReusableObjectCreator _owner; public LockOject(ReusableObjectCreator owner, T reusableObject) { Result = reusableObject; _owner = owner; } public void Dispose() { _owner?.Deallocate(Result); } } protected T? _reusableObject; private readonly Action _clearObject; private readonly Func _createObject; protected ReusableObjectCreator(Func createObject, Action clearObject) { _reusableObject = createObject(); _clearObject = clearObject; _createObject = createObject; } public LockOject Allocate() { T reusableObject = _reusableObject ?? _createObject(); _reusableObject = null; return new LockOject(this, reusableObject); } private void Deallocate(T reusableObject) { _clearObject(reusableObject); _reusableObject = reusableObject; } } internal sealed class ReusableStreamCreator : ReusableObjectCreator, IDisposable { public ReusableStreamCreator() : base((Func)(() => new MemoryStream(4096)), (Action)delegate(MemoryStream ms) { ResetCapacity(ms); }) { } public ReusableStreamCreator(bool batchStream) : base((Func)(() => new MemoryStream(4096)), (Action)delegate(MemoryStream ms) { ResetBatchCapacity(ms); }) { } private static void ResetCapacity(MemoryStream memoryStream) { memoryStream.Position = 0L; memoryStream.SetLength(0L); if (memoryStream.Capacity > 1000000) { memoryStream.Capacity = 81920; } } private static void ResetBatchCapacity(MemoryStream memoryStream) { memoryStream.Position = 0L; memoryStream.SetLength(0L); if (memoryStream.Capacity > 10000000) { memoryStream.Capacity = 81920; } } void IDisposable.Dispose() { _reusableObject?.Dispose(); } } internal enum RuntimeOS { Unknown, Linux, Windows9x, WindowsNT, MacOSX } internal abstract class ScopeContextAsyncState : IDisposable { private bool _disposed; public IScopeContextAsyncState? Parent { get; } protected ScopeContextAsyncState(IScopeContextAsyncState? parent) { Parent = parent; } void IDisposable.Dispose() { if (!_disposed) { ScopeContext.SetAsyncLocalContext(Parent); _disposed = true; } } } internal interface IScopeContextAsyncState : IDisposable { IScopeContextAsyncState? Parent { get; } object? NestedState { get; } long NestedStateTimestamp { get; } IReadOnlyCollection>? CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector); IList? CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector); } internal struct ScopeContextPropertyCollector { private IReadOnlyCollection>? _allProperties; private List> _propertyCollector; public bool IsCollectorEmpty { get { if (_allProperties != null) { if (_allProperties.Count == 0) { return _propertyCollector == null; } return false; } return true; } } public bool IsCollectorInactive => _allProperties == null; public ScopeContextPropertyCollector(List> propertyCollector) { _allProperties = (_propertyCollector = propertyCollector); } public IReadOnlyCollection> StartCaptureProperties(IScopeContextAsyncState? state) { while (state != null) { IReadOnlyCollection> readOnlyCollection = state.CaptureContextProperties(ref this); if (readOnlyCollection != null) { return readOnlyCollection; } state = state.Parent; } return CaptureCompleted(null); } public IReadOnlyCollection> CaptureCompleted(IReadOnlyCollection>? properties) { IReadOnlyCollection>? allProperties = _allProperties; if (allProperties != null && allProperties.Count > 0) { if (properties != null && properties.Count > 0) { if (_propertyCollector == null) { return _allProperties = MergeUniqueProperties(_allProperties, properties); } AddProperties(properties); } return _allProperties = EnsureUniqueProperties(_allProperties); } if (properties != null && properties.Count > 0) { return _allProperties = EnsureUniqueProperties(properties); } return _allProperties = (IReadOnlyCollection>?)(object)Array.Empty>(); } private static Dictionary MergeUniqueProperties(IReadOnlyCollection> currentProperties, IReadOnlyCollection> properties) { Dictionary dictionary = new Dictionary(currentProperties.Count + properties.Count, ScopeContext.DefaultComparer); ScopeContextPropertyEnumerator.CopyScopePropertiesToDictionary(properties, dictionary); ScopeContextPropertyEnumerator.CopyScopePropertiesToDictionary(currentProperties, dictionary); return dictionary; } private static IReadOnlyCollection> EnsureUniqueProperties(IReadOnlyCollection> properties) { int count = properties.Count; if (count <= 1) { return properties; } if (properties is Dictionary dictionary && dictionary.Comparer == ScopeContext.DefaultComparer) { return properties; } if (count > 10 || !ScopeContextPropertyEnumerator.HasUniqueCollectionKeys(properties, ScopeContext.DefaultComparer)) { Dictionary dictionary2 = new Dictionary(Math.Min(count, 10), ScopeContext.DefaultComparer); ScopeContextPropertyEnumerator.CopyScopePropertiesToDictionary(properties, dictionary2); return dictionary2; } return properties; } public void AddProperty(string propertyName, object? propertyValue) { if (_allProperties == null || IsCollectorEmpty) { _allProperties = (IReadOnlyCollection>?)(object)new KeyValuePair[1] { new KeyValuePair(propertyName, propertyValue) }; } else if (_propertyCollector == null) { _propertyCollector = new List>(Math.Max(4, _allProperties.Count + 1)); _propertyCollector.Add(new KeyValuePair(propertyName, propertyValue)); CollectProperties(_allProperties); _allProperties = _propertyCollector; } else { _propertyCollector.Insert(0, new KeyValuePair(propertyName, propertyValue)); } } public void AddProperties(IReadOnlyCollection> properties) { if (_allProperties == null || IsCollectorEmpty) { _allProperties = properties; } else { if (properties == null || properties.Count <= 0) { return; } if (_propertyCollector == null) { _propertyCollector = new List>(Math.Max(4, _allProperties.Count + properties.Count)); CollectProperties(properties); CollectProperties(_allProperties); _allProperties = _propertyCollector; return; } if (_propertyCollector.Count != 0) { int num = 0; using ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = new ScopeContextPropertyEnumerator(properties); while (scopeContextPropertyEnumerator.MoveNext()) { KeyValuePair current = scopeContextPropertyEnumerator.Current; _propertyCollector.Insert(num++, current); } return; } CollectProperties(properties); } } private void CollectProperties(IReadOnlyCollection> properties) { using ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = new ScopeContextPropertyEnumerator(properties); while (scopeContextPropertyEnumerator.MoveNext()) { KeyValuePair current = scopeContextPropertyEnumerator.Current; _propertyCollector.Add(current); } } } internal struct ScopeContextNestedStateCollector { private IList _allNestedStates; private List _nestedStateCollector; public bool IsCollectorEmpty { get { if (_allNestedStates != null) { if (_allNestedStates.Count == 0) { return _nestedStateCollector == null; } return false; } return true; } } public bool IsCollectorInactive => _allNestedStates == null; public IList StartCaptureNestedStates(IScopeContextAsyncState? state) { _allNestedStates = _allNestedStates ?? Array.Empty(); while (state != null) { IList list = state.CaptureNestedContext(ref this); if (list != null) { return list; } state = state.Parent; } return _allNestedStates; } public void PushNestedState(object state) { if (_nestedStateCollector == null) { _nestedStateCollector = new List(Math.Max(4, _allNestedStates?.Count ?? 1)); IList allNestedStates = _allNestedStates; if (allNestedStates != null && allNestedStates.Count > 0) { for (int i = 0; i < _allNestedStates.Count; i++) { _nestedStateCollector.Add(_allNestedStates[i]); } } _allNestedStates = _nestedStateCollector; } _nestedStateCollector.Add(state); } } internal interface IScopeContextPropertiesAsyncState : IScopeContextAsyncState, IDisposable { } internal sealed class ScopedContextNestedAsyncState : ScopeContextAsyncState, IScopeContextAsyncState, IDisposable { private readonly T _value; object? IScopeContextAsyncState.NestedState => _value; public long NestedStateTimestamp { get; } public ScopedContextNestedAsyncState(IScopeContextAsyncState? parent, T state) : base(parent) { NestedStateTimestamp = ScopeContext.GetNestedContextTimestampNow(); _value = state; } IList? IScopeContextAsyncState.CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector) { object obj = _value; if (contextCollector.IsCollectorEmpty) { if (base.Parent == null) { if (obj != null) { return new object[1] { obj }; } return Array.Empty(); } if (contextCollector.IsCollectorInactive) { if (obj != null) { contextCollector.PushNestedState(obj); } return contextCollector.StartCaptureNestedStates(base.Parent); } } if (obj != null) { contextCollector.PushNestedState(obj); } return null; } IReadOnlyCollection>? IScopeContextAsyncState.CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector) { if (contextCollector.IsCollectorInactive) { if (base.Parent == null) { return (IReadOnlyCollection>?)(object)Array.Empty>(); } contextCollector.AddProperties((IReadOnlyCollection>)(object)Array.Empty>()); return contextCollector.StartCaptureProperties(base.Parent); } return null; } public override string ToString() { T value = _value; return ((value != null) ? value.ToString() : null) ?? "null"; } } internal sealed class ScopeContextPropertyAsyncState : ScopeContextAsyncState, IScopeContextPropertiesAsyncState, IScopeContextAsyncState, IDisposable { private IReadOnlyCollection>? _allProperties; long IScopeContextAsyncState.NestedStateTimestamp => 0L; object? IScopeContextAsyncState.NestedState => null; public string Name { get; } public TValue? Value { get; } public ScopeContextPropertyAsyncState(IScopeContextAsyncState? parent, string name, TValue? value) : base(parent) { Name = name; Value = value; } IList? IScopeContextAsyncState.CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector) { if (contextCollector.IsCollectorInactive) { if (base.Parent == null) { return Array.Empty(); } return contextCollector.StartCaptureNestedStates(base.Parent); } return null; } IReadOnlyCollection>? IScopeContextAsyncState.CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector) { if (contextCollector.IsCollectorEmpty) { if (_allProperties == null) { contextCollector.AddProperty(Name, Value); _allProperties = contextCollector.StartCaptureProperties(base.Parent); } return _allProperties; } if (_allProperties == null) { contextCollector.AddProperty(Name, Value); return null; } return contextCollector.CaptureCompleted(_allProperties); } public override string ToString() { string name = Name; TValue value = Value; return name + "=" + (((value != null) ? value.ToString() : null) ?? "null"); } } internal sealed class ScopeContextPropertiesAsyncState : ScopeContextAsyncState, IScopeContextPropertiesAsyncState, IScopeContextAsyncState, IDisposable, IReadOnlyCollection>, IEnumerable>, IEnumerable { private readonly IReadOnlyCollection> _scopeProperties; private IReadOnlyCollection>? _allProperties; public long NestedStateTimestamp { get; } public object? NestedState { get; } public int Count => _scopeProperties.Count; public ScopeContextPropertiesAsyncState(IScopeContextAsyncState? parent, Dictionary allProperties) : base(parent) { _allProperties = allProperties; _scopeProperties = (IReadOnlyCollection>)(object)Array.Empty>(); } public ScopeContextPropertiesAsyncState(IScopeContextAsyncState? parent, Dictionary allProperties, object? nestedState) : base(parent) { _allProperties = allProperties; _scopeProperties = (IReadOnlyCollection>)(object)Array.Empty>(); NestedState = nestedState; NestedStateTimestamp = ScopeContext.GetNestedContextTimestampNow(); } public ScopeContextPropertiesAsyncState(IScopeContextAsyncState? parent, IReadOnlyCollection> scopeProperties) : base(parent) { _scopeProperties = scopeProperties; } public ScopeContextPropertiesAsyncState(IScopeContextAsyncState? parent, IReadOnlyCollection> scopeProperties, object? nestedState) : base(parent) { _scopeProperties = scopeProperties; NestedState = nestedState; NestedStateTimestamp = ScopeContext.GetNestedContextTimestampNow(); } IList? IScopeContextAsyncState.CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector) { if (NestedState == null) { if (contextCollector.IsCollectorInactive) { return contextCollector.StartCaptureNestedStates(base.Parent); } return null; } if (contextCollector.IsCollectorEmpty) { if (base.Parent == null) { return new object[1] { NestedState }; } if (contextCollector.IsCollectorInactive) { contextCollector.PushNestedState(NestedState); return contextCollector.StartCaptureNestedStates(base.Parent); } } contextCollector.PushNestedState(NestedState); return null; } IReadOnlyCollection>? IScopeContextAsyncState.CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector) { if (contextCollector.IsCollectorEmpty) { if (_allProperties == null) { contextCollector.AddProperties((_scopeProperties as IReadOnlyCollection>) ?? this); _allProperties = contextCollector.StartCaptureProperties(base.Parent); } return _allProperties; } if (_allProperties == null) { contextCollector.AddProperties((_scopeProperties as IReadOnlyCollection>) ?? this); return null; } return contextCollector.CaptureCompleted(_allProperties); } public override string ToString() { return NestedState?.ToString() ?? $"Count = {Count}"; } IEnumerator> IEnumerable>.GetEnumerator() { return new ScopeContextPropertyEnumerator(_scopeProperties); } IEnumerator IEnumerable.GetEnumerator() { return new ScopeContextPropertyEnumerator(_scopeProperties); } } [Obsolete("Replaced by ScopeContext.PushProperty / ScopeContext.PushNestedState")] internal sealed class ScopeContextLegacyAsyncState : ScopeContextAsyncState, IScopeContextAsyncState, IDisposable { public object[] NestedContext { get; } public IReadOnlyCollection>? MappedContext { get; } public long NestedStateTimestamp { get; } object? IScopeContextAsyncState.NestedState { get { object[] nestedContext = NestedContext; if (nestedContext == null || nestedContext.Length == 0) { return null; } return NestedContext[0]; } } public ScopeContextLegacyAsyncState(IReadOnlyCollection>? allProperties, object[] nestedContext, long nestedContextTimestamp) : base(null) { MappedContext = allProperties; NestedContext = nestedContext; NestedStateTimestamp = nestedContextTimestamp; } public static void CaptureLegacyContext(IScopeContextAsyncState? contextState, out Dictionary allProperties, out object[] nestedContext, out long nestedContextTimestamp) { ScopeContextNestedStateCollector contextCollector = default(ScopeContextNestedStateCollector); ScopeContextPropertyCollector contextCollector2 = default(ScopeContextPropertyCollector); IList list = contextState?.CaptureNestedContext(ref contextCollector) ?? Array.Empty(); IReadOnlyCollection> readOnlyCollection = (IReadOnlyCollection>)(((object)contextState?.CaptureContextProperties(ref contextCollector2)) ?? ((object)Array.Empty>())); allProperties = new Dictionary(readOnlyCollection.Count, ScopeContext.DefaultComparer); ScopeContextPropertyEnumerator.CopyScopePropertiesToDictionary(readOnlyCollection, allProperties); nestedContextTimestamp = 0L; if (list.Count > 0) { for (IScopeContextAsyncState scopeContextAsyncState = contextState; scopeContextAsyncState != null; scopeContextAsyncState = scopeContextAsyncState.Parent) { if (scopeContextAsyncState.NestedStateTimestamp != 0L) { nestedContextTimestamp = scopeContextAsyncState.NestedStateTimestamp; } } if (nestedContextTimestamp == 0L) { nestedContextTimestamp = ScopeContext.GetNestedContextTimestampNow(); } nestedContext = (list as object[]) ?? CloneNestedContext(list); } else { nestedContext = Array.Empty(); } } IList IScopeContextAsyncState.CaptureNestedContext(ref ScopeContextNestedStateCollector contextCollector) { if (contextCollector.IsCollectorEmpty) { object[] nestedContext = NestedContext; if (nestedContext == null || nestedContext.Length == 0) { return Array.Empty(); } return CloneNestedContext(NestedContext); } for (int i = 0; i < NestedContext.Length; i++) { contextCollector.PushNestedState(NestedContext[i]); } return contextCollector.StartCaptureNestedStates(null); } private static object[] CloneNestedContext(IList nestedContext) { object[] array = new object[nestedContext.Count]; for (int i = 0; i < nestedContext.Count; i++) { array[i] = nestedContext[i]; } return array; } IReadOnlyCollection>? IScopeContextAsyncState.CaptureContextProperties(ref ScopeContextPropertyCollector contextCollector) { if (contextCollector.IsCollectorEmpty) { return MappedContext; } return contextCollector.CaptureCompleted(MappedContext); } public override string ToString() { object[] nestedContext = NestedContext; if (nestedContext != null && nestedContext.Length != 0) { return NestedContext[NestedContext.Length - 1]?.ToString() ?? "null"; } return base.ToString() ?? GetType().ToString(); } } internal struct ScopeContextPropertyEnumerator : IEnumerator>, IEnumerator, IDisposable { [CompilerGenerated] private sealed class d__7 : IEnumerable>, IEnumerable, IEnumerator>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair <>2__current; private int <>l__initialThreadId; private IEnumerable> scopeProperties; public IEnumerable> <>3__scopeProperties; private IEnumerator> <>7__wrap1; KeyValuePair IEnumerator>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__7(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = scopeProperties.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { KeyValuePair current = <>7__wrap1.Current; <>2__current = new KeyValuePair(current.Key, current.Value); <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator> IEnumerable>.GetEnumerator() { d__7 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__7(0); } d__.scopeProperties = <>3__scopeProperties; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable>)this).GetEnumerator(); } } private readonly IEnumerator>? _scopeEnumerator; private readonly IReadOnlyList>? _scopeList; private int _scopeIndex; private Dictionary.Enumerator _dictionaryEnumerator; public KeyValuePair Current { get { if (_scopeList != null) { return _scopeList[_scopeIndex]; } if (_scopeEnumerator != null) { return _scopeEnumerator.Current; } return _dictionaryEnumerator.Current; } } object IEnumerator.Current => Current; public ScopeContextPropertyEnumerator(IEnumerable> scopeProperties) { if (scopeProperties is IReadOnlyList> scopeList) { _scopeEnumerator = null; _scopeList = scopeList; _scopeIndex = -1; _dictionaryEnumerator = default(Dictionary.Enumerator); return; } _scopeList = null; _scopeIndex = 0; if (scopeProperties is Dictionary dictionary) { _scopeEnumerator = null; _dictionaryEnumerator = dictionary.GetEnumerator(); } else if (scopeProperties is IEnumerable> enumerable) { _scopeEnumerator = enumerable.GetEnumerator(); _dictionaryEnumerator = default(Dictionary.Enumerator); } else { _scopeEnumerator = CreateScopeEnumerable(scopeProperties).GetEnumerator(); _dictionaryEnumerator = default(Dictionary.Enumerator); } } public static void CopyScopePropertiesToDictionary(IReadOnlyCollection> parentContext, Dictionary scopeDictionary) { using ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = new ScopeContextPropertyEnumerator(parentContext); while (scopeContextPropertyEnumerator.MoveNext()) { KeyValuePair current = scopeContextPropertyEnumerator.Current; scopeDictionary[current.Key] = current.Value; } } public static bool HasUniqueCollectionKeys(IEnumerable> scopeProperties, IEqualityComparer keyComparer) { int num = 1; using (ScopeContextPropertyEnumerator scopeContextPropertyEnumerator = new ScopeContextPropertyEnumerator(scopeProperties)) { while (scopeContextPropertyEnumerator.MoveNext()) { num++; string key = scopeContextPropertyEnumerator.Current.Key; if (!scopeContextPropertyEnumerator.MoveNext()) { return true; } num++; string key2 = scopeContextPropertyEnumerator.Current.Key; if (keyComparer.Equals(key, key2)) { return false; } int num2 = 0; using ScopeContextPropertyEnumerator scopeContextPropertyEnumerator2 = new ScopeContextPropertyEnumerator(scopeProperties); while (scopeContextPropertyEnumerator2.MoveNext()) { if (++num2 >= num) { if (num2 > 10) { return false; } string key3 = scopeContextPropertyEnumerator2.Current.Key; if (keyComparer.Equals(key, key3)) { return false; } if (keyComparer.Equals(key2, key3)) { return false; } } } } } return true; } [IteratorStateMachine(typeof(ScopeContextPropertyEnumerator<>.d__7))] private static IEnumerable> CreateScopeEnumerable(IEnumerable> scopeProperties) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__7(-2) { <>3__scopeProperties = scopeProperties }; } public void Dispose() { if (_scopeEnumerator != null) { _scopeEnumerator.Dispose(); } else if (_scopeList == null) { _dictionaryEnumerator.Dispose(); } } public bool MoveNext() { if (_scopeList != null) { if (_scopeIndex < _scopeList.Count - 1) { _scopeIndex++; return true; } return false; } if (_scopeEnumerator != null) { return _scopeEnumerator.MoveNext(); } return _dictionaryEnumerator.MoveNext(); } public void Reset() { if (_scopeList != null) { _scopeIndex = -1; } else if (_scopeEnumerator != null) { _scopeEnumerator.Reset(); } else { _dictionaryEnumerator = default(Dictionary.Enumerator); } } } internal sealed class SetupBuilder : ISetupBuilder { public LogFactory LogFactory { get; } internal SetupBuilder(LogFactory logFactory) { LogFactory = logFactory; } } internal sealed class SetupConfigurationLoggingRuleBuilder : ISetupConfigurationLoggingRuleBuilder, ISetupConfigurationTargetBuilder, IList, ICollection, IEnumerable, IEnumerable { public LoggingRule LoggingRule { get; } public LoggingConfiguration Configuration { get; } public LogFactory LogFactory { get; } public IList Targets => this; Target IList.this[int index] { get { return LoggingRule.Targets[index]; } set { LoggingRule.Targets[index] = value; } } int ICollection.Count => LoggingRule.Targets.Count; bool ICollection.IsReadOnly => LoggingRule.Targets.IsReadOnly; public SetupConfigurationLoggingRuleBuilder(LogFactory logFactory, LoggingConfiguration configuration, string? loggerNamePattern = null, string? ruleName = null) { LoggingRule = new LoggingRule(ruleName) { LoggerNamePattern = (loggerNamePattern ?? "*") }; Configuration = configuration; LogFactory = logFactory; } void ICollection.Add(Target item) { if (!Configuration.LoggingRules.Contains(LoggingRule)) { Configuration.LoggingRules.Add(LoggingRule); } LoggingRule.Targets.Add(item); } void ICollection.Clear() { LoggingRule.Targets.Clear(); } bool ICollection.Contains(Target item) { return LoggingRule.Targets.Contains(item); } void ICollection.CopyTo(Target[] array, int arrayIndex) { LoggingRule.Targets.CopyTo(array, arrayIndex); } IEnumerator IEnumerable.GetEnumerator() { return LoggingRule.Targets.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return LoggingRule.Targets.GetEnumerator(); } int IList.IndexOf(Target item) { return LoggingRule.Targets.IndexOf(item); } void IList.Insert(int index, Target item) { LoggingRule.Targets.Insert(index, item); } bool ICollection.Remove(Target item) { return LoggingRule.Targets.Remove(item); } void IList.RemoveAt(int index) { LoggingRule.Targets.RemoveAt(index); } } internal sealed class SetupConfigurationTargetBuilder : ISetupConfigurationTargetBuilder, IList, ICollection, IEnumerable, IEnumerable { private readonly IList _targets = new List(); private string? _targetName; public LoggingConfiguration Configuration { get; } public LogFactory LogFactory { get; } public IList Targets => this; Target IList.this[int index] { get { return _targets[index]; } set { _targets[index] = value; } } int ICollection.Count => _targets.Count; bool ICollection.IsReadOnly => _targets.IsReadOnly; public SetupConfigurationTargetBuilder(LogFactory logFactory, LoggingConfiguration configuration, string? targetName = null) { Configuration = configuration; LogFactory = logFactory; _targetName = (string.IsNullOrEmpty(targetName) ? null : targetName); } private void UpdateTargetName(Target item) { if (_targetName != null && !string.IsNullOrEmpty(_targetName)) { item.Name = _targetName; _targetName = string.Empty; } else if (_targetName == string.Empty) { throw new ArgumentException("Cannot apply the same Target-Name to multiple targets"); } } void ICollection.Add(Target item) { UpdateTargetName(item); _targets.Add(item); } void ICollection.Clear() { _targets.Clear(); } bool ICollection.Contains(Target item) { return _targets.Contains(item); } void ICollection.CopyTo(Target[] array, int arrayIndex) { _targets.CopyTo(array, arrayIndex); } IEnumerator IEnumerable.GetEnumerator() { return _targets.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _targets.GetEnumerator(); } int IList.IndexOf(Target item) { return _targets.IndexOf(item); } void IList.Insert(int index, Target item) { UpdateTargetName(item); _targets.Insert(index, item); } bool ICollection.Remove(Target item) { return _targets.Remove(item); } void IList.RemoveAt(int index) { _targets.RemoveAt(index); } } internal sealed class SetupExtensionsBuilder : ISetupExtensionsBuilder { public LogFactory LogFactory { get; } internal SetupExtensionsBuilder(LogFactory logFactory) { LogFactory = logFactory; } } internal sealed class SetupInternalLoggerBuilder : ISetupInternalLoggerBuilder { public LogFactory LogFactory { get; } internal SetupInternalLoggerBuilder(LogFactory logFactory) { LogFactory = logFactory; } } internal sealed class SetupLoadConfigurationBuilder : ISetupLoadConfigurationBuilder { internal LoggingConfiguration? _configuration; public LogFactory LogFactory { get; } public LoggingConfiguration Configuration { get { return _configuration ?? (_configuration = new LoggingConfiguration(LogFactory)); } set { _configuration = value; } } internal SetupLoadConfigurationBuilder(LogFactory logFactory, LoggingConfiguration? configuration) { LogFactory = logFactory; _configuration = configuration; } } internal sealed class SetupLogFactoryBuilder : ISetupLogFactoryBuilder { public LogFactory LogFactory { get; } internal SetupLogFactoryBuilder(LogFactory logFactory) { LogFactory = logFactory; } } internal sealed class SetupSerializationBuilder : ISetupSerializationBuilder { public LogFactory LogFactory { get; } internal SetupSerializationBuilder(LogFactory logFactory) { LogFactory = logFactory; } } internal sealed class SimpleStringReader { private readonly string _text; internal int Position { get; set; } internal string Text => _text; public SimpleStringReader(string text) { _text = text; Position = 0; } internal int Peek() { if (Position < _text.Length) { return _text[Position]; } return -1; } internal int Read() { if (Position < _text.Length) { return _text[Position++]; } return -1; } internal string Substring(int startIndex, int endIndex) { return _text.Substring(startIndex, endIndex - startIndex); } internal string ReadUntilMatch(Func charFinder) { int position = Position; int arg; while ((arg = Peek()) != -1) { if (charFinder(arg)) { return Substring(position, Position); } Read(); } return Substring(position, Position); } } internal sealed class SingleCallContinuation { internal static readonly AsyncContinuation Completed = new SingleCallContinuation(null).CompletedFunction; private AsyncContinuation? _asyncContinuation; public SingleCallContinuation(AsyncContinuation? asyncContinuation) { _asyncContinuation = asyncContinuation; } public void Function(Exception? exception) { try { Interlocked.Exchange(ref _asyncContinuation, null)?.Invoke(exception); } catch (Exception ex) { InternalLogger.Error(ex, "Exception in asynchronous handler."); if (ex.MustBeRethrown()) { throw; } } } private void CompletedFunction(Exception? exception) { } } internal struct SingleItemOptimizedHashSet : ICollection, IEnumerable, IEnumerable { public struct SingleItemScopedInsert : IDisposable { private readonly T _singleItem; private readonly HashSet? _hashset; public SingleItemScopedInsert(T singleItem, ref SingleItemOptimizedHashSet existing, bool forceHashSet) { _singleItem = singleItem; if (existing._hashset != null) { existing._hashset.Add(singleItem); _hashset = existing._hashset; } else if (forceHashSet) { existing = new SingleItemOptimizedHashSet(singleItem, existing, ReferenceEqualityComparer.Default); existing.Add(singleItem); _hashset = existing._hashset; } else { existing = new SingleItemOptimizedHashSet(singleItem, existing, ReferenceEqualityComparer.Default); _hashset = null; } } public void Dispose() { if (_hashset != null) { _hashset.Remove(_singleItem); } } } public sealed class ReferenceEqualityComparer : IEqualityComparer { public static readonly ReferenceEqualityComparer Default = new ReferenceEqualityComparer(); bool IEqualityComparer.Equals(T? x, T? y) { return (object)x == (object)y; } int IEqualityComparer.GetHashCode(T obj) { return RuntimeHelpers.GetHashCode(obj); } } [CompilerGenerated] private sealed class d__17 : IEnumerator, IEnumerator, IDisposable { private int <>1__state; private T <>2__current; public SingleItemOptimizedHashSet <>4__this; T IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__17(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { switch (<>1__state) { default: return false; case 0: <>1__state = -1; if (<>4__this.Count == 1 && <>4__this._singleItem != null) { <>2__current = <>4__this._singleItem; <>1__state = 1; return true; } break; case 1: <>1__state = -1; break; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private readonly T? _singleItem; private HashSet? _hashset; private readonly IEqualityComparer? _comparer; private IEqualityComparer Comparer => _comparer ?? EqualityComparer.Default; public int Count => _hashset?.Count ?? ((!EqualityComparer.Default.Equals(_singleItem, default(T))) ? 1 : 0); public bool IsReadOnly => false; public SingleItemOptimizedHashSet(T singleItem, SingleItemOptimizedHashSet existing, IEqualityComparer? comparer = null) { _comparer = existing._comparer ?? comparer ?? EqualityComparer.Default; if (existing._hashset != null) { _hashset = new HashSet(existing._hashset, _comparer); _hashset.Add(singleItem); _singleItem = default(T); } else if (existing.Count == 1 && existing._singleItem != null) { _hashset = new HashSet(_comparer); _hashset.Add(existing._singleItem); _hashset.Add(singleItem); _singleItem = default(T); } else { _hashset = null; _singleItem = singleItem; } } public void Add(T item) { if (_hashset != null) { _hashset.Add(item); return; } HashSet hashSet = new HashSet(Comparer); if (Count == 1 && _singleItem != null) { hashSet.Add(_singleItem); } hashSet.Add(item); _hashset = hashSet; } public void Clear() { if (_hashset != null) { _hashset.Clear(); } else { _hashset = new HashSet(Comparer); } } public bool Contains(T item) { if (_hashset != null) { return _hashset.Contains(item); } if (Count == 1 && _singleItem != null) { return Comparer.Equals(_singleItem, item); } return false; } public bool Remove(T item) { if (_hashset != null) { return _hashset.Remove(item); } if (Count == 1 && _singleItem != null && Comparer.Equals(_singleItem, item)) { _hashset = new HashSet(Comparer); return true; } return false; } public void CopyTo(T[] array, int arrayIndex) { if (_hashset != null) { _hashset.CopyTo(array, arrayIndex); } else if (Count == 1 && _singleItem != null) { array[arrayIndex] = _singleItem; } } public IEnumerator GetEnumerator() { if (_hashset != null) { return _hashset.GetEnumerator(); } return SingleItemEnumerator(); } [IteratorStateMachine(typeof(SingleItemOptimizedHashSet<>.d__17))] private IEnumerator SingleItemEnumerator() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__17(0) { <>4__this = this }; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal static class SortHelpers { internal delegate TKey KeySelector(TValue value); public readonly struct ReadOnlySingleBucketGroupBy : IEnumerable>, IEnumerable where TKey : notnull { public struct Enumerator : IEnumerator>, IEnumerator, IDisposable { private bool _singleBucketFirstRead; private KeyValuePair _singleBucket; private readonly IEnumerator>? _multiBuckets; public KeyValuePair Current { get { if (_multiBuckets != null) { return _multiBuckets.Current; } return new KeyValuePair(_singleBucket.Key, _singleBucket.Value); } } object IEnumerator.Current => Current; internal Enumerator(Dictionary multiBucket) { _singleBucketFirstRead = false; _singleBucket = default(KeyValuePair); _multiBuckets = multiBucket.GetEnumerator(); } internal Enumerator(KeyValuePair singleBucket) { _singleBucketFirstRead = false; _singleBucket = singleBucket; _multiBuckets = null; } public void Dispose() { if (_multiBuckets != null) { _multiBuckets.Dispose(); } } public bool MoveNext() { if (_multiBuckets != null) { return _multiBuckets.MoveNext(); } if (_singleBucketFirstRead) { return false; } return _singleBucketFirstRead = true; } public void Reset() { if (_multiBuckets != null) { _multiBuckets.Reset(); } else { _singleBucketFirstRead = false; } } } private readonly KeyValuePair? _singleBucket; private readonly Dictionary? _multiBucket; private readonly IEqualityComparer _comparer; public IEqualityComparer Comparer => _comparer; public int Count => _multiBucket?.Count ?? (_singleBucket.HasValue ? 1 : 0); public ReadOnlySingleBucketGroupBy(KeyValuePair singleBucket) : this(singleBucket, EqualityComparer.Default) { } public ReadOnlySingleBucketGroupBy(Dictionary multiBucket) : this(multiBucket, EqualityComparer.Default) { } public ReadOnlySingleBucketGroupBy(KeyValuePair? singleBucket, IEqualityComparer comparer) { _comparer = comparer; _multiBucket = null; _singleBucket = singleBucket; } public ReadOnlySingleBucketGroupBy(Dictionary multiBucket, IEqualityComparer comparer) { _comparer = comparer; _multiBucket = multiBucket; _singleBucket = default(KeyValuePair); } public Enumerator GetEnumerator() { if (_multiBucket != null) { return new Enumerator(_multiBucket); } if (_singleBucket.HasValue) { return new Enumerator(_singleBucket.Value); } return new Enumerator(new Dictionary()); } IEnumerator> IEnumerable>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public static Dictionary> BucketSort(this IEnumerable inputs, KeySelector keySelector) where TKey : notnull { Dictionary> dictionary = new Dictionary>(); foreach (TValue input in inputs) { TKey key = keySelector(input); if (!dictionary.TryGetValue(key, out var value)) { value = new List(); dictionary.Add(key, value); } value.Add(input); } return dictionary; } public static ReadOnlySingleBucketGroupBy> BucketSort(this IList inputs, KeySelector keySelector) where TKey : notnull { return inputs.BucketSort(keySelector, EqualityComparer.Default); } public static ReadOnlySingleBucketGroupBy> BucketSort(this IList inputs, KeySelector keySelector, IEqualityComparer keyComparer) where TKey : notnull { if (inputs.Count == 0) { return new ReadOnlySingleBucketGroupBy>((KeyValuePair>?)null, keyComparer); } Dictionary> dictionary = null; TKey val = keySelector(inputs[0]); for (int i = 1; i < inputs.Count; i++) { TKey val2 = keySelector(inputs[i]); if (dictionary == null) { if (!keyComparer.Equals(val, val2)) { dictionary = CreateBucketDictionaryWithValue(inputs, keyComparer, i, val, val2); } continue; } if (!dictionary.TryGetValue(val2, out var value)) { value = new List(); dictionary.Add(val2, value); } value.Add(inputs[i]); } if (dictionary == null) { return new ReadOnlySingleBucketGroupBy>(new KeyValuePair>(val, inputs), keyComparer); } return new ReadOnlySingleBucketGroupBy>(dictionary, keyComparer); } private static Dictionary> CreateBucketDictionaryWithValue(IList inputs, IEqualityComparer keyComparer, int currentIndex, TKey firstBucketKey, TKey nextBucketKey) where TKey : notnull { Dictionary> dictionary = new Dictionary>(keyComparer); List list = new List(currentIndex); for (int i = 0; i < currentIndex; i++) { list.Add(inputs[i]); } dictionary[firstBucketKey] = list; List value = new List { inputs[currentIndex] }; dictionary[nextBucketKey] = value; return dictionary; } } internal static class StackTraceUsageUtils { private static readonly Assembly nlogAssembly = typeof(StackTraceUsageUtils).Assembly; private static readonly Assembly mscorlibAssembly = typeof(string).Assembly; private static readonly Assembly systemAssembly = typeof(Debug).Assembly; public static StackTraceUsage GetStackTraceUsage(bool includeFileName, int skipFrames, bool captureStackTrace) { if (!captureStackTrace) { return StackTraceUsage.None; } if (skipFrames != 0) { if (!includeFileName) { return StackTraceUsage.WithStackTrace; } return StackTraceUsage.WithSource; } if (includeFileName) { return StackTraceUsage.WithFileNameAndLineNumber | StackTraceUsage.WithCallSite; } return StackTraceUsage.WithCallSite; } public static int GetFrameCount(this StackTrace strackTrace) { return strackTrace.FrameCount; } public static string GetStackFrameMethodName(MethodBase method, bool includeMethodInfo, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { if ((object)method == null) { return string.Empty; } string text = method.Name; Type declaringType = method.DeclaringType; if (cleanAsyncMoveNext && text == "MoveNext" && declaringType?.DeclaringType != null && declaringType.Name.IndexOf('<') == 0) { int num = declaringType.Name.IndexOf('>', 1); if (num > 1) { text = declaringType.Name.Substring(1, num - 1); if (text.IndexOf('<') == 0) { text = text.Substring(1); } } } if (cleanAnonymousDelegates && text.IndexOf('<') == 0 && text.IndexOf("__", StringComparison.Ordinal) >= 0 && text.IndexOf('>') >= 0) { int num2 = text.IndexOf('<') + 1; int num3 = text.IndexOf('>'); text = text.Substring(num2, num3 - num2); } if (includeMethodInfo && text == method.Name) { text = method.ToString() ?? text; } return text; } public static string GetStackFrameMethodClassName(MethodBase method, bool includeNameSpace, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { if ((object)method == null) { return string.Empty; } Type declaringType = method.DeclaringType; if (cleanAsyncMoveNext && method.Name == "MoveNext" && declaringType?.DeclaringType != null) { string name = declaringType.Name; if (name != null && name.IndexOf('<') == 0 && declaringType.Name.IndexOf('>', 1) > 1) { declaringType = declaringType.DeclaringType; } } if ((object)declaringType == null) { return string.Empty; } string text = (includeNameSpace ? declaringType.FullName : declaringType.Name); if (cleanAnonymousDelegates && text != null && text.IndexOf("<>", StringComparison.Ordinal) >= 0) { if (!includeNameSpace && declaringType.DeclaringType != null && declaringType.IsNested) { text = declaringType.DeclaringType.Name; } else { int num = text.IndexOf("+<>", StringComparison.Ordinal); if (num >= 0) { text = text.Substring(0, num); } } } if (includeNameSpace && text != null && text.IndexOf('.') == -1) { string namespaceFromTypeAssembly = GetNamespaceFromTypeAssembly(declaringType); text = (string.IsNullOrEmpty(namespaceFromTypeAssembly) ? text : (namespaceFromTypeAssembly + "." + text)); } return text ?? string.Empty; } private static string GetNamespaceFromTypeAssembly(Type? callerClassType) { Assembly assembly = callerClassType?.Assembly; if (assembly != null && assembly != mscorlibAssembly && assembly != systemAssembly) { string fullName = assembly.FullName; if (fullName != null && fullName.IndexOf(',') >= 0 && !fullName.StartsWith("System.", StringComparison.Ordinal) && !fullName.StartsWith("Microsoft.", StringComparison.Ordinal)) { return fullName.Substring(0, fullName.IndexOf(',')); } } return string.Empty; } [UnconditionalSuppressMessage("Trimming - Allow callsite logic", "IL2026")] public static MethodBase? GetStackMethod(StackFrame? stackFrame) { return stackFrame?.GetMethod(); } public static string GetClassFullName(StackFrame? stackFrame) { string text = LookupClassNameFromStackFrame(stackFrame); if (string.IsNullOrEmpty(text)) { text = GetClassFullName(new StackTrace(fNeedFileInfo: false)); if (string.IsNullOrEmpty(text)) { text = GetStackMethod(stackFrame)?.Name ?? string.Empty; } } return text; } private static string GetClassFullName(StackTrace stackTrace) { StackFrame[] frames = stackTrace.GetFrames(); for (int i = 0; i < frames.Length; i++) { string text = LookupClassNameFromStackFrame(frames[i]); if (!string.IsNullOrEmpty(text)) { return text; } } return string.Empty; } public static Assembly? LookupAssemblyFromMethod(MethodBase method) { Assembly assembly = method.DeclaringType?.Assembly ?? method.Module?.Assembly; if (assembly == nlogAssembly) { return null; } if (assembly == mscorlibAssembly) { return null; } if (assembly == systemAssembly) { return null; } return assembly; } public static string LookupClassNameFromStackFrame(StackFrame? stackFrame) { MethodBase stackMethod = GetStackMethod(stackFrame); if (stackMethod != null && LookupAssemblyFromMethod(stackMethod) != null) { string stackFrameMethodClassName = GetStackFrameMethodClassName(stackMethod, includeNameSpace: true, cleanAsyncMoveNext: true, cleanAnonymousDelegates: true); if (!string.IsNullOrEmpty(stackFrameMethodClassName)) { if (!stackFrameMethodClassName.StartsWith("System.", StringComparison.Ordinal)) { return stackFrameMethodClassName; } } else { stackFrameMethodClassName = stackMethod.Name ?? string.Empty; if (stackFrameMethodClassName != "lambda_method" && stackFrameMethodClassName != "MoveNext") { return stackFrameMethodClassName; } } } return string.Empty; } } internal static class StringBuilderExt { private static readonly char[] charToInt = new char[10] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; internal const int Iso8601_MaxDigitCount = 7; private static readonly string[] _zeroPaddedDigits = (from i in Enumerable.Range(0, 60) select i.ToString("D2", CultureInfo.InvariantCulture)).ToArray(); public static void AppendFormattedValue(this StringBuilder builder, object? value, string? format, IFormatProvider? formatProvider, IValueFormatter valueFormatter) { if (value is string value2 && string.IsNullOrEmpty(format)) { builder.Append(value2); } else if ("@".Equals(format)) { valueFormatter.FormatValue(value, null, CaptureType.Serialize, formatProvider, builder); } else if (value != null) { valueFormatter.FormatValue(value, format, CaptureType.Normal, formatProvider, builder); } } public static void AppendInvariant(this StringBuilder builder, int value) { builder.Append(value); } public static void AppendInvariant(this StringBuilder builder, uint value) { builder.Append(value); } private static int CalculateDigitCount(uint value) { int num = 0; uint num2 = value; do { num2 /= 10; num++; } while (num2 != 0); return num; } private static void ApppendValueWithDigitCount(StringBuilder builder, uint value, int digitCount) { builder.Append('0', digitCount); int num = builder.Length; while (digitCount > 0) { num--; builder[num] = charToInt[value % 10]; value /= 10; digitCount--; } } public static void AppendXmlDateTimeUtcRoundTripFixed(this StringBuilder builder, DateTime dateTime) { int fraction = (int)(dateTime.Ticks % 10000000); builder.AppendXmlDateTimeUtcRoundTrip(dateTime, fraction, 7); } public static void AppendXmlDateTimeUtcRoundTrip(this StringBuilder builder, DateTime dateTime) { int num = 7; int num2 = (int)(dateTime.Ticks % 10000000); if (num2 > 0) { while (num2 % 10 == 0) { num--; num2 /= 10; } } builder.AppendXmlDateTimeUtcRoundTrip(dateTime, num2, num); } private static void AppendXmlDateTimeUtcRoundTrip(this StringBuilder builder, DateTime dateTime, int fraction, int max_digit_count) { dateTime = ((dateTime.Kind != 0) ? dateTime.ToUniversalTime() : new DateTime(dateTime.Ticks, DateTimeKind.Utc)); builder.Append4DigitsZeroPadded(dateTime.Year); builder.Append('-'); builder.Append2DigitsZeroPadded(dateTime.Month); builder.Append('-'); builder.Append2DigitsZeroPadded(dateTime.Day); builder.Append('T'); builder.Append2DigitsZeroPadded(dateTime.Hour); builder.Append(':'); builder.Append2DigitsZeroPadded(dateTime.Minute); builder.Append(':'); builder.Append2DigitsZeroPadded(dateTime.Second); if (fraction > 0) { builder.Append('.'); int num = CalculateDigitCount((uint)fraction); if (max_digit_count > num) { builder.Append('0', max_digit_count - num); } ApppendValueWithDigitCount(builder, (uint)fraction, num); } builder.Append('Z'); } public static void ClearBuilder(this StringBuilder builder) { try { builder.Clear(); } catch { if (builder.Length > 1) { builder.Remove(0, builder.Length - 1); } builder.Remove(0, builder.Length); } } public static void CopyToStream(this StringBuilder builder, MemoryStream ms, Encoding encoding, char[] transformBuffer) { int maxByteCount = encoding.GetMaxByteCount(builder.Length); long num = ms.Position; ms.SetLength(num + maxByteCount); for (int i = 0; i < builder.Length; i += transformBuffer.Length) { int num2 = Math.Min(builder.Length - i, transformBuffer.Length); builder.CopyTo(i, transformBuffer, 0, num2); maxByteCount = encoding.GetBytes(transformBuffer, 0, num2, ms.GetBuffer(), (int)num); num += maxByteCount; } ms.Position = num; if (num != ms.Length) { ms.SetLength(num); } } public static void CopyToBuffer(this StringBuilder builder, char[] destination, int destinationIndex) { builder.CopyTo(0, destination, destinationIndex, builder.Length); } public static void CopyTo(this StringBuilder builder, StringBuilder destination) { int length = builder.Length; if (length <= 0) { return; } destination.EnsureCapacity(length + destination.Length); if (length < 8) { for (int i = 0; i < length; i++) { destination.Append(builder[i]); } return; } if (length < 512) { destination.Append(builder.ToString()); return; } char[] array = new char[256]; for (int j = 0; j < length; j += array.Length) { int num = Math.Min(length - j, array.Length); builder.CopyTo(j, array, 0, num); destination.Append(array, 0, num); } } public static int IndexOf(this StringBuilder builder, char needle, int startPos = 0) { int length = builder.Length; for (int i = startPos; i < length; i++) { if (builder[i] == needle) { return i; } } return -1; } public static int IndexOfAny(this StringBuilder builder, char[] needles, int startPos = 0) { int length = builder.Length; for (int i = startPos; i < length; i++) { if (CharArrayContains(builder[i], needles)) { return i; } } return -1; } private static bool CharArrayContains(char searchChar, char[] needles) { for (int i = 0; i < needles.Length; i++) { if (needles[i] == searchChar) { return true; } } return false; } public static bool EqualTo(this StringBuilder builder, StringBuilder other) { int length = builder.Length; if (length != other.Length) { return false; } for (int i = 0; i < length; i++) { if (builder[i] != other[i]) { return false; } } return true; } public static bool EqualTo(this StringBuilder builder, string other) { if (builder.Length != other.Length) { return false; } int num = 0; foreach (char c in other) { if (builder[num++] != c) { return false; } } return true; } internal static void Append2DigitsZeroPadded(this StringBuilder builder, int number) { if (number < 0 || number >= _zeroPaddedDigits.Length) { builder.Append((char)(number / 10 + 48)); builder.Append((char)(number % 10 + 48)); } else { builder.Append(_zeroPaddedDigits[number]); } } internal static void Append4DigitsZeroPadded(this StringBuilder builder, int number) { if (999 < number && number < 10000) { builder.Append(number); return; } builder.Append(new ReadOnlySpan(new char[4] { (char)(number / 1000 % 10 + 48), (char)(number / 100 % 10 + 48), (char)(number / 10 % 10 + 48), (char)(number % 10 + 48) })); } internal static void AppendNumericInvariant(this StringBuilder sb, IConvertible value, TypeCode objTypeCode) { switch (objTypeCode) { case TypeCode.Byte: sb.AppendInvariant(value.ToByte(CultureInfo.InvariantCulture)); break; case TypeCode.SByte: sb.AppendInvariant(value.ToSByte(CultureInfo.InvariantCulture)); break; case TypeCode.Int16: sb.AppendInvariant(value.ToInt16(CultureInfo.InvariantCulture)); break; case TypeCode.Int32: sb.AppendInvariant(value.ToInt32(CultureInfo.InvariantCulture)); break; case TypeCode.Int64: { long value2 = value.ToInt64(CultureInfo.InvariantCulture); sb.Append(value2); break; } case TypeCode.UInt16: sb.AppendInvariant(value.ToUInt16(CultureInfo.InvariantCulture)); break; case TypeCode.UInt32: sb.AppendInvariant(value.ToUInt32(CultureInfo.InvariantCulture)); break; case TypeCode.UInt64: { ulong value3 = value.ToUInt64(CultureInfo.InvariantCulture); sb.Append(value3); break; } case TypeCode.Single: { float num2 = value.ToSingle(CultureInfo.InvariantCulture); if (!float.IsNaN(num2) && !float.IsInfinity(num2) && value is IFormattable formattable3) { AppendDecimalInvariant(sb, formattable3, "{0:R}"); } else { AppendFloatInvariant(sb, num2); } break; } case TypeCode.Double: { double num = value.ToDouble(CultureInfo.InvariantCulture); if (!double.IsNaN(num) && !double.IsInfinity(num) && value is IFormattable formattable2) { AppendDecimalInvariant(sb, formattable2, "{0:R}"); } else { AppendDoubleInvariant(sb, num); } break; } case TypeCode.Decimal: if (value is IFormattable formattable) { AppendDecimalInvariant(sb, formattable, "{0}"); } else { AppendDecimalInvariant(sb, value.ToDecimal(CultureInfo.InvariantCulture)); } break; default: sb.Append(XmlHelper.XmlConvertToString(value, objTypeCode)); break; } } private static void AppendDecimalInvariant(StringBuilder sb, IFormattable formattable, string format) { int length = sb.Length; sb.AppendFormat(CultureInfo.InvariantCulture, format, formattable); for (int num = sb.Length - 1; num > length; num--) { if (!char.IsDigit(sb[num])) { return; } } sb.Append('.'); sb.Append('0'); } private static void AppendDecimalInvariant(StringBuilder sb, decimal decimalValue) { if (Math.Truncate(decimalValue) == decimalValue && decimalValue > -2147483648m && decimalValue < 2147483647m) { sb.AppendInvariant(Convert.ToInt32(decimalValue)); sb.Append(".0"); } else { sb.Append(XmlHelper.XmlConvertToString(decimalValue)); } } private static void AppendDoubleInvariant(StringBuilder sb, double doubleValue) { if (double.IsNaN(doubleValue) || double.IsInfinity(doubleValue)) { sb.Append(XmlHelper.XmlConvertToString(doubleValue)); } else if (Math.Truncate(doubleValue) == doubleValue && doubleValue > -2147483648.0 && doubleValue < 2147483647.0) { sb.AppendInvariant(Convert.ToInt32(doubleValue)); sb.Append(".0"); } else { sb.Append(XmlHelper.XmlConvertToString(doubleValue)); } } private static void AppendFloatInvariant(StringBuilder sb, float floatValue) { if (float.IsNaN(floatValue) || float.IsInfinity(floatValue)) { sb.Append(XmlHelper.XmlConvertToString(floatValue)); } else if (Math.Truncate(floatValue) == (double)floatValue && floatValue > -2.1474836E+09f && floatValue < 2.1474836E+09f) { sb.AppendInvariant(Convert.ToInt32(floatValue)); sb.Append(".0"); } else { sb.Append(XmlHelper.XmlConvertToString(floatValue)); } } public static void TrimRight(this StringBuilder sb, int startPos = 0) { int num = sb.Length - 1; while (num >= startPos && char.IsWhiteSpace(sb[num])) { num--; } if (num < sb.Length - 1) { sb.Length = num + 1; } } } internal sealed class StringBuilderPool { public readonly struct ItemHolder : IDisposable { public readonly StringBuilder Item; private readonly StringBuilderPool? _owner; private readonly int _poolIndex; public ItemHolder(StringBuilder stringBuilder, StringBuilderPool? owner, int poolIndex) { Item = stringBuilder; _owner = owner; _poolIndex = poolIndex; } public void Dispose() { _owner?.Release(Item, _poolIndex); } } private StringBuilder? _fastPool; private readonly StringBuilder?[] _slowPool; private readonly int _maxBuilderCapacity; public StringBuilderPool(int poolCapacity, int initialBuilderCapacity = 1024, int maxBuilderCapacity = 40960) { _fastPool = new StringBuilder(10 * initialBuilderCapacity); _slowPool = new StringBuilder[poolCapacity]; for (int i = 0; i < _slowPool.Length; i++) { _slowPool[i] = new StringBuilder(initialBuilderCapacity); } _maxBuilderCapacity = maxBuilderCapacity; } public ItemHolder Acquire() { StringBuilder fastPool = _fastPool; if (fastPool == null || fastPool != Interlocked.CompareExchange(ref _fastPool, null, fastPool)) { for (int i = 0; i < _slowPool.Length; i++) { fastPool = _slowPool[i]; if (fastPool != null && fastPool == Interlocked.CompareExchange(ref _slowPool[i], null, fastPool)) { return new ItemHolder(fastPool, this, i); } } return new ItemHolder(new StringBuilder(), null, 0); } return new ItemHolder(fastPool, this, -1); } private void Release(StringBuilder stringBuilder, int poolIndex) { if (stringBuilder.Length > _maxBuilderCapacity) { int num = ((poolIndex == -1) ? (_maxBuilderCapacity * 10) : _maxBuilderCapacity); if (stringBuilder.Length > num) { stringBuilder.Remove(0, stringBuilder.Length - 1); if (stringBuilder.Capacity > num) { stringBuilder.Capacity = _maxBuilderCapacity; } } } stringBuilder.ClearBuilder(); if (poolIndex == -1) { _fastPool = stringBuilder; } else { _slowPool[poolIndex] = stringBuilder; } } } internal static class StringHelpers { [ContractAnnotation("value:null => true")] internal static bool IsNullOrWhiteSpace(string? value) { return string.IsNullOrWhiteSpace(value); } internal static string[] SplitAndTrimTokens(this string value, char delimiter) { if (IsNullOrWhiteSpace(value)) { return ArrayHelper.Empty(); } if (value.IndexOf(delimiter) == -1) { return new string[1] { value.Trim() }; } string[] array = value.Split(new char[1] { delimiter }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { array[i] = array[i].Trim(); if (string.IsNullOrEmpty(array[i])) { return (from s in array where !IsNullOrWhiteSpace(s) select s.Trim()).ToArray(); } } return array; } public static string Replace(string str, string oldValue, string newValue, StringComparison comparison, bool wholeWords = false) { Guard.ThrowIfNull(str, "str"); if (string.IsNullOrEmpty(str)) { return string.Empty; } Guard.ThrowIfNullOrEmpty(oldValue, "oldValue"); StringBuilder stringBuilder = null; int num = 0; int num2; for (num2 = str.IndexOf(oldValue, comparison); num2 != -1; num2 = str.IndexOf(oldValue, num2, comparison)) { if (!wholeWords || IsWholeWord(str, oldValue, num2)) { stringBuilder = stringBuilder ?? new StringBuilder(str.Length); if (num >= str.Length) { break; } stringBuilder.Append(str, num, num2 - num); stringBuilder.Append(newValue); num2 += oldValue.Length; num = num2; if (num2 >= str.Length) { break; } } else { num2 += oldValue.Length; } } if (stringBuilder == null) { return str; } if (num < str.Length) { stringBuilder.Append(str, num, str.Length - num); } return stringBuilder.ToString(); } public static bool IsWholeWord(string str, string token, int index) { if (index + token.Length != str.Length) { if (!char.IsLetterOrDigit(str[index + token.Length])) { if (index != 0) { return !char.IsLetterOrDigit(str[index - 1]); } return true; } return false; } return true; } internal static string Join(string separator, IEnumerable values) { return string.Join(separator, values); } internal static bool IsNullOrEmptyString(object? objectValue) { if (objectValue != null && string.Empty != objectValue) { if (objectValue is string text) { return text.Length == 0; } return false; } return true; } } internal static class StringSplitter { [CompilerGenerated] private sealed class d__1 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private string <>2__current; private int <>l__initialThreadId; private char escapeChar; public char <>3__escapeChar; private char quoteChar; public char <>3__quoteChar; private string text; public string <>3__text; private char splitChar; public char <>3__splitChar; private bool 5__2; private bool 5__3; private StringBuilder 5__4; private string <>7__wrap4; private int <>7__wrap5; string IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__1(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { 5__4 = null; <>7__wrap4 = null; <>1__state = -2; } private bool MoveNext() { bool flag; bool flag2; switch (<>1__state) { default: return false; case 0: <>1__state = -1; 5__2 = false; flag = false; flag2 = false; 5__3 = escapeChar == quoteChar; 5__4 = new StringBuilder(); <>7__wrap4 = text; <>7__wrap5 = 0; goto IL_024f; case 1: <>1__state = -1; 5__4.Length = 0; flag = false; flag2 = true; goto IL_0241; case 2: <>1__state = -1; 5__4.Length = 0; goto IL_0215; case 3: { <>1__state = -1; break; } IL_024f: if (<>7__wrap5 < <>7__wrap4.Length) { char c = <>7__wrap4[<>7__wrap5]; if (c == quoteChar) { if (5__2) { if (flag && !5__3) { 5__4.Append(c); flag = false; flag2 = false; } else if (flag2 & 5__3) { 5__4.Append(c); 5__2 = false; flag = false; flag2 = false; } else { if (5__4.Length > 0) { 5__2 = false; <>2__current = 5__4.ToString(); <>1__state = 1; return true; } 5__2 = false; flag = false; flag2 = false; } } else if (5__4.Length != 0 || flag) { 5__4.Append(c); flag = false; flag2 = false; } else { flag = c == escapeChar; flag2 = true; 5__2 = true; } } else if (c == escapeChar) { if (flag) { 5__4.Append(escapeChar); } flag = true; flag2 = false; } else if (5__2) { 5__4.Append(c); flag = false; flag2 = false; } else { if (c == splitChar) { if (flag) { 5__4.Append(escapeChar); } if (5__4.Length > 0 || !flag2) { <>2__current = 5__4.ToString(); <>1__state = 2; return true; } goto IL_0215; } if (flag) { 5__4.Append(escapeChar); } 5__4.Append(c); flag = false; flag2 = false; } goto IL_0241; } <>7__wrap4 = null; if (flag && !5__3) { 5__4.Append(escapeChar); } if (5__2) { if (flag2) { 5__4.Append(quoteChar); } else { 5__4.Insert(0, quoteChar); } } if (5__4.Length > 0 || !flag2) { <>2__current = 5__4.ToString(); <>1__state = 3; return true; } break; IL_0241: <>7__wrap5++; goto IL_024f; IL_0215: flag = false; flag2 = false; goto IL_0241; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { d__1 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__1(0); } d__.text = <>3__text; d__.splitChar = <>3__splitChar; d__.quoteChar = <>3__quoteChar; d__.escapeChar = <>3__escapeChar; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } public static IEnumerable SplitQuoted(this string text, char splitChar, char quoteChar, char escapeChar) { if (!string.IsNullOrEmpty(text)) { if (splitChar == quoteChar) { throw new NotSupportedException("Quote character should different from split character"); } if (splitChar == escapeChar) { throw new NotSupportedException("Escape character should different from split character"); } return SplitQuoted2(text, splitChar, quoteChar, escapeChar); } return ArrayHelper.Empty(); } [IteratorStateMachine(typeof(d__1))] private static IEnumerable SplitQuoted2(string text, char splitChar, char quoteChar, char escapeChar) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__1(-2) { <>3__text = text, <>3__splitChar = splitChar, <>3__quoteChar = quoteChar, <>3__escapeChar = escapeChar }; } } internal sealed class TargetWithFilterChain : ITargetWithFilterChain { private readonly struct CallSiteKey : IEquatable { public readonly string MethodName; public readonly string FileSourceName; public readonly int FileSourceLineNumber; public CallSiteKey(string? methodName, string? fileSourceName, int fileSourceLineNumber) { MethodName = methodName ?? string.Empty; FileSourceName = fileSourceName ?? string.Empty; FileSourceLineNumber = fileSourceLineNumber; } public override int GetHashCode() { return MethodName.GetHashCode() ^ FileSourceName.GetHashCode() ^ FileSourceLineNumber; } public override bool Equals(object? obj) { if (obj is CallSiteKey other) { return Equals(other); } return false; } public bool Equals(CallSiteKey other) { if (FileSourceLineNumber == other.FileSourceLineNumber && string.Equals(FileSourceName, other.FileSourceName, StringComparison.Ordinal)) { return string.Equals(MethodName, other.MethodName, StringComparison.Ordinal); } return false; } } internal static readonly TargetWithFilterChain[] NoTargetsByLevel = CreateLoggerConfiguration(); private MruCache? _callSiteClassNameCache; public Target Target { get; } public IList FilterChain { get; } public TargetWithFilterChain? NextInChain { get; set; } public StackTraceUsage StackTraceUsage { get; private set; } public FilterResult FilterDefaultAction { get; } private static TargetWithFilterChain[] CreateLoggerConfiguration() { return new TargetWithFilterChain[LogLevel.MaxLevel.Ordinal + 2]; } public TargetWithFilterChain(Target target, IList filterChain, FilterResult filterDefaultAction) { Target = target; FilterChain = filterChain; FilterDefaultAction = filterDefaultAction; } internal StackTraceUsage PrecalculateStackTraceUsage() { StackTraceUsage stackTraceUsage = StackTraceUsage.None; if (Target != null) { stackTraceUsage = Target.StackTraceUsage; } if (NextInChain != null && (stackTraceUsage & StackTraceUsage.WithSource) != StackTraceUsage.WithSource) { StackTraceUsage stackTraceUsage2 = NextInChain.PrecalculateStackTraceUsage(); stackTraceUsage |= stackTraceUsage2; } StackTraceUsage = stackTraceUsage; return stackTraceUsage; } internal static TargetWithFilterChain[] BuildLoggerConfiguration(string loggerName, LoggingRule[] loggingRules, LogLevel globalLogLevel) { TargetWithFilterChain[] array = CreateLoggerConfiguration(); TargetWithFilterChain[] lastTargetsByLevel = CreateLoggerConfiguration(); bool[] suppressedLevels = new bool[LogLevel.MaxLevel.Ordinal + 1]; if (!GetTargetsByLevelForLogger(loggerName, loggingRules, globalLogLevel, array, lastTargetsByLevel, suppressedLevels)) { return NoTargetsByLevel; } return array; } private static bool GetTargetsByLevelForLogger(string name, LoggingRule[] loggingRules, LogLevel globalLogLevel, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels) { IList>> finalMinLevelWithFilters = null; bool flag = false; foreach (LoggingRule loggingRule in loggingRules) { if (loggingRule.NameMatches(name)) { if (LoggingRuleHasFinalMinLevelFilters(loggingRule)) { CollectFinalMinLevelFiltersFromRule(loggingRule, ref finalMinLevelWithFilters); } flag = AddTargetsFromLoggingRule(loggingRule, name, globalLogLevel, targetsByLevel, lastTargetsByLevel, suppressedLevels) || flag; if (loggingRule.ChildRules.Count != 0) { flag = GetTargetsByLevelForLogger(name, loggingRule.GetChildRulesThreadSafe(), globalLogLevel, targetsByLevel, lastTargetsByLevel, suppressedLevels) || flag; } } } for (int j = 0; j <= LogLevel.MaxLevel.Ordinal; j++) { TargetWithFilterChain targetWithFilterChain = targetsByLevel[j]; if (targetWithFilterChain == null) { continue; } if (finalMinLevelWithFilters != null && finalMinLevelWithFilters.Count > 0) { KeyValuePair> keyValuePair = finalMinLevelWithFilters[j]; IList value = keyValuePair.Value; if (value != null && value.Count > 0 && keyValuePair.Key.HasValue) { targetWithFilterChain = (targetsByLevel[j] = AppendFinalMinLevelFilters(targetWithFilterChain, keyValuePair.Value, keyValuePair.Key.Value)); } } targetWithFilterChain.PrecalculateStackTraceUsage(); } return flag; } private static bool LoggingRuleHasFinalMinLevelFilters(LoggingRule rule) { if (rule.FinalMinLevel != LogLevel.Off && rule.Filters.Count != 0) { return rule.Targets.Count == 0; } return false; } private static void CollectFinalMinLevelFiltersFromRule(LoggingRule rule, ref IList>>? finalMinLevelWithFilters) { LogLevel finalMinLevel = rule.FinalMinLevel; if ((object)finalMinLevel == null) { return; } finalMinLevelWithFilters = finalMinLevelWithFilters ?? new KeyValuePair>[LogLevel.MaxLevel.Ordinal + 1]; for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; i++) { if (i < finalMinLevel.Ordinal) { continue; } FilterResult filterResult = finalMinLevelWithFilters[i].Key ?? rule.FilterDefaultAction; if (filterResult == rule.FilterDefaultAction) { IList value = finalMinLevelWithFilters[i].Value; IList list; if (value == null || value.Count <= 0) { list = rule.Filters; } else { IList list2 = finalMinLevelWithFilters[i].Value.Concat(rule.Filters).ToArray(); list = list2; } IList value2 = list; finalMinLevelWithFilters[i] = new KeyValuePair>(filterResult, value2); } } } private static TargetWithFilterChain AppendFinalMinLevelFilters(TargetWithFilterChain targetsByLevel, IList finalMinLevelFilters, FilterResult finalMinLevelDefaultResult) { IList filterChain = targetsByLevel.FilterChain; if (filterChain != null && filterChain.Count > 0 && targetsByLevel.FilterDefaultAction != finalMinLevelDefaultResult) { return targetsByLevel; } IList filterChain2 = targetsByLevel.FilterChain; IList list; if (filterChain2 == null || filterChain2.Count <= 0) { list = finalMinLevelFilters; } else { IList list2 = finalMinLevelFilters.Concat(targetsByLevel.FilterChain).ToArray(); list = list2; } IList filterChain3 = list; TargetWithFilterChain targetWithFilterChain = new TargetWithFilterChain(targetsByLevel.Target, filterChain3, finalMinLevelDefaultResult); TargetWithFilterChain targetWithFilterChain2 = ((targetsByLevel.NextInChain == null) ? null : AppendFinalMinLevelFilters(targetsByLevel.NextInChain, finalMinLevelFilters, finalMinLevelDefaultResult)); targetWithFilterChain.NextInChain = targetWithFilterChain2 ?? targetsByLevel.NextInChain; return targetWithFilterChain; } private static bool AddTargetsFromLoggingRule(LoggingRule rule, string loggerName, LogLevel globalLogLevel, TargetWithFilterChain[] targetsByLevel, TargetWithFilterChain[] lastTargetsByLevel, bool[] suppressedLevels) { bool result = false; bool flag = false; LogLevel finalMinLevel = rule.FinalMinLevel; bool[] logLevels = rule.LogLevels; for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; i++) { if (SuppressLogLevel(rule, logLevels, finalMinLevel, globalLogLevel, i, ref suppressedLevels[i])) { continue; } Target[] targetsThreadSafe = rule.GetTargetsThreadSafe(); foreach (Target target in targetsThreadSafe) { result = true; TargetWithFilterChain targetWithFilterChain = CreateTargetChainFromLoggingRule(rule, target, targetsByLevel[i]); if (targetWithFilterChain == null) { if (!flag) { InternalLogger.Warn("Logger: {0} configured with duplicate output to target: {1}. LoggingRule with NamePattern='{2}' and Level={3} has been skipped.", new ReadOnlySpan(new object[4] { loggerName, target, rule.LoggerNamePattern, LogLevel.FromOrdinal(i) })); } flag = true; } else { if (lastTargetsByLevel[i] != null) { lastTargetsByLevel[i].NextInChain = targetWithFilterChain; } else { targetsByLevel[i] = targetWithFilterChain; } lastTargetsByLevel[i] = targetWithFilterChain; } } } return result; } private static bool SuppressLogLevel(LoggingRule rule, bool[] ruleLogLevels, LogLevel? finalMinLevel, LogLevel globalLogLevel, int logLevelOrdinal, ref bool suppressedLevels) { if (logLevelOrdinal < globalLogLevel.Ordinal) { return true; } if ((object)finalMinLevel == null) { if (suppressedLevels) { return true; } } else { suppressedLevels = finalMinLevel.Ordinal > logLevelOrdinal; } if (!ruleLogLevels[logLevelOrdinal]) { return true; } if (rule.Final) { suppressedLevels = true; } return false; } private static TargetWithFilterChain? CreateTargetChainFromLoggingRule(LoggingRule rule, Target target, TargetWithFilterChain existingTargets) { IList list; if (rule.Filters.Count != 0) { list = rule.Filters; } else { IList list2 = ArrayHelper.Empty(); list = list2; } IList filterChain = list; TargetWithFilterChain targetWithFilterChain = new TargetWithFilterChain(target, filterChain, rule.FilterDefaultAction); if (existingTargets != null && targetWithFilterChain.FilterChain.Count == 0) { for (TargetWithFilterChain targetWithFilterChain2 = existingTargets; targetWithFilterChain2 != null; targetWithFilterChain2 = targetWithFilterChain2.NextInChain) { if (target == targetWithFilterChain2.Target && targetWithFilterChain2.FilterChain.Count == 0) { return null; } } } return targetWithFilterChain; } internal bool TryRememberCallSiteClassName(LogEventInfo logEvent) { if (string.IsNullOrEmpty(logEvent.CallSiteInformation?.CallerFilePath)) { return false; } string text = logEvent.CallSiteInformation?.GetCallerClassName(null, includeNameSpace: true, cleanAsyncMoveNext: true, cleanAnonymousDelegates: true); if (string.IsNullOrEmpty(text)) { return false; } if (_callSiteClassNameCache == null) { return false; } string value = ((logEvent.LoggerName == text) ? logEvent.LoggerName : string.Intern(text)); CallSiteKey key = new CallSiteKey(logEvent.CallerMemberName, logEvent.CallerFilePath, logEvent.CallerLineNumber); return _callSiteClassNameCache.TryAddValue(key, value); } internal bool TryLookupCallSiteClassName(LogEventInfo logEvent, out string? callSiteClassName) { callSiteClassName = logEvent.CallSiteInformation?.CallerClassName; if (!string.IsNullOrEmpty(callSiteClassName)) { return true; } if (_callSiteClassNameCache == null) { Interlocked.CompareExchange(ref _callSiteClassNameCache, new MruCache(1000), null); } CallSiteKey key = new CallSiteKey(logEvent.CallerMemberName, logEvent.CallerFilePath, logEvent.CallerLineNumber); return _callSiteClassNameCache.TryGetValue(key, out callSiteClassName); } public void WriteToLoggerTargets(Type loggerType, LogEventInfo logEvent, LogFactory logFactory) { LoggerImpl.Write(loggerType, this, logEvent, logFactory); } } [DebuggerDisplay("Count = {Count}")] internal class ThreadSafeDictionary : IDictionary, ICollection>, IEnumerable>, IEnumerable where TKey : notnull { public struct Enumerator : IEnumerator>, IEnumerator, IDisposable { private Dictionary.Enumerator _enumerator; public KeyValuePair Current => _enumerator.Current; object IEnumerator.Current => _enumerator.Current; public Enumerator(Dictionary.Enumerator enumerator) { _enumerator = enumerator; } public void Dispose() { _enumerator.Dispose(); } public bool MoveNext() { return _enumerator.MoveNext(); } void IEnumerator.Reset() { ((IEnumerator)_enumerator).Reset(); } } private readonly object _lockObject = new object(); private Dictionary _dict; private Dictionary? _dictReadOnly; public TValue this[TKey key] { get { return GetReadOnlyDict()[key]; } set { lock (_lockObject) { GetWritableDict()[key] = value; } } } public IEqualityComparer Comparer => _dict.Comparer; public ICollection Keys => GetReadOnlyDict().Keys; public ICollection Values => GetReadOnlyDict().Values; public int Count => GetReadOnlyDict().Count; public bool IsReadOnly => false; public ThreadSafeDictionary() : this((IEqualityComparer)EqualityComparer.Default) { } public ThreadSafeDictionary(IEqualityComparer comparer) { _dict = new Dictionary(comparer); } public ThreadSafeDictionary(ThreadSafeDictionary source) { Dictionary readOnlyDict = source.GetReadOnlyDict(); _dict = new Dictionary(readOnlyDict.Count, readOnlyDict.Comparer); foreach (KeyValuePair item in readOnlyDict) { _dict.Add(item.Key, item.Value); } } public void Add(TKey key, TValue value) { lock (_lockObject) { GetWritableDict().Add(key, value); } } public void Add(KeyValuePair item) { lock (_lockObject) { GetWritableDict().Add(item.Key, item.Value); } } public void Clear() { lock (_lockObject) { GetWritableDict(clearDictionary: true); } } public bool Contains(KeyValuePair item) { return GetReadOnlyDict().Contains(item); } public bool ContainsKey(TKey key) { return GetReadOnlyDict().ContainsKey(key); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { ((ICollection>)GetReadOnlyDict()).CopyTo(array, arrayIndex); } public void CopyFrom(IDictionary source) { if (this == source || source == null || source.Count <= 0) { return; } lock (_lockObject) { IDictionary writableDict = GetWritableDict(); foreach (KeyValuePair item in source) { writableDict[item.Key] = item.Value; } } } public bool Remove(TKey key) { lock (_lockObject) { return GetWritableDict().Remove(key); } } public bool Remove(KeyValuePair item) { lock (_lockObject) { return GetWritableDict().Remove(item); } } public bool TryGetValue(TKey key, out TValue value) { return GetReadOnlyDict().TryGetValue(key, out value); } IEnumerator> IEnumerable>.GetEnumerator() { return GetReadOnlyDict().GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetReadOnlyDict().GetEnumerator(); } public Enumerator GetEnumerator() { return new Enumerator(GetReadOnlyDict().GetEnumerator()); } private Dictionary GetReadOnlyDict() { Dictionary dictionary = _dictReadOnly; if (dictionary == null) { lock (_lockObject) { dictionary = (_dictReadOnly = _dict); } } return dictionary; } private IDictionary GetWritableDict(bool clearDictionary = false) { if (_dictReadOnly == null) { if (clearDictionary) { _dict.Clear(); } return _dict; } Dictionary dictionary = new Dictionary((!clearDictionary) ? (_dict.Count + 1) : 0, _dict.Comparer); if (!clearDictionary) { foreach (KeyValuePair item in _dict) { dictionary[item.Key] = item.Value; } } _dict = dictionary; _dictReadOnly = null; return dictionary; } } [Obsolete("Marked obsolete on NLog 6.0")] internal sealed class TimeoutContinuation : IDisposable { private AsyncContinuation? _asyncContinuation; private Timer? _timeoutTimer; public TimeoutContinuation(AsyncContinuation asyncContinuation, TimeSpan timeout) { _asyncContinuation = asyncContinuation; _timeoutTimer = new Timer(TimerElapsed, null, (int)timeout.TotalMilliseconds, -1); } public void Function(Exception? exception) { try { AsyncContinuation? asyncContinuation = Interlocked.Exchange(ref _asyncContinuation, null); StopTimer(); asyncContinuation?.Invoke(exception); } catch (Exception ex) { InternalLogger.Error(ex, "Exception in asynchronous handler."); if (ex.MustBeRethrown()) { throw; } } } public void Dispose() { StopTimer(); } private void StopTimer() { Interlocked.Exchange(ref _timeoutTimer, null)?.WaitForDispose(TimeSpan.Zero); } private void TimerElapsed(object? state) { Function(new TimeoutException("Timeout.")); } } internal static class UrlHelper { [Flags] public enum EscapeEncodingOptions { None = 0, UriString = 1, LegacyRfc2396 = 2, LowerCaseHex = 4, SpaceAsPlus = 8, [Obsolete("Instead use default Rfc2396 or Rfc3986. Marked obsolete with NLog v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] NLogLegacy = 0x17 } private const string RFC2396ReservedMarks = ";/?:@&=+$,"; private const string RFC3986ReservedMarks = ":/?#[]@!$&'()*+,;="; private const string RFC2396UnreservedMarks = "-_.!~*'()"; private const string RFC3986UnreservedMarks = "-._~"; private static readonly char[] hexUpperChars = new char[16] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static readonly char[] hexLowerChars = new char[16] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static void EscapeDataEncode(string source, StringBuilder target, EscapeEncodingOptions options) { if (string.IsNullOrEmpty(source)) { return; } bool num = Contains(options, EscapeEncodingOptions.LowerCaseHex); bool flag = Contains(options, EscapeEncodingOptions.SpaceAsPlus); bool flag2 = Contains(options, EscapeEncodingOptions.NLogLegacy); char[] array = null; byte[] array2 = null; char[] hexChars = (num ? hexLowerChars : hexUpperChars); foreach (char c in source) { target.Append(c); if (IsSimpleCharOrNumber(c)) { continue; } if (flag && c == ' ') { target[target.Length - 1] = '+'; } else { if (IsAllowedChar(options, c)) { continue; } if (flag2) { HandleLegacyEncoding(target, c, hexChars); continue; } if (array == null) { array = new char[1]; } array[0] = c; if (array2 == null) { array2 = new byte[8]; } WriteWideChars(target, array, array2, hexChars); } } } private static bool Contains(EscapeEncodingOptions options, EscapeEncodingOptions option) { return (options & option) == option; } private static void WriteWideChars(StringBuilder target, char[] charArray, byte[] byteArray, char[] hexChars) { int bytes = Encoding.UTF8.GetBytes(charArray, 0, 1, byteArray, 0); for (int i = 0; i < bytes; i++) { byte b = byteArray[i]; if (i == 0) { target[target.Length - 1] = '%'; } else { target.Append('%'); } target.Append(hexChars[(b & 0xF0) >> 4]); target.Append(hexChars[b & 0xF]); } } [Obsolete("Instead use default Rfc2396 or Rfc3986. Marked obsolete with NLog v5.3")] private static void HandleLegacyEncoding(StringBuilder target, char ch, char[] hexChars) { if (ch < 'Ä€') { target[target.Length - 1] = '%'; target.Append(hexChars[((int)ch >> 4) & 0xF]); target.Append(hexChars[ch & 0xF]); return; } target[target.Length - 1] = '%'; target.Append('u'); target.Append(hexChars[((int)ch >> 12) & 0xF]); target.Append(hexChars[((int)ch >> 8) & 0xF]); target.Append(hexChars[((int)ch >> 4) & 0xF]); target.Append(hexChars[ch & 0xF]); } private static bool IsAllowedChar(EscapeEncodingOptions options, char ch) { bool num = (options & EscapeEncodingOptions.UriString) == EscapeEncodingOptions.UriString; bool flag = (options & EscapeEncodingOptions.LegacyRfc2396) == EscapeEncodingOptions.LegacyRfc2396; if (num) { if (!flag && "-._~".IndexOf(ch) >= 0) { return true; } if (flag && "-_.!~*'()".IndexOf(ch) >= 0) { return true; } } else { if (!flag && ":/?#[]@!$&'()*+,;=".IndexOf(ch) >= 0) { return true; } if (flag && ";/?:@&=+$,".IndexOf(ch) >= 0) { return true; } } return false; } private static bool IsSimpleCharOrNumber(char ch) { if (ch >= 'a' && ch <= 'z') { return true; } if (ch >= 'A' && ch <= 'Z') { return true; } if (ch >= '0' && ch <= '9') { return true; } return false; } public static EscapeEncodingOptions GetUriStringEncodingFlags(bool escapeDataNLogLegacy, bool spaceAsPlus, bool escapeDataRfc3986) { EscapeEncodingOptions escapeEncodingOptions = EscapeEncodingOptions.UriString; if (escapeDataNLogLegacy) { escapeEncodingOptions |= EscapeEncodingOptions.NLogLegacy; } else if (!escapeDataRfc3986) { escapeEncodingOptions |= EscapeEncodingOptions.LegacyRfc2396 | EscapeEncodingOptions.LowerCaseHex; } if (spaceAsPlus) { escapeEncodingOptions |= EscapeEncodingOptions.SpaceAsPlus; } return escapeEncodingOptions; } } internal static class XmlHelper { private const char HIGH_SURROGATE_START = '\ud800'; private const char HIGH_SURROGATE_END = '\udbff'; private const char LOW_SURROGATE_START = '\udc00'; private const char LOW_SURROGATE_END = '\udfff'; private static readonly char[] XmlEscapeChars = new char[5] { '<', '>', '&', '\'', '"' }; private static readonly char[] XmlEscapeNewlineChars = new char[7] { '<', '>', '&', '\'', '"', '\r', '\n' }; private static readonly char[] DecimalScientificExponent = new char[2] { 'e', 'E' }; internal static bool XmlConvertIsXmlChar(char chr) { if (chr <= '\u001f' || chr >= '\ud800') { return ExoticIsXmlChar(chr); } return true; } private static bool ExoticIsXmlChar(char chr) { if (chr < ' ') { if (chr != '\t' && chr != '\n') { return chr == '\r'; } return true; } if (XmlConvertIsHighSurrogate(chr) || XmlConvertIsLowSurrogate(chr)) { return false; } if (chr == '\ufffe' || chr == '\uffff') { return false; } return true; } public static bool XmlConvertIsHighSurrogate(char chr) { if (chr >= '\ud800') { return chr <= '\udbff'; } return false; } public static bool XmlConvertIsLowSurrogate(char chr) { if (chr >= '\udc00') { return chr <= '\udfff'; } return false; } public static bool XmlConvertIsXmlSurrogatePair(char lowChar, char highChar) { if (XmlConvertIsHighSurrogate(highChar)) { return XmlConvertIsLowSurrogate(lowChar); } return false; } private static string RemoveInvalidXmlChars(string text, StringBuilder? builder = null) { if (string.IsNullOrEmpty(text)) { return string.Empty; } int length = text.Length; for (int i = 0; i < length; i++) { char c = text[i]; if (!XmlConvertIsXmlChar(c)) { if (i + 1 >= text.Length || !XmlConvertIsXmlSurrogatePair(text[i + 1], c)) { return CreateValidXmlString(text, i, builder); } i++; } } builder?.Append(text); return text; } private static string CreateValidXmlString(string text, int startIndex = 0, StringBuilder? builder = null) { StringBuilder stringBuilder = builder ?? new StringBuilder(text.Length); stringBuilder.Append(text, 0, startIndex); for (int i = startIndex; i < text.Length; i++) { char c = text[i]; if (XmlConvertIsXmlChar(c)) { stringBuilder.Append(c); } else if (i + 1 < text.Length && XmlConvertIsXmlSurrogatePair(text[i + 1], c)) { stringBuilder.Append(c); stringBuilder.Append(text[++i]); } } if (builder != null) { return string.Empty; } return stringBuilder.ToString(); } internal static void EscapeXmlWhenNeeded(StringBuilder builder, int startPos, bool xmlEncodeNewlines) { int length = builder.Length; for (int i = startPos; i < length; i++) { char chr = builder[i]; if (!XmlConvertIsXmlChar(chr) || RequiresXmlEscape(chr, xmlEncodeNewlines)) { string text = builder.ToString(i, length - i); builder.Length = i; EscapeXmlString(text, xmlEncodeNewlines, builder); break; } } } internal static string EscapeXmlWhenNeeded(string text, bool xmlEncodeNewlines, StringBuilder? builder = null) { if (text.IndexOfAny(xmlEncodeNewlines ? XmlEscapeNewlineChars : XmlEscapeChars) >= 0) { StringBuilder stringBuilder = builder ?? new StringBuilder(text.Length + 16); EscapeXmlString(text, xmlEncodeNewlines, stringBuilder); if (builder != null) { return string.Empty; } return stringBuilder.ToString(); } return RemoveInvalidXmlChars(text, builder); } private static bool RequiresXmlEscape(char chr, bool xmlEncodeNewlines) { switch (chr) { case '"': case '&': case '\'': case '<': case '>': return true; case '\n': case '\r': return xmlEncodeNewlines; default: return false; } } private static void EscapeXmlString(string text, bool xmlEncodeNewlines, StringBuilder destination) { for (int i = 0; i < text.Length; i++) { char c = text[i]; switch (c) { case '<': destination.Append("<"); continue; case '>': destination.Append(">"); continue; case '&': destination.Append("&"); continue; case '\'': destination.Append("'"); continue; case '"': destination.Append("""); continue; case '\r': if (xmlEncodeNewlines) { destination.Append(" "); } else { destination.Append(c); } continue; case '\n': if (xmlEncodeNewlines) { destination.Append(" "); } else { destination.Append(c); } continue; } if (XmlConvertIsXmlChar(c)) { destination.Append(c); } else if (i + 1 < text.Length && XmlConvertIsXmlSurrogatePair(text[i + 1], c)) { destination.Append(c); destination.Append(text[++i]); } } } internal static string XmlConvertToStringSafe(object? value) { return XmlConvertToString(value, safeConversion: true); } internal static string XmlConvertToString(object? value) { if (!(value is string result)) { return XmlConvertToString(value, safeConversion: false); } return result; } internal static string XmlConvertToString(float value) { if (float.IsInfinity(value) || float.IsNaN(value)) { return Convert.ToString(value, CultureInfo.InvariantCulture); } return EnsureDecimalPlace(value.ToString("R", NumberFormatInfo.InvariantInfo)); } internal static string XmlConvertToString(double value) { if (double.IsInfinity(value) || double.IsNaN(value)) { return Convert.ToString(value, CultureInfo.InvariantCulture); } return EnsureDecimalPlace(value.ToString("R", NumberFormatInfo.InvariantInfo)); } internal static string XmlConvertToString(decimal value) { return EnsureDecimalPlace(value.ToString(null, NumberFormatInfo.InvariantInfo)); } internal static string XmlConvertToString(DateTime value) { value = ((value.Kind != 0) ? value.ToUniversalTime() : new DateTime(value.Ticks, DateTimeKind.Utc)); return value.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK", CultureInfo.InvariantCulture); } internal static string XmlConvertToString(IConvertible? value, TypeCode objTypeCode, bool safeConversion = false) { if (objTypeCode == TypeCode.Empty || value == null) { return "null"; } switch (objTypeCode) { case TypeCode.Boolean: if (!value.ToBoolean(CultureInfo.InvariantCulture)) { return "false"; } return "true"; case TypeCode.Byte: return value.ToByte(CultureInfo.InvariantCulture).ToString(null, NumberFormatInfo.InvariantInfo); case TypeCode.SByte: return value.ToSByte(CultureInfo.InvariantCulture).ToString(null, NumberFormatInfo.InvariantInfo); case TypeCode.Int16: return value.ToInt16(CultureInfo.InvariantCulture).ToString(null, NumberFormatInfo.InvariantInfo); case TypeCode.Int32: return value.ToInt32(CultureInfo.InvariantCulture).ToString(null, NumberFormatInfo.InvariantInfo); case TypeCode.Int64: return value.ToInt64(CultureInfo.InvariantCulture).ToString(null, NumberFormatInfo.InvariantInfo); case TypeCode.UInt16: return value.ToUInt16(CultureInfo.InvariantCulture).ToString(null, NumberFormatInfo.InvariantInfo); case TypeCode.UInt32: return value.ToUInt32(CultureInfo.InvariantCulture).ToString(null, NumberFormatInfo.InvariantInfo); case TypeCode.UInt64: return value.ToUInt64(CultureInfo.InvariantCulture).ToString(null, NumberFormatInfo.InvariantInfo); case TypeCode.Single: return XmlConvertToString(value.ToSingle(CultureInfo.InvariantCulture)); case TypeCode.Double: return XmlConvertToString(value.ToDouble(CultureInfo.InvariantCulture)); case TypeCode.Decimal: return XmlConvertToString(value.ToDecimal(CultureInfo.InvariantCulture)); case TypeCode.DateTime: return XmlConvertToString(value.ToDateTime(CultureInfo.InvariantCulture)); case TypeCode.Char: if (!safeConversion) { return value.ToString(CultureInfo.InvariantCulture); } return RemoveInvalidXmlChars(value.ToString(CultureInfo.InvariantCulture)); case TypeCode.String: if (!safeConversion) { return value.ToString(CultureInfo.InvariantCulture); } return RemoveInvalidXmlChars(value.ToString(CultureInfo.InvariantCulture)); default: return XmlConvertToStringInvariant(value, safeConversion); } } private static string XmlConvertToString(object? value, bool safeConversion) { try { IConvertible convertible = value as IConvertible; TypeCode typeCode = (TypeCode)(((int?)convertible?.GetTypeCode()) ?? ((value != null) ? 1 : 0)); if (typeCode != TypeCode.Object) { return XmlConvertToString(convertible, typeCode, safeConversion); } return XmlConvertToStringInvariant(value, safeConversion); } catch { return string.Empty; } } private static string XmlConvertToStringInvariant(object? value, bool safeConversion) { try { string text = Convert.ToString(value, CultureInfo.InvariantCulture); if (text == null) { return string.Empty; } return safeConversion ? RemoveInvalidXmlChars(text) : text; } catch { return string.Empty; } } internal static string XmlConvertToElementName(string xmlElementName) { if (string.IsNullOrEmpty(xmlElementName)) { return xmlElementName; } xmlElementName = RemoveInvalidXmlChars(xmlElementName); bool flag = true; StringBuilder stringBuilder = null; for (int j = 0; j < xmlElementName.Length; j++) { char c = xmlElementName[j]; if (char.IsLetter(c)) { stringBuilder?.Append(c); continue; } bool flag2 = false; switch (c) { case ':': if (j != 0 && flag) { flag = false; stringBuilder?.Append(c); continue; } break; case '_': stringBuilder?.Append(c); continue; case '-': case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (j != 0) { stringBuilder?.Append(c); continue; } flag2 = true; break; } if (stringBuilder == null) { stringBuilder = CreateStringBuilder(xmlElementName, j); } stringBuilder.Append('_'); if (flag2) { stringBuilder.Append(c); } } stringBuilder?.TrimRight(); return stringBuilder?.ToString() ?? xmlElementName; static StringBuilder CreateStringBuilder(string orgValue, int i) { StringBuilder stringBuilder2 = new StringBuilder(orgValue.Length); if (i > 0) { stringBuilder2.Append(orgValue, 0, i); } return stringBuilder2; } } private static string EnsureDecimalPlace(string text) { if (text.IndexOf('.') != -1 || text.IndexOfAny(DecimalScientificExponent) != -1) { return text; } if (text.Length == 1) { switch (text[0]) { case '0': return "0.0"; case '1': return "1.0"; case '2': return "2.0"; case '3': return "3.0"; case '4': return "4.0"; case '5': return "5.0"; case '6': return "6.0"; case '7': return "7.0"; case '8': return "8.0"; case '9': return "9.0"; } } return text + ".0"; } public static void EscapeCDataWhenNeeded(StringBuilder builder, int orgLength) { int length = builder.Length; char c = '\0'; char c2 = c; char c3 = c; for (int i = orgLength; i < length; i++) { c = c2; c2 = c3; c3 = builder[i]; if (!XmlConvertIsXmlChar(c3) || (c == ']' && c2 == ']' && c3 == '>')) { string text = builder.ToString(i - 2, length - i + 2); builder.Length = i - 2; text = RemoveInvalidXmlChars(text); text = text.Replace("]]>", "]]]]>"); builder.Append(text); break; } } } public static string EscapeCData(string text, StringBuilder? builder = null) { if (string.IsNullOrEmpty(text)) { string text2 = ""; builder?.Append(text2); return text2; } builder?.Append("", StringComparison.Ordinal) >= 0) { text3 = text3.Replace("]]>", "]]]]>"); if (builder != null) { builder.Length = num; builder.Append(text3); } } } else { EscapeCDataWhenNeeded(builder, num); } builder?.Append("]]>"); if (builder != null) { return string.Empty; } return ""; } } internal sealed class XmlParser { public sealed class XmlParserElement { private IList? _children; private readonly IList>? _attributes; public string Name { get; set; } public string? InnerText { get; set; } public IList Children => _children ?? ArrayHelper.Empty(); public IList> Attributes => _attributes ?? ArrayHelper.Empty>(); public XmlParserElement(string name, IList>? attributes) { Name = name; _attributes = attributes; } public void AddChild(XmlParserElement child) { if (_children == null) { _children = new List(); } _children.Add(child); } } private sealed class CharEnumerator : IEnumerator, IEnumerator, IDisposable { private readonly TextReader _xmlSource; private int _lineNumber; private char _current; private char? _peek; private bool _endOfFile; public char Current { get { if (_endOfFile) { throw new XmlParserException("Invalid XML document. Unexpected end of document."); } return _current; } } public int LineNumber => _lineNumber; object IEnumerator.Current => Current; public bool EndOfFile => _endOfFile; public CharEnumerator(TextReader xmlSource) { _xmlSource = xmlSource; int num = xmlSource.Read(); _current = ((num >= 0) ? ((char)num) : '\0'); _lineNumber = ((num != 10) ? 1 : 2); } public bool MoveNext() { if (_peek.HasValue) { _current = _peek.Value; if (_current == '\n') { _lineNumber++; } _peek = null; return true; } int num = _xmlSource.Read(); if (num < 0) { _endOfFile = true; return false; } _current = (char)num; if (_current == '\n') { _lineNumber++; } return true; } public char Peek() { if (_peek.HasValue) { return _peek.Value; } int num = _xmlSource.Read(); if (num < 0) { return '\0'; } _peek = (char)num; return _peek.Value; } void IEnumerator.Reset() { } void IDisposable.Dispose() { } } private readonly CharEnumerator _xmlSource; private readonly StringBuilder _stringBuilder = new StringBuilder(); private static readonly Dictionary _specialTokens = new Dictionary { { "amp", "&" }, { "AMP", "&" }, { "apos", "'" }, { "APOS", "'" }, { "quot", "\"" }, { "QUOT", "\"" }, { "lt", "<" }, { "LT", "<" }, { "gt", ">" }, { "GT", ">" } }; public XmlParser(TextReader xmlSource) { _xmlSource = new CharEnumerator(xmlSource); } public XmlParser(string xmlSource) { _xmlSource = new CharEnumerator(new StringReader(xmlSource)); } public XmlParserElement LoadDocument(out IList? processingInstructions) { try { TryReadProcessingInstructions(out processingInstructions); if (!TryReadStartElement(out string name, out List> attributes)) { throw new XmlParserException("Invalid XML document. Cannot parse root start-tag"); } Stack stack = new Stack(); XmlParserElement xmlParserElement = new XmlParserElement(name ?? string.Empty, attributes); stack.Push(xmlParserElement); bool flag = true; while (flag) { flag = false; if (TryReadEndElement(xmlParserElement.Name)) { flag = true; stack.Pop(); if (stack.Count == 0) { break; } xmlParserElement = stack.Peek(); } try { if (TryReadInnerText(out string innerText)) { flag = true; xmlParserElement.InnerText += innerText; } if (TryReadStartElement(out string name2, out List> attributes2)) { flag = true; xmlParserElement = new XmlParserElement(name2 ?? string.Empty, attributes2); stack.Peek().AddChild(xmlParserElement); stack.Push(xmlParserElement); } } catch (XmlParserException ex) { throw new XmlParserException(ex.Message + " - Start-tag: " + xmlParserElement.Name); } } if (!flag) { throw new XmlParserException("Invalid XML document. Cannot parse end-tag: " + xmlParserElement.Name); } SkipWhiteSpaces(); while (_xmlSource.Peek() == '!' && _xmlSource.Current == '<') { _xmlSource.MoveNext(); SkipXmlComment(); } if (_xmlSource.MoveNext()) { throw new XmlParserException("Invalid XML document. Unexpected characters after end-tag: " + xmlParserElement.Name); } return xmlParserElement; } catch (XmlParserException ex2) { throw new XmlParserException($"{ex2.Message} - Line: {_xmlSource.LineNumber}"); } } public bool TryReadProcessingInstructions(out IList? processingInstructions) { SkipWhiteSpaces(); processingInstructions = null; while (_xmlSource.Current == '<') { if (_xmlSource.Peek() == '!') { _xmlSource.MoveNext(); SkipXmlComment(); continue; } if (_xmlSource.Peek() != '?') { break; } if (!TryBeginReadStartElement(out string name, processingInstruction: true)) { throw new XmlParserException("Invalid XML document. Cannot parse XML processing instruction"); } if (name == null || string.IsNullOrEmpty(name) || name.Length == 1 || name[0] != '?') { throw new XmlParserException("Invalid XML document. Cannot parse XML processing instruction"); } name = name.Substring(1); TryReadAttributes(out List> attributes, expectsProcessingInstruction: true); if (!SkipChar('?')) { throw new XmlParserException("Invalid XML document. Cannot parse XML processing instruction: " + name); } if (!SkipChar('>')) { throw new XmlParserException("Invalid XML document. Cannot parse XML processing instruction: " + name); } XmlParserElement item = new XmlParserElement(name, attributes); processingInstructions = processingInstructions ?? new List(); processingInstructions.Add(item); SkipWhiteSpaces(); } return processingInstructions != null; } public bool TryReadStartElement(out string? name, out List>? attributes) { SkipWhiteSpaces(); if (TryBeginReadStartElement(out name)) { try { TryReadAttributes(out attributes); SkipChar('>'); } catch (XmlParserException ex) { throw new XmlParserException(ex.Message + " - Cannot parse attributes for Start-tag: " + name); } return true; } name = null; attributes = null; return false; } public bool TryReadEndElement(string name) { SkipWhiteSpaces(); if (_xmlSource.Current == '<' && _xmlSource.Peek() != '/') { return false; } if (_xmlSource.Current == '/' && _xmlSource.Peek() == '>') { if (SkipChar('/')) { return SkipChar('>'); } return false; } if (!SkipChar('<')) { return false; } if (!SkipChar('/')) { throw new XmlParserException("Invalid XML document. Cannot parse end-tag: " + name); } foreach (char c in name) { if (_xmlSource.Current != c || !_xmlSource.MoveNext()) { throw new XmlParserException("Invalid XML document. Cannot parse end-tag: " + name); } } if (!SkipChar('>')) { throw new XmlParserException("Invalid XML document. Cannot parse end-tag: " + name); } return true; } public bool TryReadInnerText(out string innerText) { char current = _xmlSource.Current; SkipWhiteSpaces(); innerText = ReadUntilChar('<', includeSpaces: true); while (_xmlSource.Current == '<' && _xmlSource.Peek() == '!') { _xmlSource.MoveNext(); current = _xmlSource.Current; if (_xmlSource.Peek() == '-') { SkipXmlComment(); } else { if (_xmlSource.Peek() != '[') { throw new XmlParserException("Invalid XML document. Cannot parse XML comment"); } innerText += ReadCDATA(); } innerText += ReadUntilChar('<', includeSpaces: true); } SkipWhiteSpaces(); if (string.IsNullOrEmpty(innerText) && _xmlSource.Current == '<') { return current != '<'; } return true; } private string ReadCDATA() { if (!SkipCDATA()) { throw new XmlParserException("Invalid XML document. Cannot parse XML CDATA"); } _stringBuilder.ClearBuilder(); do { if (_xmlSource.Current == ']' && _xmlSource.Peek() == ']') { _xmlSource.MoveNext(); if (_xmlSource.Peek() == '>') { _xmlSource.MoveNext(); _xmlSource.MoveNext(); break; } _stringBuilder.Append(']'); } _stringBuilder.Append(_xmlSource.Current); } while (_xmlSource.MoveNext()); SkipWhiteSpaces(); return _stringBuilder.ToString(); } private bool SkipCDATA() { if (!SkipChar('!')) { return false; } if (!SkipChar('[')) { return false; } if (!SkipChar('C')) { return false; } if (!SkipChar('D')) { return false; } if (!SkipChar('A')) { return false; } if (!SkipChar('T')) { return false; } if (!SkipChar('A')) { return false; } if (!SkipChar('[')) { return false; } return true; } private void SkipXmlComment() { if (!SkipChar('!') || !SkipChar('-') || !SkipChar('-')) { throw new XmlParserException("Invalid XML document. Cannot parse XML comment"); } while (_xmlSource.MoveNext() && (!SkipChar('-') || !SkipChar('-') || !SkipChar('>'))) { } SkipWhiteSpaces(); } private bool TryReadAttributes(out List>? attributes, bool expectsProcessingInstruction = false) { SkipWhiteSpaces(); attributes = null; while (_xmlSource.Current != '>' && _xmlSource.Current != '/' && (!expectsProcessingInstruction || _xmlSource.Current != '?')) { string text = ReadUntilChar('=').Trim(); if (string.IsNullOrEmpty(text)) { throw new XmlParserException("Invalid XML document. Cannot parse XML attribute"); } if (!SkipChar('=')) { throw new XmlParserException("Invalid XML document. Cannot parse XML attribute"); } bool flag = false; SkipWhiteSpaces(); if (!SkipChar('"')) { if (!SkipChar('\'')) { throw new XmlParserException("Invalid XML document. Cannot parse XML attribute: " + text); } flag = true; } try { string value = ReadUntilChar(flag ? '\'' : '"', includeSpaces: true); _xmlSource.MoveNext(); attributes = attributes ?? new List>(); attributes.Add(new KeyValuePair(text, value)); SkipWhiteSpaces(); } catch (XmlParserException ex) { throw new XmlParserException(ex.Message + " - XML attribute: " + text); } } return attributes != null; } private bool TryBeginReadStartElement(out string? name, bool processingInstruction = false) { if (_xmlSource.Current != '<' || _xmlSource.Peek() == '/' || _xmlSource.Peek() == '!') { name = null; return false; } _xmlSource.MoveNext(); SkipWhiteSpaces(); _stringBuilder.ClearBuilder(); do { char current = _xmlSource.Current; if (CharIsSpace(current) || current == '/' || current == '>') { break; } if (processingInstruction && current == '?') { if (_stringBuilder.Length != 0) { throw new XmlParserException($"Invalid XML document. Cannot parse XML start-tag with character: {current}"); } } else if (!IsValidXmlNameChar(current)) { throw new XmlParserException($"Invalid XML document. Cannot parse XML start-tag with character: {current}"); } _stringBuilder.Append(current); } while (_xmlSource.MoveNext()); name = _stringBuilder.ToString(); if (string.IsNullOrEmpty(name)) { throw new XmlParserException("Invalid XML document. Cannot parse XML start-tag"); } return true; } private bool SkipChar(char c) { if (_xmlSource.Current != c) { return false; } _xmlSource.MoveNext(); return true; } private bool SkipWhiteSpaces() { bool result = false; while (!_xmlSource.EndOfFile && CharIsSpace(_xmlSource.Current) && _xmlSource.MoveNext()) { result = true; } return result; } private string ReadUntilChar(char expectedChar, bool includeSpaces = false) { _stringBuilder.ClearBuilder(); bool flag = false; do { char current = _xmlSource.Current; if (current == expectedChar) { break; } if (!includeSpaces && CharIsSpace(current)) { SkipWhiteSpaces(); if (_xmlSource.Current == expectedChar) { break; } throw new XmlParserException("Invalid XML document. Cannot parse attribute-name with white-space"); } if (!includeSpaces && !IsValidXmlNameChar(current)) { throw new XmlParserException($"Invalid XML document. Cannot parse attribute-name with character: {current}"); } if (current == '<' && (!includeSpaces || expectedChar == '<')) { throw new XmlParserException("Invalid XML document. Cannot parse value with '<', maybe encode to <"); } if (includeSpaces && current == '&') { _xmlSource.MoveNext(); if (_xmlSource.Current == '#' && char.IsDigit(_xmlSource.Peek())) { int num = TryParseUnicodeValue(); _stringBuilder.Append((char)num); continue; } if (_xmlSource.Current == '#' && (_xmlSource.Peek() == 'x' || _xmlSource.Peek() == 'X')) { _xmlSource.MoveNext(); int num2 = TryParseUnicodeValueHex(); _stringBuilder.Append((char)num2); continue; } if (TryParseSpecialXmlToken(out string xmlToken)) { _stringBuilder.Append(xmlToken); continue; } _stringBuilder.Append('&'); if (_xmlSource.Current == expectedChar) { break; } _stringBuilder.Append(_xmlSource.Current); continue; } if (includeSpaces && expectedChar == '<') { if (_stringBuilder.Length == 0 && CharIsSpace(current)) { continue; } flag = !flag && CharIsSpace(current); } _stringBuilder.Append(current); } while (_xmlSource.MoveNext()); string text = _stringBuilder.ToString(); if (!flag) { return text; } return text.TrimEnd(ArrayHelper.Empty()); } private static bool IsValidXmlNameChar(char chr) { if (char.IsLetterOrDigit(chr)) { return true; } switch (chr) { case '-': case '.': case ':': case '_': return true; default: return false; } } private int TryParseUnicodeValue() { int num = 0; while (_xmlSource.MoveNext()) { char current = _xmlSource.Current; if (current == ';') { break; } num *= 10; if (current >= '0' && current <= '9') { num += current - 48; continue; } throw new XmlParserException("Invalid XML document. Cannot parse unicode-char digit-value"); } if (num >= 65535) { throw new XmlParserException("Invalid XML document. Unicode value exceeds maximum allowed value"); } return num; } private int TryParseUnicodeValueHex() { int num = 0; while (_xmlSource.MoveNext() && _xmlSource.Current != ';') { num *= 16; char c = char.ToUpperInvariant(_xmlSource.Current); if (c >= 'A' && c <= 'F') { num += c - 65 + 10; continue; } if (c >= '0' && c <= '9') { num += c - 48; continue; } throw new XmlParserException("Invalid XML document. Cannot parse unicode-char hex-value"); } if (num >= 65535) { throw new XmlParserException("Invalid XML document. Unicode value exceeds maximum allowed value"); } return num; } private bool TryParseSpecialXmlToken(out string? xmlToken) { foreach (KeyValuePair specialToken in _specialTokens) { if (_xmlSource.Current != specialToken.Key[0] || _xmlSource.Peek() != specialToken.Key[1]) { continue; } string key = specialToken.Key; foreach (char c in key) { if (!SkipChar(c)) { throw new XmlParserException("Invalid XML document. Cannot parse special token: " + specialToken.Key); } } if (_xmlSource.Current != ';') { throw new XmlParserException("Invalid XML document. Cannot parse special token: " + specialToken.Key); } xmlToken = specialToken.Value; return true; } xmlToken = null; return false; } private static bool CharIsSpace(char c) { switch (c) { case '\t': case '\n': case '\r': case ' ': return true; default: return char.IsWhiteSpace(c); } } } } namespace NLog.Internal.Fakeables { internal sealed class AppEnvironmentWrapper : IAppEnvironment, IFileSystem { private const string LongUNCPrefix = "\\\\?\\UNC\\"; private const string UnknownProcessName = "[unknown]"; private string? _entryAssemblyLocation; private string? _entryAssemblyFileName; private string? _currentProcessFilePath; private string? _currentProcessBaseName; private string? _appDomainBaseDirectory; private string? _appDomainConfigFile; private string? _appDomainFriendlyName; private IEnumerable? _appDomainPrivateBinPath; private int? _appDomainId; private int? _currentProcessId; public string EntryAssemblyLocation => _entryAssemblyLocation ?? (_entryAssemblyLocation = LookupEntryAssemblyLocation()); public string EntryAssemblyFileName => _entryAssemblyFileName ?? (_entryAssemblyFileName = LookupEntryAssemblyFileName()); public string CurrentProcessFilePath => _currentProcessFilePath ?? (_currentProcessFilePath = LookupCurrentProcessFilePathWithFallback()); public string CurrentProcessBaseName => _currentProcessBaseName ?? (_currentProcessBaseName = LookupCurrentProcessNameWithFallback()); public int CurrentProcessId { get { int? currentProcessId = _currentProcessId; if (!currentProcessId.HasValue) { int? num = (_currentProcessId = LookupCurrentProcessIdWithFallback()); return num.Value; } return currentProcessId.GetValueOrDefault(); } } public string AppDomainBaseDirectory => _appDomainBaseDirectory ?? (_appDomainBaseDirectory = LookupAppDomainBaseDirectory()); public string AppDomainConfigurationFile => _appDomainConfigFile ?? (_appDomainConfigFile = LookupAppDomainConfigFileSafe()); public string AppDomainFriendlyName { get { string text = _appDomainFriendlyName; if (text == null) { string obj = LookupAppDomainFriendlyName() ?? CurrentProcessBaseName; string text2 = obj; _appDomainFriendlyName = obj; text = text2; } return text; } } public int AppDomainId { get { int? appDomainId = _appDomainId; if (!appDomainId.HasValue) { int? num = (_appDomainId = AppDomain.CurrentDomain.Id); return num.Value; } return appDomainId.GetValueOrDefault(); } } public IEnumerable AppDomainPrivateBinPath => _appDomainPrivateBinPath ?? (_appDomainPrivateBinPath = LookupAppDomainPrivateBinPathSafe()); public string UserTempFilePath => Path.GetTempPath(); public event EventHandler ProcessExit { add { AppDomain.CurrentDomain.ProcessExit += value; AppDomain.CurrentDomain.DomainUnload += value; } remove { AppDomain.CurrentDomain.DomainUnload -= value; AppDomain.CurrentDomain.ProcessExit -= value; } } public IEnumerable GetAppDomainRuntimeAssemblies() { return AppDomain.CurrentDomain?.GetAssemblies() ?? ArrayHelper.Empty(); } public bool FileExists(string path) { return File.Exists(path); } public TextReader LoadTextFile(string path) { return new StreamReader(path); } internal static string FixFilePathWithLongUNC(string filepath) { if (!string.IsNullOrEmpty(filepath) && filepath.StartsWith("\\\\?\\UNC\\", StringComparison.Ordinal) && filepath.Length < 260) { filepath = "\\\\" + filepath.Substring("\\\\?\\UNC\\".Length); } return filepath; } private static string LookupAppDomainBaseDirectory() { try { return AppDomain.CurrentDomain.BaseDirectory ?? string.Empty; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug(ex, "AppDomain.BaseDirectory Failed"); return string.Empty; } } private static string[] LookupAppDomainPrivateBinPathSafe() { try { return LookupAppDomainPrivateBinPath(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug(ex, "AppDomain.CurrentDomain.SetupInformation.PrivateBinPath Failed"); return ArrayHelper.Empty(); } } private static string[] LookupAppDomainPrivateBinPath() { try { return ArrayHelper.Empty(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug(ex, "AppDomain.CurrentDomain.SetupInformation.PrivateBinPath Failed"); return ArrayHelper.Empty(); } } private static string LookupAppDomainConfigFileSafe() { try { return LookupAppDomainConfigFile(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug(ex, "AppDomain.SetupInformation.ConfigurationFile Failed"); return string.Empty; } } private static string LookupAppDomainConfigFile() { try { return string.Empty; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug(ex, "AppDomain.SetupInformation.ConfigurationFile Failed"); return string.Empty; } } private static string LookupAppDomainFriendlyName() { try { string friendlyName = AppDomain.CurrentDomain.FriendlyName; return (!string.IsNullOrEmpty(friendlyName)) ? friendlyName : LookupEntryAssemblyFriendlyName(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug(ex, "AppDomain.FriendlyName Failed"); return LookupEntryAssemblyFriendlyName(); } } private static string LookupEntryAssemblyFriendlyName() { try { return Assembly.GetEntryAssembly()?.GetName()?.Name ?? "[unknown]"; } catch { return "[unknown]"; } } private static string LookupEntryAssemblyLocation() { string assemblyFileLocation = AssemblyHelpers.GetAssemblyFileLocation(Assembly.GetEntryAssembly()); if (!string.IsNullOrEmpty(assemblyFileLocation)) { return Path.GetDirectoryName(assemblyFileLocation) ?? string.Empty; } return string.Empty; } private static string LookupEntryAssemblyFileName() { try { Assembly entryAssembly = Assembly.GetEntryAssembly(); string assemblyFileLocation = AssemblyHelpers.GetAssemblyFileLocation(entryAssembly); if (!string.IsNullOrEmpty(assemblyFileLocation)) { return Path.GetFileName(assemblyFileLocation); } string text = entryAssembly?.GetName()?.Name; if (!string.IsNullOrEmpty(text)) { return text + ".dll"; } return string.Empty; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug("LookupEntryAssemblyFileName Failed - {0}", ex.Message); return string.Empty; } } private static string LookupCurrentProcessFilePathWithFallback() { try { return LookupCurrentProcessFilePath() ?? LookupCurrentProcessFilePathNative(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug("LookupCurrentProcessFilePath Failed - {0}", ex.Message); return LookupCurrentProcessFilePathNative(); } } private static string? LookupCurrentProcessFilePath() { try { string text = Process.GetCurrentProcess()?.MainModule?.FileName; return (!string.IsNullOrEmpty(text)) ? text : null; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug("LookupCurrentProcessFilePath Managed Failed - {0}", ex.Message); return null; } } private static int LookupCurrentProcessIdWithFallback() { try { return LookupCurrentProcessId() ?? LookupCurrentProcessIdNative(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug("LookupCurrentProcessId Failed - {0}", ex.Message); return LookupCurrentProcessIdNative(); } } private static int? LookupCurrentProcessId() { try { return Process.GetCurrentProcess()?.Id; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug("LookupCurrentProcessId Managed Failed - {0}", ex.Message); return null; } } private static string LookupCurrentProcessNameWithFallback() { try { return LookupCurrentProcessName() ?? LookupCurrentProcessNameNative(); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug("LookupCurrentProcessName Failed - {0}", ex.Message); return LookupCurrentProcessNameNative(); } } private static string? LookupCurrentProcessName() { try { string text = Process.GetCurrentProcess()?.ProcessName; if (!string.IsNullOrEmpty(text)) { return text; } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Debug("LookupCurrentProcessName Managed Failed - {0}", ex.Message); } return null; } private static string LookupCurrentProcessNameNative() { string text = LookupCurrentProcessFilePath(); if (!string.IsNullOrEmpty(text)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text); if (!string.IsNullOrEmpty(fileNameWithoutExtension)) { return fileNameWithoutExtension; } } string text2 = LookupEntryAssemblyFileName(); if (!string.IsNullOrEmpty(text2)) { text2 = Path.GetFileNameWithoutExtension(text2); if (!string.IsNullOrEmpty(text2)) { return text2; } } return "[unknown]"; } private static string LookupCurrentProcessFilePathNative() { return string.Empty; } private static int LookupCurrentProcessIdNative() { return 0; } } internal interface IAppEnvironment : IFileSystem { string AppDomainBaseDirectory { get; } string AppDomainConfigurationFile { get; } string AppDomainFriendlyName { get; } int AppDomainId { get; } IEnumerable AppDomainPrivateBinPath { get; } string CurrentProcessFilePath { get; } string CurrentProcessBaseName { get; } int CurrentProcessId { get; } string EntryAssemblyLocation { get; } string EntryAssemblyFileName { get; } string UserTempFilePath { get; } event EventHandler ProcessExit; IEnumerable GetAppDomainRuntimeAssemblies(); } internal interface IFileSystem { bool FileExists(string path); TextReader LoadTextFile(string path); } } namespace NLog.Filters { [Filter("when")] public class ConditionBasedFilter : Filter { internal static readonly ConditionBasedFilter Empty = new ConditionBasedFilter(); public ConditionExpression Condition { get; set; } = ConditionLiteralExpression.Null; internal FilterResult FilterDefaultAction { get; set; } protected override FilterResult Check(LogEventInfo logEvent) { object obj = Condition?.Evaluate(logEvent); if (!ConditionExpression.BoxedTrue.Equals(obj)) { return FilterDefaultAction; } return base.Action; } } [NLogConfigurationItem] public abstract class Filter { public FilterResult Action { get; set; } protected Filter() { Action = FilterResult.Neutral; } internal FilterResult GetFilterResult(LogEventInfo logEvent) { return Check(logEvent); } protected abstract FilterResult Check(LogEventInfo logEvent); } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class FilterAttribute : NameBaseAttribute { public FilterAttribute(string name) : base(name) { } } public enum FilterResult { Neutral, Log, Ignore, LogFinal, IgnoreFinal } public abstract class LayoutBasedFilter : Filter { public Layout Layout { get; set; } = NLog.Layouts.Layout.Empty; } [Filter("whenContains")] public class WhenContainsFilter : LayoutBasedFilter { public bool IgnoreCase { get; set; } public string Substring { get; set; } = string.Empty; protected override FilterResult Check(LogEventInfo logEvent) { StringComparison comparisonType = (IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); string text = base.Layout.Render(logEvent); if (!string.IsNullOrEmpty(Substring) && text.IndexOf(Substring, comparisonType) >= 0) { return base.Action; } return FilterResult.Neutral; } } [Filter("whenEqual")] public class WhenEqualFilter : LayoutBasedFilter { public bool IgnoreCase { get; set; } public string CompareTo { get; set; } = string.Empty; protected override FilterResult Check(LogEventInfo logEvent) { StringComparison comparisonType = (IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); if (base.Layout.Render(logEvent).Equals(CompareTo, comparisonType)) { return base.Action; } return FilterResult.Neutral; } } public class WhenMethodFilter : Filter { private readonly Func _filterMethod; public WhenMethodFilter(Func filterMethod) { Guard.ThrowIfNull(filterMethod, "filterMethod"); _filterMethod = filterMethod; } protected override FilterResult Check(LogEventInfo logEvent) { FilterResult filterResult = _filterMethod(logEvent); if (base.Action == FilterResult.Neutral) { return filterResult; } if (filterResult != 0) { return base.Action; } return FilterResult.Neutral; } } [Filter("whenNotContains")] public class WhenNotContainsFilter : LayoutBasedFilter { public string Substring { get; set; } = string.Empty; public bool IgnoreCase { get; set; } protected override FilterResult Check(LogEventInfo logEvent) { StringComparison comparisonType = (IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); string text = base.Layout.Render(logEvent); if (!string.IsNullOrEmpty(Substring) && text.IndexOf(Substring, comparisonType) < 0) { return base.Action; } return FilterResult.Neutral; } } [Filter("whenNotEqual")] public class WhenNotEqualFilter : LayoutBasedFilter { public string CompareTo { get; set; } = string.Empty; public bool IgnoreCase { get; set; } protected override FilterResult Check(LogEventInfo logEvent) { StringComparison comparisonType = (IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); if (!base.Layout.Render(logEvent).Equals(CompareTo, comparisonType)) { return base.Action; } return FilterResult.Neutral; } } [Filter("whenRepeated")] public class WhenRepeatedFilter : LayoutBasedFilter { private sealed class FilterInfo { public StringBuilder StringBuffer { get; } public LogLevel? LogLevel { get; private set; } private DateTime LastLogTime { get; set; } private DateTime LastFilterTime { get; set; } public int FilterCount { get; private set; } public FilterInfo(StringBuilder stringBuilder) { StringBuffer = stringBuilder; } public void Refresh(LogLevel logLevel, DateTime logTimeStamp, int filterCount) { if (filterCount == 0) { LastLogTime = logTimeStamp; LogLevel = logLevel; } else if ((object)LogLevel == null || logLevel.Ordinal > LogLevel.Ordinal) { LogLevel = logLevel; } LastFilterTime = logTimeStamp; FilterCount = filterCount; } public bool IsObsolete(DateTime logEventTime, int timeoutSeconds) { if (FilterCount == 0) { return HasExpired(logEventTime, timeoutSeconds); } if ((logEventTime - LastFilterTime).TotalSeconds > (double)timeoutSeconds) { return HasExpired(logEventTime, timeoutSeconds * 2); } return false; } public bool HasExpired(DateTime logEventTime, int timeoutSeconds) { return (logEventTime - LastLogTime).TotalSeconds > (double)timeoutSeconds; } } private readonly struct FilterInfoKey : IEquatable { private readonly StringBuilder? _stringBuffer; public readonly string? StringValue; public readonly int StringHashCode; public FilterInfoKey(StringBuilder? stringBuffer, string? stringValue, int? stringHashCode = null) { _stringBuffer = stringBuffer; StringValue = stringValue; if (stringHashCode.HasValue) { StringHashCode = stringHashCode.Value; } else if (stringBuffer != null) { int num = stringBuffer.Length.GetHashCode(); int num2 = Math.Min(stringBuffer.Length, 100); for (int i = 0; i < num2; i++) { num ^= stringBuffer[i].GetHashCode(); } StringHashCode = num; } else { StringHashCode = ((stringValue != null) ? StringComparer.Ordinal.GetHashCode(stringValue) : 0); } } public override int GetHashCode() { return StringHashCode; } public bool Equals(FilterInfoKey other) { if (StringValue != null) { return string.Equals(StringValue, other.StringValue, StringComparison.Ordinal); } if (_stringBuffer != null && other._stringBuffer != null) { if (_stringBuffer.Capacity != other._stringBuffer.Capacity) { return _stringBuffer.EqualTo(other._stringBuffer); } return _stringBuffer.Equals(other._stringBuffer); } if (_stringBuffer == other._stringBuffer) { return (object)StringValue == other.StringValue; } return false; } public override bool Equals(object? obj) { if (obj is FilterInfoKey other) { return Equals(other); } return false; } } private const int MaxInitialRenderBufferLength = 16384; private bool? _optimizeBufferReuse; private readonly ReusableBuilderCreator ReusableLayoutBuilder = new ReusableBuilderCreator(); private readonly Dictionary _repeatFilter = new Dictionary(1000); private readonly Stack> _objectPool = new Stack>(1000); public int TimeoutSeconds { get; set; } = 10; public int MaxLength { get; set; } = 1000; public bool IncludeFirst { get; set; } public int MaxFilterCacheSize { get; set; } = 50000; public int DefaultFilterCacheSize { get; set; } = 1000; public string FilterCountPropertyName { get; set; } = string.Empty; public string FilterCountMessageAppendFormat { get; set; } = string.Empty; [Obsolete("No longer used, and always returns true. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public bool OptimizeBufferReuse { get { return _optimizeBufferReuse.GetValueOrDefault(true); } set { _optimizeBufferReuse = (value ? new bool?(true) : null); } } public int OptimizeBufferDefaultLength { get; set; } = 1000; protected override FilterResult Check(LogEventInfo logEvent) { FilterResult result = FilterResult.Neutral; bool flag = false; lock (_repeatFilter) { ReusableObjectCreator.LockOject lockOject = ReusableLayoutBuilder.Allocate(); try { if (lockOject.Result.Capacity != OptimizeBufferDefaultLength) { if (OptimizeBufferDefaultLength < 16384) { OptimizeBufferDefaultLength = MaxLength; while (OptimizeBufferDefaultLength < lockOject.Result.Capacity && OptimizeBufferDefaultLength < 16384) { OptimizeBufferDefaultLength *= 2; } } lockOject.Result.Capacity = OptimizeBufferDefaultLength; } FilterInfoKey key = RenderFilterInfoKey(logEvent, lockOject.Result); if (!_repeatFilter.TryGetValue(key, out FilterInfo value)) { value = CreateFilterInfo(logEvent); if (value.StringBuffer != null) { value.StringBuffer.ClearBuilder(); int num = Math.Min(lockOject.Result.Length, MaxLength); for (int i = 0; i < num; i++) { value.StringBuffer.Append(lockOject.Result[i]); } } value.Refresh(logEvent.Level, logEvent.TimeStamp, 0); _repeatFilter.Add(new FilterInfoKey(value.StringBuffer, key.StringValue, key.StringHashCode), value); flag = true; } else { if (IncludeFirst) { flag = value.IsObsolete(logEvent.TimeStamp, TimeoutSeconds); } result = RefreshFilterInfo(logEvent, value); } } finally { ((IDisposable)lockOject).Dispose(); } } if (IncludeFirst && flag) { result = base.Action; } return result; } private FilterInfo CreateFilterInfo(LogEventInfo logEvent) { if (_objectPool.Count == 0 && _repeatFilter.Count > DefaultFilterCacheSize) { int val = ((_repeatFilter.Count > MaxFilterCacheSize) ? (TimeoutSeconds * 2 / 3) : TimeoutSeconds); PruneFilterCache(logEvent, Math.Max(1, val)); if (_repeatFilter.Count > MaxFilterCacheSize) { PruneFilterCache(logEvent, Math.Max(1, TimeoutSeconds / 2)); } } FilterInfo filterInfo; if (_objectPool.Count == 0) { filterInfo = new FilterInfo(new StringBuilder(OptimizeBufferDefaultLength)); } else { filterInfo = _objectPool.Pop().Value; if (filterInfo.StringBuffer != null && filterInfo.StringBuffer.Capacity != OptimizeBufferDefaultLength) { filterInfo.StringBuffer.Capacity = OptimizeBufferDefaultLength; } } return filterInfo; } private void PruneFilterCache(LogEventInfo logEvent, int aggressiveTimeoutSeconds) { foreach (KeyValuePair item in _repeatFilter) { if (item.Value.IsObsolete(logEvent.TimeStamp, aggressiveTimeoutSeconds)) { _objectPool.Push(item); } } foreach (KeyValuePair item2 in _objectPool) { _repeatFilter.Remove(item2.Key); } if (_repeatFilter.Count * 2 > DefaultFilterCacheSize && DefaultFilterCacheSize < MaxFilterCacheSize) { DefaultFilterCacheSize *= 2; } while (_objectPool.Count != 0 && _objectPool.Count > DefaultFilterCacheSize) { _objectPool.Pop(); } } private FilterInfoKey RenderFilterInfoKey(LogEventInfo logEvent, StringBuilder targetBuilder) { if (targetBuilder != null) { base.Layout.Render(logEvent, targetBuilder); if (targetBuilder.Length > MaxLength) { targetBuilder.Length = MaxLength; } return new FilterInfoKey(targetBuilder, null); } string text = base.Layout.Render(logEvent); if (text.Length > MaxLength) { text = text.Substring(0, MaxLength); } return new FilterInfoKey(null, text); } private FilterResult RefreshFilterInfo(LogEventInfo logEvent, FilterInfo filterInfo) { if (filterInfo.HasExpired(logEvent.TimeStamp, TimeoutSeconds) || logEvent.Level > filterInfo.LogLevel) { int num = filterInfo.FilterCount; if (num > 0 && filterInfo.IsObsolete(logEvent.TimeStamp, TimeoutSeconds)) { num = 0; } filterInfo.Refresh(logEvent.Level, logEvent.TimeStamp, 0); if (num > 0) { if (!string.IsNullOrEmpty(FilterCountPropertyName)) { if (!logEvent.Properties.TryGetValue(FilterCountPropertyName, out object value)) { logEvent.Properties[FilterCountPropertyName] = num; } else if (value is int val) { num = Math.Max(val, num); logEvent.Properties[FilterCountPropertyName] = num; } } if (!string.IsNullOrEmpty(FilterCountMessageAppendFormat) && logEvent.Message != null) { logEvent.Message += string.Format(FilterCountMessageAppendFormat, num.ToString(CultureInfo.InvariantCulture)); } } return FilterResult.Neutral; } filterInfo.Refresh(logEvent.Level, logEvent.TimeStamp, filterInfo.FilterCount + 1); return base.Action; } } } namespace NLog.Config { [Obsolete("Attribute is no longer used. Obsolete with NLog 5.0")] [AttributeUsage(AttributeTargets.Property)] public sealed class AdvancedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class)] public sealed class AppDomainFixedOutputAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property)] [MeansImplicitUse] public sealed class ArrayParameterAttribute : Attribute { public Type ItemType { get; } public string ElementName { get; } public ArrayParameterAttribute(Type itemType, string elementName) { ItemType = itemType; ElementName = elementName; } } [Obsolete("Instead use RegisterType, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] internal sealed class AssemblyExtensionLoader : IAssemblyExtensionLoader { [CompilerGenerated] private sealed class d__14 : IEnumerable>, IEnumerable, IEnumerator>, IEnumerator, IDisposable { private int <>1__state; private KeyValuePair <>2__current; private int <>l__initialThreadId; private string 5__2; private string 5__3; KeyValuePair IEnumerator>.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__14(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; 5__3 = null; <>1__state = -2; } private bool MoveNext() { string text; switch (<>1__state) { default: return false; case 0: { <>1__state = -1; string assemblyFileLocation = AssemblyHelpers.GetAssemblyFileLocation(typeof(LogFactory).Assembly); 5__2 = (string.IsNullOrEmpty(assemblyFileLocation) ? assemblyFileLocation : PathHelpers.TrimDirectorySeparators(Path.GetDirectoryName(assemblyFileLocation) ?? string.Empty)); InternalLogger.Debug("Auto loading based on NLog-Assembly found location: {0}", 5__2); if (!string.IsNullOrEmpty(5__2)) { <>2__current = new KeyValuePair(5__2, "nlogAssemblyLocation"); <>1__state = 1; return true; } goto IL_00a3; } case 1: <>1__state = -1; goto IL_00a3; case 2: <>1__state = -1; goto IL_010f; case 3: { <>1__state = -1; break; } IL_010f: text = PathHelpers.TrimDirectorySeparators(LogFactory.DefaultAppEnvironment.AppDomainBaseDirectory); InternalLogger.Debug("Auto loading based on AppDomain-BaseDirectory found location: {0}", text); if (!string.IsNullOrEmpty(text) && !string.Equals(text, 5__2, StringComparison.OrdinalIgnoreCase) && !string.Equals(text, 5__3, StringComparison.OrdinalIgnoreCase)) { <>2__current = new KeyValuePair(text, "baseDirectory"); <>1__state = 3; return true; } break; IL_00a3: 5__3 = PathHelpers.TrimDirectorySeparators(LogFactory.DefaultAppEnvironment.EntryAssemblyLocation); InternalLogger.Debug("Auto loading based on GetEntryAssembly-Assembly found location: {0}", 5__3); if (!string.IsNullOrEmpty(5__3) && !string.Equals(5__3, 5__2, StringComparison.OrdinalIgnoreCase)) { <>2__current = new KeyValuePair(5__3, "entryAssemblyLocation"); <>1__state = 2; return true; } goto IL_010f; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator> IEnumerable>.GetEnumerator() { if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; return this; } return new d__14(0); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable>)this).GetEnumerator(); } } [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] public void LoadAssemblyFromName(ConfigurationItemFactory factory, string assemblyName, string itemNamePrefix) { if (SkipAlreadyLoadedAssembly(factory, assemblyName, itemNamePrefix)) { InternalLogger.Debug("Skipped already loaded assembly name: {0}", assemblyName); return; } InternalLogger.Info("Loading assembly name: {0}{1}", assemblyName, string.IsNullOrEmpty(itemNamePrefix) ? "" : (" (Prefix=" + itemNamePrefix + ")")); Assembly assembly = LoadAssemblyFromName(assemblyName); LoadAssembly(factory, assembly, itemNamePrefix); } [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] public void LoadAssembly(ConfigurationItemFactory factory, Assembly assembly, string itemNamePrefix) { AssemblyHelpers.LogAssemblyVersion(assembly); InternalLogger.Debug("ScanAssembly('{0}')", assembly.FullName); Type[] array = SafeGetTypes(assembly); if (array != null && array.Length != 0) { if ((object)assembly == typeof(LogFactory).Assembly) { array = array.Where((Type t) => t.IsPublic && t.IsClass).ToArray(); } Type[] array2 = array; foreach (Type type in array2) { try { RegisterTypeFromAssembly(factory, type, itemNamePrefix); } catch (Exception ex) { InternalLogger.Error(ex, "Failed to add type '{0}'.", new ReadOnlySpan(new object[1] { type.FullName })); if (ex.MustBeRethrown()) { throw; } } } } InternalLogger.Debug("Loading assembly name: {0} succeeded!", assembly.FullName); } [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] private static Type[] SafeGetTypes(Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { Type[] array = ex.Types?.Where((Type t) => t != null).ToArray() ?? ArrayHelper.Empty(); InternalLogger.Warn(ex, "Loaded {0} valid types from Assembly: {1}", new ReadOnlySpan(new object[2] { array.Length, assembly.FullName })); Exception[] array2 = ex.LoaderExceptions ?? ArrayHelper.Empty(); for (int i = 0; i < array2.Length; i++) { InternalLogger.Warn(array2[i], "Type load exception."); } return array; } catch (Exception ex2) { InternalLogger.Warn(ex2, "Failed to load types from Assembly: {0}", new ReadOnlySpan(new object[1] { assembly.FullName })); return ArrayHelper.Empty(); } } [UnconditionalSuppressMessage("Trimming - Allow extension loading from config", "IL2072")] [UnconditionalSuppressMessage("Trimming - Allow extension loading from config", "IL2067")] private static void RegisterTypeFromAssembly(ConfigurationItemFactory factory, Type type, string itemNamePrefix) { factory.RegisterType(type, itemNamePrefix); } private static bool SkipAlreadyLoadedAssembly(ConfigurationItemFactory factory, string assemblyName, string itemNamePrefix) { try { Dictionary dictionary = ResolveLoadedAssemblyTypes(factory); if (dictionary.Count > 1) { foreach (KeyValuePair item in dictionary) { if (string.Equals(item.Key.GetName()?.Name, assemblyName, StringComparison.OrdinalIgnoreCase) && IsNLogItemTypeAlreadyRegistered(factory, item.Value, itemNamePrefix)) { return true; } } } } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } InternalLogger.Warn(ex, "Failed checking loading assembly name: {0}", new ReadOnlySpan(new object[1] { assemblyName })); } return false; } private static Dictionary ResolveLoadedAssemblyTypes(ConfigurationItemFactory factory) { Dictionary dictionary = new Dictionary(); foreach (Type itemType in factory.ItemTypes) { Assembly assembly = itemType.Assembly; if ((object)assembly == null) { continue; } if (dictionary.TryGetValue(assembly, out var value)) { if ((object)value == null && IsNLogConfigurationItemType(itemType)) { dictionary[assembly] = itemType; } } else { dictionary.Add(assembly, IsNLogConfigurationItemType(itemType) ? itemType : null); } } return dictionary; } private static bool IsNLogConfigurationItemType(Type? itemType) { if ((object)itemType == null) { return false; } if (typeof(Layout).IsAssignableFrom(itemType)) { return !string.IsNullOrEmpty(itemType.GetFirstCustomAttribute()?.Name); } if (typeof(LayoutRenderer).IsAssignableFrom(itemType)) { return !string.IsNullOrEmpty(itemType.GetFirstCustomAttribute()?.Name); } if (typeof(Target).IsAssignableFrom(itemType)) { return !string.IsNullOrEmpty(itemType.GetFirstCustomAttribute()?.Name); } if (typeof(Filter).IsAssignableFrom(itemType)) { return !string.IsNullOrEmpty(itemType.GetFirstCustomAttribute()?.Name); } return false; } private static bool IsNLogItemTypeAlreadyRegistered(ConfigurationItemFactory factory, Type? itemType, string itemNamePrefix) { if ((object)itemType == null) { return false; } if (typeof(Layout).IsAssignableFrom(itemType)) { return IsNLogItemTypeAlreadyRegistered(factory.LayoutFactory, itemType, itemNamePrefix); } if (typeof(LayoutRenderer).IsAssignableFrom(itemType)) { return IsNLogItemTypeAlreadyRegistered(factory.LayoutRendererFactory, itemType, itemNamePrefix); } if (typeof(Target).IsAssignableFrom(itemType)) { return IsNLogItemTypeAlreadyRegistered(factory.TargetFactory, itemType, itemNamePrefix); } if (typeof(Filter).IsAssignableFrom(itemType)) { return IsNLogItemTypeAlreadyRegistered(factory.FilterFactory, itemType, itemNamePrefix); } return false; } private static bool IsNLogItemTypeAlreadyRegistered(IFactory factory, Type itemType, string itemNamePrefix) where TBaseType : class where TAttribute : NameBaseAttribute { string text = itemType.GetFirstCustomAttribute()?.Name ?? string.Empty; if (!string.IsNullOrEmpty(text)) { string typeAlias = (string.IsNullOrEmpty(itemNamePrefix) ? text : (itemNamePrefix + text)); TBaseType result; return factory.TryCreateInstance(typeAlias, out result); } return false; } [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] public void LoadAssemblyFromPath(ConfigurationItemFactory factory, string assemblyFileName, string? baseDirectory, string itemNamePrefix) { Assembly assembly = LoadAssemblyFromPath(assemblyFileName, baseDirectory); if (assembly != null) { LoadAssembly(factory, assembly, itemNamePrefix); } } [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] public void ScanForAutoLoadExtensions(ConfigurationItemFactory factory) { try { Assembly assembly = typeof(LogFactory).Assembly; string text = string.Empty; string[] array = ArrayHelper.Empty(); foreach (KeyValuePair autoLoadingFileLocation in GetAutoLoadingFileLocations()) { if (!string.IsNullOrEmpty(autoLoadingFileLocation.Key)) { if (string.IsNullOrEmpty(text)) { text = autoLoadingFileLocation.Key; } array = GetNLogExtensionFiles(autoLoadingFileLocation.Key); if (array.Length != 0) { text = autoLoadingFileLocation.Key; break; } } } InternalLogger.Debug("Start auto loading, location: {0}", text); HashSet alreadyRegistered = LoadNLogExtensionAssemblies(factory, assembly, array); RegisterAppDomainAssemblies(factory, assembly, alreadyRegistered); } catch (SecurityException ex) { InternalLogger.Warn(ex, "Seems that we do not have permission"); if (ex.MustBeRethrown()) { throw; } } catch (UnauthorizedAccessException ex2) { InternalLogger.Warn(ex2, "Seems that we do not have permission"); if (ex2.MustBeRethrown()) { throw; } } InternalLogger.Debug("Auto loading done"); } [RequiresUnreferencedCode("Assembly.LoadFrom() Incompatible with trimming.")] private HashSet LoadNLogExtensionAssemblies(ConfigurationItemFactory factory, Assembly nlogAssembly, string[] extensionDlls) { HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase) { nlogAssembly.FullName ?? string.Empty }; foreach (string text in extensionDlls) { try { Assembly assembly = LoadAssemblyFromPath(text); if (assembly != null) { LoadAssembly(factory, assembly, string.Empty); hashSet.Add(assembly.FullName ?? string.Empty); } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } InternalLogger.Warn(ex, "Auto loading assembly file: {0} failed! Skipping this file.", new ReadOnlySpan(new object[1] { text })); if (ex.MustBeRethrown()) { throw; } } } return hashSet; } [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] private void RegisterAppDomainAssemblies(ConfigurationItemFactory factory, Assembly nlogAssembly, HashSet alreadyRegistered) { alreadyRegistered.Add(nlogAssembly.FullName ?? string.Empty); foreach (Assembly appDomainRuntimeAssembly in LogFactory.DefaultAppEnvironment.GetAppDomainRuntimeAssemblies()) { if (appDomainRuntimeAssembly.FullName.StartsWith("NLog.", StringComparison.OrdinalIgnoreCase) && !alreadyRegistered.Contains(appDomainRuntimeAssembly.FullName)) { LoadAssembly(factory, appDomainRuntimeAssembly, string.Empty); } if (IncludeAsHiddenAssembly(appDomainRuntimeAssembly.FullName)) { LogManager.AddHiddenAssembly(appDomainRuntimeAssembly); } } } private static bool IncludeAsHiddenAssembly(string assemblyFullName) { if (assemblyFullName.StartsWith("NLog.Extensions.Logging,", StringComparison.OrdinalIgnoreCase)) { return true; } if (assemblyFullName.StartsWith("NLog.Web,", StringComparison.OrdinalIgnoreCase)) { return true; } if (assemblyFullName.StartsWith("NLog.Web.AspNetCore,", StringComparison.OrdinalIgnoreCase)) { return true; } if (assemblyFullName.StartsWith("Microsoft.Extensions.Logging,", StringComparison.OrdinalIgnoreCase)) { return true; } if (assemblyFullName.StartsWith("Microsoft.Extensions.Logging.Abstractions,", StringComparison.OrdinalIgnoreCase)) { return true; } if (assemblyFullName.StartsWith("Microsoft.Extensions.Logging.Filter,", StringComparison.OrdinalIgnoreCase)) { return true; } if (assemblyFullName.StartsWith("Microsoft.Logging,", StringComparison.OrdinalIgnoreCase)) { return true; } return false; } [IteratorStateMachine(typeof(d__14))] internal static IEnumerable> GetAutoLoadingFileLocations() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__14(-2); } private static string[] GetNLogExtensionFiles(string assemblyLocation) { string assemblyLocation2 = assemblyLocation; try { InternalLogger.Debug("Search for auto loading files in location: {0}", assemblyLocation2); if (string.IsNullOrEmpty(assemblyLocation2)) { return ArrayHelper.Empty(); } return (from x in Directory.GetFiles(assemblyLocation2, "NLog*.dll").Select(Path.GetFileName) where !x.Equals("NLog.dll", StringComparison.OrdinalIgnoreCase) where !x.Equals("NLog.UnitTests.dll", StringComparison.OrdinalIgnoreCase) select Path.Combine(assemblyLocation2, x)).ToArray(); } catch (DirectoryNotFoundException ex) { InternalLogger.Warn(ex, "Skipping auto loading location because assembly directory does not exist: {0}", new ReadOnlySpan(new object[1] { assemblyLocation2 })); if (ex.MustBeRethrown()) { throw; } return ArrayHelper.Empty(); } catch (SecurityException ex2) { InternalLogger.Warn(ex2, "Skipping auto loading location because access not allowed to assembly directory: {0}", new ReadOnlySpan(new object[1] { assemblyLocation2 })); if (ex2.MustBeRethrown()) { throw; } return ArrayHelper.Empty(); } catch (UnauthorizedAccessException ex3) { InternalLogger.Warn(ex3, "Skipping auto loading location because access not allowed to assembly directory: {0}", new ReadOnlySpan(new object[1] { assemblyLocation2 })); if (ex3.MustBeRethrown()) { throw; } return ArrayHelper.Empty(); } } [RequiresUnreferencedCode("Assembly.LoadFrom() Incompatible with trimming.")] private static Assembly LoadAssemblyFromPath(string assemblyFileName, string? baseDirectory = null) { string text = assemblyFileName; if (!string.IsNullOrEmpty(baseDirectory)) { text = Path.Combine(baseDirectory, assemblyFileName); } InternalLogger.Info("Loading assembly file: {0}", text); return Assembly.LoadFrom(text); } private static Assembly LoadAssemblyFromName(string assemblyName) { try { return Assembly.Load(assemblyName); } catch (FileNotFoundException) { AssemblyName name = new AssemblyName(assemblyName); InternalLogger.Trace("Try find '{0}' in current domain", assemblyName); Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly domainAssembly) => IsAssemblyMatch(name, domainAssembly.GetName())); if (assembly != null) { InternalLogger.Trace("Found '{0}' in current domain", assemblyName); return assembly; } InternalLogger.Trace("Haven't found' '{0}' in current domain", assemblyName); throw; } } private static bool IsAssemblyMatch(AssemblyName expected, AssemblyName actual) { if (expected == null || actual == null) { return false; } if (expected.Name != actual.Name) { return false; } if (expected.Version != null && expected.Version != actual.Version) { return false; } if (expected.CultureInfo != null && expected.CultureInfo.Name != actual.CultureInfo.Name) { return false; } return expected.GetPublicKeyToken()?.SequenceEqual(actual.GetPublicKeyToken()) ?? true; } } internal interface IAssemblyExtensionLoader { [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] void ScanForAutoLoadExtensions(ConfigurationItemFactory factory); [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] void LoadAssemblyFromPath(ConfigurationItemFactory factory, string assemblyFileName, string? baseDirectory, string itemNamePrefix); [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] void LoadAssemblyFromName(ConfigurationItemFactory factory, string assemblyName, string itemNamePrefix); [RequiresUnreferencedCode("Assembly.GetTypes() Incompatible with trimming.")] void LoadAssembly(ConfigurationItemFactory factory, Assembly assembly, string itemNamePrefix); } internal static class AssemblyExtensionTypes { public static void RegisterTargetTypes(ConfigurationItemFactory factory, bool checkTypeExists) { Factory targetFactory = factory.GetTargetFactory(); factory.RegisterTypeProperties(() => null); targetFactory.RegisterType("ColoredConsole", checkTypeExists); factory.RegisterType(); targetFactory.RegisterType("Console", checkTypeExists); factory.RegisterType(); targetFactory.RegisterType("Debugger", checkTypeExists); targetFactory.RegisterType("DebugSystem", checkTypeExists); targetFactory.RegisterType("Debug", checkTypeExists); targetFactory.RegisterType("File", checkTypeExists); targetFactory.RegisterType("Memory", checkTypeExists); factory.RegisterType(); targetFactory.RegisterType("MethodCall", checkTypeExists); targetFactory.RegisterType("Null", checkTypeExists); factory.RegisterType(); targetFactory.RegisterType("AsyncWrapper", checkTypeExists); targetFactory.RegisterType("AutoFlushWrapper", checkTypeExists); targetFactory.RegisterType("BufferingWrapper", checkTypeExists); targetFactory.RegisterType("FallbackGroup", checkTypeExists); factory.RegisterType(); targetFactory.RegisterType("FilteringWrapper", checkTypeExists); targetFactory.RegisterType("GroupByWrapper", checkTypeExists); targetFactory.RegisterType("LimitingWrapper", checkTypeExists); targetFactory.RegisterType("PostFilteringWrapper", checkTypeExists); targetFactory.RegisterType("RandomizeGroup", checkTypeExists); targetFactory.RegisterType("RepeatingWrapper", checkTypeExists); targetFactory.RegisterType("RetryingWrapper", checkTypeExists); targetFactory.RegisterType("RoundRobinGroup", checkTypeExists); targetFactory.RegisterType("SplitGroup", checkTypeExists); } public static void RegisterLayoutTypes(ConfigurationItemFactory factory, bool checkTypeExists) { Factory layoutFactory = factory.GetLayoutFactory(); factory.RegisterTypeProperties(() => null); layoutFactory.RegisterType("CompoundLayout", checkTypeExists); factory.RegisterType(); layoutFactory.RegisterType("CsvLayout", checkTypeExists); layoutFactory.RegisterType("JsonArrayLayout", checkTypeExists); factory.RegisterType(); layoutFactory.RegisterType("JsonLayout", checkTypeExists); layoutFactory.RegisterType("LayoutWithHeaderAndFooter", checkTypeExists); layoutFactory.RegisterType("SimpleLayout", checkTypeExists); factory.RegisterType(); factory.RegisterType(); layoutFactory.RegisterType("XmlLayout", checkTypeExists); } public static void RegisterLayoutRendererTypes(ConfigurationItemFactory factory, bool checkTypeExists) { LayoutRendererFactory layoutRendererFactory = factory.GetLayoutRendererFactory(); Factory ambientPropertyFactory = factory.GetAmbientPropertyFactory(); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); layoutRendererFactory.RegisterType("alleventproperties", checkTypeExists); layoutRendererFactory.RegisterType("appdomain", checkTypeExists); layoutRendererFactory.RegisterType("assemblyversion", checkTypeExists); layoutRendererFactory.RegisterType("basedir", checkTypeExists); layoutRendererFactory.RegisterType("callsitefilename", checkTypeExists); layoutRendererFactory.RegisterType("callsite", checkTypeExists); layoutRendererFactory.RegisterType("callsitelinenumber", checkTypeExists); layoutRendererFactory.RegisterType("counter", checkTypeExists); layoutRendererFactory.RegisterType("currentdir", checkTypeExists); layoutRendererFactory.RegisterType("date", checkTypeExists); layoutRendererFactory.RegisterType("dbnull", checkTypeExists); layoutRendererFactory.RegisterType("dirseparator", checkTypeExists); layoutRendererFactory.RegisterType("environment", checkTypeExists); layoutRendererFactory.RegisterType("environmentuser", checkTypeExists); layoutRendererFactory.RegisterType("eventproperties", checkTypeExists); layoutRendererFactory.RegisterType("eventproperty", checkTypeExists); layoutRendererFactory.RegisterType("eventcontext", checkTypeExists); layoutRendererFactory.RegisterType("exceptiondata", checkTypeExists); layoutRendererFactory.RegisterType("exception", checkTypeExists); layoutRendererFactory.RegisterType("gc", checkTypeExists); layoutRendererFactory.RegisterType("gdc", checkTypeExists); layoutRendererFactory.RegisterType("guid", checkTypeExists); layoutRendererFactory.RegisterType("hostname", checkTypeExists); layoutRendererFactory.RegisterType("identity", checkTypeExists); layoutRendererFactory.RegisterType("installcontext", checkTypeExists); layoutRendererFactory.RegisterType("level", checkTypeExists); layoutRendererFactory.RegisterType("loglevel", checkTypeExists); layoutRendererFactory.RegisterType("literal", checkTypeExists); layoutRendererFactory.RegisterType("loggername", checkTypeExists); layoutRendererFactory.RegisterType("logger", checkTypeExists); layoutRendererFactory.RegisterType("longdate", checkTypeExists); layoutRendererFactory.RegisterType("machinename", checkTypeExists); layoutRendererFactory.RegisterType("message", checkTypeExists); layoutRendererFactory.RegisterType("newline", checkTypeExists); layoutRendererFactory.RegisterType("nlogdir", checkTypeExists); layoutRendererFactory.RegisterType("processdir", checkTypeExists); layoutRendererFactory.RegisterType("processid", checkTypeExists); layoutRendererFactory.RegisterType("processinfo", checkTypeExists); layoutRendererFactory.RegisterType("processname", checkTypeExists); layoutRendererFactory.RegisterType("processtime", checkTypeExists); layoutRendererFactory.RegisterType("scopeindent", checkTypeExists); layoutRendererFactory.RegisterType("scopenested", checkTypeExists); layoutRendererFactory.RegisterType("ndc", checkTypeExists); layoutRendererFactory.RegisterType("ndlc", checkTypeExists); layoutRendererFactory.RegisterType("scopeproperty", checkTypeExists); layoutRendererFactory.RegisterType("mdc", checkTypeExists); layoutRendererFactory.RegisterType("mdlc", checkTypeExists); layoutRendererFactory.RegisterType("scopetiming", checkTypeExists); layoutRendererFactory.RegisterType("ndlctiming", checkTypeExists); layoutRendererFactory.RegisterType("sequenceid", checkTypeExists); layoutRendererFactory.RegisterType("shortdate", checkTypeExists); layoutRendererFactory.RegisterType("userApplicationDataDir", checkTypeExists); layoutRendererFactory.RegisterType("commonApplicationDataDir", checkTypeExists); layoutRendererFactory.RegisterType("specialfolder", checkTypeExists); layoutRendererFactory.RegisterType("userLocalApplicationDataDir", checkTypeExists); layoutRendererFactory.RegisterType("stacktrace", checkTypeExists); layoutRendererFactory.RegisterType("tempdir", checkTypeExists); layoutRendererFactory.RegisterType("threadid", checkTypeExists); layoutRendererFactory.RegisterType("threadname", checkTypeExists); layoutRendererFactory.RegisterType("ticks", checkTypeExists); layoutRendererFactory.RegisterType("time", checkTypeExists); layoutRendererFactory.RegisterType("var", checkTypeExists); layoutRendererFactory.RegisterType("cached", checkTypeExists); ambientPropertyFactory.RegisterType("Cached", checkTypeExists); ambientPropertyFactory.RegisterType("ClearCache", checkTypeExists); ambientPropertyFactory.RegisterType("CachedSeconds", checkTypeExists); layoutRendererFactory.RegisterType("filesystemnormalize", checkTypeExists); ambientPropertyFactory.RegisterType("FSNormalize", checkTypeExists); layoutRendererFactory.RegisterType("jsonencode", checkTypeExists); ambientPropertyFactory.RegisterType("JsonEncode", checkTypeExists); layoutRendererFactory.RegisterType("left", checkTypeExists); ambientPropertyFactory.RegisterType("Truncate", checkTypeExists); layoutRendererFactory.RegisterType("lowercase", checkTypeExists); ambientPropertyFactory.RegisterType("Lowercase", checkTypeExists); ambientPropertyFactory.RegisterType("ToLower", checkTypeExists); layoutRendererFactory.RegisterType("norawvalue", checkTypeExists); ambientPropertyFactory.RegisterType("NoRawValue", checkTypeExists); layoutRendererFactory.RegisterType("ObjectPath", checkTypeExists); ambientPropertyFactory.RegisterType("ObjectPath", checkTypeExists); layoutRendererFactory.RegisterType("onexception", checkTypeExists); layoutRendererFactory.RegisterType("onhasproperties", checkTypeExists); layoutRendererFactory.RegisterType("pad", checkTypeExists); ambientPropertyFactory.RegisterType("Padding", checkTypeExists); ambientPropertyFactory.RegisterType("PadCharacter", checkTypeExists); ambientPropertyFactory.RegisterType("FixedLength", checkTypeExists); ambientPropertyFactory.RegisterType("AlignmentOnTruncation", checkTypeExists); layoutRendererFactory.RegisterType("replace", checkTypeExists); layoutRendererFactory.RegisterType("replacenewlines", checkTypeExists); ambientPropertyFactory.RegisterType("ReplaceNewLines", checkTypeExists); layoutRendererFactory.RegisterType("right", checkTypeExists); layoutRendererFactory.RegisterType("rot13", checkTypeExists); layoutRendererFactory.RegisterType("substring", checkTypeExists); layoutRendererFactory.RegisterType("trimwhitespace", checkTypeExists); ambientPropertyFactory.RegisterType("TrimWhiteSpace", checkTypeExists); layoutRendererFactory.RegisterType("uppercase", checkTypeExists); ambientPropertyFactory.RegisterType("Uppercase", checkTypeExists); ambientPropertyFactory.RegisterType("ToUpper", checkTypeExists); layoutRendererFactory.RegisterType("urlencode", checkTypeExists); layoutRendererFactory.RegisterType("whenEmpty", checkTypeExists); ambientPropertyFactory.RegisterType("WhenEmpty", checkTypeExists); layoutRendererFactory.RegisterType("when", checkTypeExists); ambientPropertyFactory.RegisterType("When", checkTypeExists); layoutRendererFactory.RegisterType("wrapline", checkTypeExists); ambientPropertyFactory.RegisterType("WrapLine", checkTypeExists); layoutRendererFactory.RegisterType("xmlencode", checkTypeExists); ambientPropertyFactory.RegisterType("XmlEncode", checkTypeExists); } public static void RegisterFilterTypes(ConfigurationItemFactory factory, bool checkTypeExists) { Factory filterFactory = factory.GetFilterFactory(); filterFactory.RegisterType("when", checkTypeExists); filterFactory.RegisterType("whenContains", checkTypeExists); filterFactory.RegisterType("whenEqual", checkTypeExists); filterFactory.RegisterType("whenNotContains", checkTypeExists); filterFactory.RegisterType("whenNotEqual", checkTypeExists); filterFactory.RegisterType("whenRepeated", checkTypeExists); } public static void RegisterTimeSourceTypes(ConfigurationItemFactory factory, bool checkTypeExists) { Factory timeSourceFactory = factory.GetTimeSourceFactory(); timeSourceFactory.RegisterType("AccurateLocal", checkTypeExists); timeSourceFactory.RegisterType("AccurateUTC", checkTypeExists); timeSourceFactory.RegisterType("FastLocal", checkTypeExists); timeSourceFactory.RegisterType("FastUTC", checkTypeExists); } public static void RegisterConditionTypes(ConfigurationItemFactory factory, bool checkTypeExists) { MethodFactory conditionMethodFactory = factory.GetConditionMethodFactory(); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); factory.RegisterTypeProperties(() => null); if (!checkTypeExists || !conditionMethodFactory.CheckTypeAliasExists("length")) { conditionMethodFactory.RegisterOneParameter("length", (LogEventInfo logEvent, object? arg1) => ConditionMethods.Length(arg1?.ToString())); } if (!checkTypeExists || !conditionMethodFactory.CheckTypeAliasExists("equals")) { conditionMethodFactory.RegisterTwoParameters("equals", (LogEventInfo logEvent, object? arg1, object? arg2) => (!ConditionMethods.Equals2(arg1?.ToString(), arg2?.ToString())) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); } if (!checkTypeExists || !conditionMethodFactory.CheckTypeAliasExists("strequals")) { conditionMethodFactory.RegisterTwoParameters("strequals", (LogEventInfo logEvent, object? arg1, object? arg2) => (!ConditionMethods.Equals2(arg1?.ToString(), arg2?.ToString())) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); conditionMethodFactory.RegisterThreeParameters("strequals", (LogEventInfo logEvent, object? arg1, object? arg2, object? arg3) => (!ConditionMethods.Equals2(arg1?.ToString(), arg2?.ToString(), !(arg3 is bool flag4) || flag4)) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); } if (!checkTypeExists || !conditionMethodFactory.CheckTypeAliasExists("contains")) { conditionMethodFactory.RegisterTwoParameters("contains", (LogEventInfo logEvent, object? arg1, object? arg2) => (!ConditionMethods.Contains(arg1?.ToString(), arg2?.ToString())) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); conditionMethodFactory.RegisterThreeParameters("contains", (LogEventInfo logEvent, object? arg1, object? arg2, object? arg3) => (!ConditionMethods.Contains(arg1?.ToString(), arg2?.ToString(), !(arg3 is bool flag3) || flag3)) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); } if (!checkTypeExists || !conditionMethodFactory.CheckTypeAliasExists("starts-with")) { conditionMethodFactory.RegisterTwoParameters("starts-with", (LogEventInfo logEvent, object? arg1, object? arg2) => (!ConditionMethods.StartsWith(arg1?.ToString(), arg2?.ToString())) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); conditionMethodFactory.RegisterThreeParameters("starts-with", (LogEventInfo logEvent, object? arg1, object? arg2, object? arg3) => (!ConditionMethods.StartsWith(arg1?.ToString(), arg2?.ToString(), !(arg3 is bool flag2) || flag2)) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); } if (!checkTypeExists || !conditionMethodFactory.CheckTypeAliasExists("ends-with")) { conditionMethodFactory.RegisterTwoParameters("ends-with", (LogEventInfo logEvent, object? arg1, object? arg2) => (!ConditionMethods.EndsWith(arg1?.ToString(), arg2?.ToString())) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); conditionMethodFactory.RegisterThreeParameters("ends-with", (LogEventInfo logEvent, object? arg1, object? arg2, object? arg3) => (!ConditionMethods.EndsWith(arg1?.ToString(), arg2?.ToString(), !(arg3 is bool flag) || flag)) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); } } } public sealed class ConfigurationItemFactory { private readonly struct ItemFactory { public readonly Func> ItemProperties; public readonly Func ItemCreator; public ItemFactory(Func> itemProperties, Func itemCreator) { ItemProperties = itemProperties; ItemCreator = itemCreator; } } private static ConfigurationItemFactory? _defaultInstance; internal static readonly object SyncRoot = new object(); private readonly ServiceRepository _serviceRepository; private readonly IFactory[] _allFactories; private readonly Factory _targets; private readonly Factory _filters; private readonly LayoutRendererFactory _layoutRenderers; private readonly Factory _layouts; private readonly MethodFactory _conditionMethods; private readonly Factory _ambientProperties; private readonly Factory _timeSources; private readonly Dictionary _itemFactories = new Dictionary(256); internal IAssemblyExtensionLoader AssemblyLoader { get; } = new AssemblyExtensionLoader(); public static ConfigurationItemFactory Default { get { return _defaultInstance ?? (_defaultInstance = new ConfigurationItemFactory(LogManager.LogFactory.ServiceRepository)); } set { _defaultInstance = value; } } public IFactory TargetFactory { get { if (!_targets.Initialized) { _targets.Initialize(delegate(bool checkTypeExists) { RegisterAllTargets(checkTypeExists); }); if (!_filters.Initialized) { _filters.Initialize(delegate(bool checkTypeExists) { RegisterAllFilters(checkTypeExists); }); } if (!_conditionMethods.Initialized) { _conditionMethods.Initialize(delegate(bool checkTypeExists) { RegisterAllConditionMethods(checkTypeExists); }); } if (!_layouts.Initialized) { _layouts.Initialize(delegate(bool checkTypeExists) { RegisterAllLayouts(checkTypeExists); }); } if (!_layoutRenderers.Initialized) { _layoutRenderers.Initialize(delegate(bool checkTypeExists) { RegisterAllLayoutRenderers(checkTypeExists); }); } } return _targets; } } public IFactory LayoutFactory { get { if (!_layouts.Initialized) { _layouts.Initialize(delegate(bool checkTypeExists) { RegisterAllLayouts(checkTypeExists); }); if (!_layoutRenderers.Initialized) { _layoutRenderers.Initialize(delegate(bool checkTypeExists) { RegisterAllLayoutRenderers(checkTypeExists); }); } if (!_conditionMethods.Initialized) { _conditionMethods.Initialize(delegate(bool checkTypeExists) { RegisterAllConditionMethods(checkTypeExists); }); } } return _layouts; } } public IFactory LayoutRendererFactory { get { if (!_layoutRenderers.Initialized) { _layoutRenderers.Initialize(delegate(bool checkTypeExists) { RegisterAllLayoutRenderers(checkTypeExists); }); } if (!_conditionMethods.Initialized) { _conditionMethods.Initialize(delegate(bool checkTypeExists) { RegisterAllConditionMethods(checkTypeExists); }); } return _layoutRenderers; } } public IFactory AmbientRendererFactory { get { if (!_layoutRenderers.Initialized) { _layoutRenderers.Initialize(delegate(bool checkTypeExists) { RegisterAllLayoutRenderers(checkTypeExists); }); } if (!_conditionMethods.Initialized) { _conditionMethods.Initialize(delegate(bool checkTypeExists) { RegisterAllConditionMethods(checkTypeExists); }); } return _ambientProperties; } } public IFactory FilterFactory { get { if (!_filters.Initialized) { _filters.Initialize(delegate(bool checkTypeExists) { RegisterAllFilters(checkTypeExists); }); } if (!_conditionMethods.Initialized) { _conditionMethods.Initialize(delegate(bool checkTypeExists) { RegisterAllConditionMethods(checkTypeExists); }); } return _filters; } } public IFactory TimeSourceFactory { get { if (!_timeSources.Initialized) { _timeSources.Initialize(delegate(bool checkTypeExists) { RegisterAllTimeSources(checkTypeExists); }); } return _timeSources; } } internal MethodFactory ConditionMethodFactory { get { if (!_conditionMethods.Initialized) { _conditionMethods.Initialize(delegate(bool checkTypeExists) { RegisterAllConditionMethods(checkTypeExists); }); } return _conditionMethods; } } internal ICollection ItemTypes { get { lock (SyncRoot) { return new List(_itemFactories.Keys); } } } [Obsolete("Instead use NLog.LogManager.Setup().SetupSerialization(s => s.RegisterJsonConverter()) or ResolveService(). Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public IJsonConverter JsonConverter { get { return _serviceRepository.GetService(); } set { _serviceRepository.RegisterJsonConverter(value); } } public bool? ParseMessageTemplates { get { return _serviceRepository.ResolveParseMessageTemplates(); } set { _serviceRepository.ParseMessageTemplates(LogManager.LogFactory, value); } } public ConfigurationItemFactory() : this(LogManager.LogFactory.ServiceRepository) { } internal ConfigurationItemFactory(ServiceRepository serviceRepository) { _serviceRepository = Guard.ThrowIfNull(serviceRepository, "serviceRepository"); _targets = new Factory(this); _filters = new Factory(this); _layoutRenderers = new LayoutRendererFactory(this); _layouts = new Factory(this); _conditionMethods = new MethodFactory(); _ambientProperties = new Factory(this); _timeSources = new Factory(this); _allFactories = new IFactory[7] { _targets, _filters, _layoutRenderers, _layouts, _conditionMethods, _ambientProperties, _timeSources }; RegisterType(); } internal Factory GetTargetFactory() { return _targets; } internal Factory GetLayoutFactory() { return _layouts; } internal LayoutRendererFactory GetLayoutRendererFactory() { return _layoutRenderers; } internal Factory GetAmbientPropertyFactory() { return _ambientProperties; } internal Factory GetFilterFactory() { return _filters; } internal Factory GetTimeSourceFactory() { return _timeSources; } internal MethodFactory GetConditionMethodFactory() { return _conditionMethods; } [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public void RegisterItemsFromAssembly(Assembly assembly) { AssemblyLoader.LoadAssembly(this, assembly, string.Empty); } [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public void RegisterItemsFromAssembly(Assembly assembly, string itemNamePrefix) { AssemblyLoader.LoadAssembly(this, assembly, itemNamePrefix); } public void Clear() { lock (SyncRoot) { IFactory[] allFactories = _allFactories; for (int i = 0; i < allFactories.Length; i++) { allFactories[i].Clear(); } } } [Obsolete("Instead use NLog.LogManager.Setup().SetupExtensions(). Marked obsolete with NLog v5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public void RegisterType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicProperties)] Type type, string? itemNamePrefix) { lock (SyncRoot) { IFactory[] allFactories = _allFactories; for (int i = 0; i < allFactories.Length; i++) { allFactories[i].RegisterType(type, itemNamePrefix ?? string.Empty); } } } internal void RegisterType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicProperties)] TType>() where TType : class, new() { lock (SyncRoot) { RegisterTypeProperties(() => new TType()); IFactory[] allFactories = _allFactories; for (int i = 0; i < allFactories.Length; i++) { allFactories[i].RegisterType(typeof(TType), string.Empty); } } } internal void RegisterTypeProperties<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] TType>(Func itemCreator) { lock (SyncRoot) { if (_itemFactories.ContainsKey(typeof(TType))) { return; } Dictionary properties = null; Func> itemProperties = () => properties ?? (properties = typeof(TType).GetProperties(BindingFlags.Instance | BindingFlags.Public).ToDictionary((PropertyInfo p) => p.Name, StringComparer.OrdinalIgnoreCase)); ItemFactory value = new ItemFactory(itemProperties, itemCreator); _itemFactories[typeof(TType)] = value; } } internal void RegisterTypeProperties([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type itemType, Func itemCreator) { Type itemType2 = itemType; lock (SyncRoot) { if (_itemFactories.ContainsKey(itemType2)) { return; } Dictionary properties = null; Func> itemProperties = () => properties ?? (properties = itemType2.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToDictionary((PropertyInfo p) => p.Name, StringComparer.OrdinalIgnoreCase)); ItemFactory value = new ItemFactory(itemProperties, itemCreator); _itemFactories[itemType2] = value; } } internal Dictionary TryGetTypeProperties(Type itemType) { lock (SyncRoot) { if (_itemFactories.TryGetValue(itemType, out var value)) { return value.ItemProperties(); } } if (itemType.IsAbstract) { return new Dictionary(); } if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(Layout<>)) { return new Dictionary(); } InternalLogger.Debug("Object reflection needed to configure instance of type: {0}", itemType); return ResolveTypePropertiesLegacy(itemType); } [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2067")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2070")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2072")] [Obsolete("Instead use RegisterType, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private Dictionary ResolveTypePropertiesLegacy(Type itemType) { Type itemType2 = itemType; Dictionary properties = itemType2.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToDictionary((PropertyInfo p) => p.Name, StringComparer.OrdinalIgnoreCase); lock (SyncRoot) { _itemFactories[itemType2] = new ItemFactory(() => properties, () => Activator.CreateInstance(itemType2)); } return properties; } internal bool TryCreateInstance(Type itemType, out object? instance) { Func func = null; lock (SyncRoot) { if (_itemFactories.TryGetValue(itemType, out var value)) { func = value.ItemCreator; } } if (func == null) { InternalLogger.Debug("Object reflection needed to create instance of type: {0}", itemType); instance = ResolveCreateInstanceLegacy(itemType); } else { instance = func(); } return instance != null; } [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2067")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2070")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2072")] [Obsolete("Instead use RegisterType, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] private object? ResolveCreateInstanceLegacy(Type itemType) { Type itemType2 = itemType; Dictionary properties = null; Func> itemProperties = () => properties ?? (properties = itemType2.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToDictionary((PropertyInfo p) => p.Name, StringComparer.OrdinalIgnoreCase)); ItemFactory value = new ItemFactory(itemProperties, () => Activator.CreateInstance(itemType2)); lock (SyncRoot) { _itemFactories[itemType2] = value; } return value.ItemCreator(); } private void RegisterAllTargets(bool checkTypeExists) { AssemblyExtensionTypes.RegisterTargetTypes(this, checkTypeExists); _targets.RegisterNamedType("diagnosticlistener", "NLog.Targets.DiagnosticListenerTarget, NLog.DiagnosticSource", checkTypeExists); _targets.RegisterNamedType("database", "NLog.Targets.DatabaseTarget, NLog.Database", checkTypeExists); _targets.RegisterNamedType("atomfile", "NLog.Targets.AtomicFileTarget, NLog.Targets.AtomicFile", checkTypeExists); _targets.RegisterNamedType("atomicfile", "NLog.Targets.AtomicFileTarget, NLog.Targets.AtomicFile", checkTypeExists); _targets.RegisterNamedType("eventlog", "NLog.Targets.EventLogTarget, NLog.WindowsEventLog", checkTypeExists); _targets.RegisterNamedType("gzipfile", "NLog.Targets.GZipFileTarget, NLog.Targets.GZipFile", checkTypeExists); _targets.RegisterNamedType("impersonatingwrapper", "NLog.Targets.Wrappers.ImpersonatingTargetWrapper, NLog.WindowsIdentity", checkTypeExists); _targets.RegisterNamedType("logreceiverservice", "NLog.Targets.LogReceiverWebServiceTarget, NLog.Wcf", checkTypeExists); _targets.RegisterNamedType("outputdebugstring", "NLog.Targets.OutputDebugStringTarget, NLog.OutputDebugString", checkTypeExists); _targets.RegisterNamedType("network", "NLog.Targets.NetworkTarget, NLog.Targets.Network", checkTypeExists); _targets.RegisterNamedType("log4jxml", "NLog.Targets.Log4JXmlTarget, NLog.Targets.Network", checkTypeExists); _targets.RegisterNamedType("chainsaw", "NLog.Targets.Log4JXmlTarget, NLog.Targets.Network", checkTypeExists); _targets.RegisterNamedType("nlogviewer", "NLog.Targets.Log4JXmlTarget, NLog.Targets.Network", checkTypeExists); _targets.RegisterNamedType("syslog", "NLog.Targets.SyslogTarget, NLog.Targets.Network", checkTypeExists); _targets.RegisterNamedType("gelf", "NLog.Targets.GelfTarget, NLog.Targets.Network", checkTypeExists); _targets.RegisterNamedType("mail", "NLog.Targets.MailTarget, NLog.Targets.Mail", checkTypeExists); _targets.RegisterNamedType("email", "NLog.Targets.MailTarget, NLog.Targets.Mail", checkTypeExists); _targets.RegisterNamedType("smtp", "NLog.Targets.MailTarget, NLog.Targets.Mail", checkTypeExists); _targets.RegisterNamedType("mailkit", "NLog.MailKit.MailTarget, NLog.MailKit", checkTypeExists); _targets.RegisterNamedType("performancecounter", "NLog.Targets.PerformanceCounterTarget, NLog.PerformanceCounter", checkTypeExists); _targets.RegisterNamedType("richtextbox", "NLog.Windows.Forms.RichTextBoxTarget, NLog.Windows.Forms", checkTypeExists); _targets.RegisterNamedType("messagebox", "NLog.Windows.Forms.MessageBoxTarget, NLog.Windows.Forms", checkTypeExists); _targets.RegisterNamedType("formcontrol", "NLog.Windows.Forms.FormControlTarget, NLog.Windows.Forms", checkTypeExists); _targets.RegisterNamedType("toolstripitem", "NLog.Windows.Forms.ToolStripItemTarget, NLog.Windows.Forms", checkTypeExists); _targets.RegisterNamedType("trace", "NLog.Targets.TraceTarget, NLog.Targets.Trace", checkTypeExists); _targets.RegisterNamedType("tracesystem", "NLog.Targets.TraceTarget, NLog.Targets.Trace", checkTypeExists); _targets.RegisterNamedType("webservice", "NLog.Targets.WebServiceTarget, NLog.Targets.WebService", checkTypeExists); } private void RegisterAllLayouts(bool checkTypeExists) { AssemblyExtensionTypes.RegisterLayoutTypes(this, checkTypeExists); _layouts.RegisterNamedType("microsoftconsolejsonlayout", "NLog.Extensions.Logging.MicrosoftConsoleJsonLayout, NLog.Extensions.Logging", checkTypeExists); _layouts.RegisterNamedType("sysloglayout", "NLog.Targets.SyslogLayout, NLog.Targets.Network", checkTypeExists); _layouts.RegisterNamedType("log4jxmllayout", "NLog.Targets.Log4JXmlEventLayout, NLog.Targets.Network", checkTypeExists); _layouts.RegisterNamedType("log4jxmleventlayout", "NLog.Targets.Log4JXmlEventLayout, NLog.Targets.Network", checkTypeExists); _layouts.RegisterNamedType("gelflayout", "NLog.Targets.GelfLayout, NLog.Targets.Network", checkTypeExists); } private void RegisterAllLayoutRenderers(bool checkTypeExists) { AssemblyExtensionTypes.RegisterLayoutRendererTypes(this, checkTypeExists); _layoutRenderers.RegisterNamedType("configsetting", "NLog.Extensions.Logging.ConfigSettingLayoutRenderer, NLog.Extensions.Logging", checkTypeExists); _layoutRenderers.RegisterNamedType("microsoftconsolelayout", "NLog.Extensions.Logging.MicrosoftConsoleLayoutRenderer, NLog.Extensions.Logging", checkTypeExists); _layoutRenderers.RegisterNamedType("hostappname", "NLog.Extensions.Hosting.HostAppNameLayoutRenderer, NLog.Extensions.Hosting", checkTypeExists); _layoutRenderers.RegisterNamedType("hostenvironment", "NLog.Extensions.Hosting.HostEnvironmentLayoutRenderer, NLog.Extensions.Hosting", checkTypeExists); _layoutRenderers.RegisterNamedType("hostrootdir", "NLog.Extensions.Hosting.HostRootDirLayoutRenderer, NLog.Extensions.Hosting", checkTypeExists); _layoutRenderers.RegisterNamedType("localip", "NLog.LayoutRenderers.LocalIpAddressLayoutRenderer, NLog.Targets.Network", checkTypeExists); _layoutRenderers.RegisterNamedType("performancecounter", "NLog.LayoutRenderers.PerformanceCounterLayoutRenderer, NLog.PerformanceCounter", checkTypeExists); _layoutRenderers.RegisterNamedType("registry", "NLog.LayoutRenderers.RegistryLayoutRenderer, NLog.WindowsRegistry", checkTypeExists); _layoutRenderers.RegisterNamedType("regexreplace", "NLog.LayoutRenderers.RegexReplaceLayoutRendererWrapper, NLog.RegEx", checkTypeExists); _layoutRenderers.RegisterNamedType("windowsidentity", "NLog.LayoutRenderers.WindowsIdentityLayoutRenderer, NLog.WindowsIdentity", checkTypeExists); _layoutRenderers.RegisterNamedType("rtblink", "NLog.Windows.Forms.RichTextBoxLinkLayoutRenderer, NLog.Windows.Forms", checkTypeExists); _layoutRenderers.RegisterNamedType("activity", "NLog.LayoutRenderers.ActivityTraceLayoutRenderer, NLog.DiagnosticSource", checkTypeExists); _layoutRenderers.RegisterNamedType("activityid", "NLog.LayoutRenderers.TraceActivityIdLayoutRenderer, NLog.Targets.Trace", checkTypeExists); } private void RegisterAllFilters(bool checkTypeExists) { AssemblyExtensionTypes.RegisterFilterTypes(this, checkTypeExists); } private void RegisterAllConditionMethods(bool checkTypeExists) { AssemblyExtensionTypes.RegisterConditionTypes(this, checkTypeExists); } private void RegisterAllTimeSources(bool checkTypeExists) { AssemblyExtensionTypes.RegisterTimeSourceTypes(this, checkTypeExists); } } [AttributeUsage(AttributeTargets.Property)] [MeansImplicitUse] public sealed class DefaultParameterAttribute : Attribute { } internal sealed class DynamicLogLevelFilter : ILoggingRuleLevelFilter { private readonly LoggingRule _loggingRule; private readonly SimpleLayout? _levelFilter; private readonly SimpleLayout? _finalMinLevelFilter; private KeyValuePair _activeFilter; public bool[] LogLevels => GenerateLogLevels(); public LogLevel? FinalMinLevel => GenerateFinalMinLevel(); public DynamicLogLevelFilter(LoggingRule loggingRule, SimpleLayout? levelFilter, SimpleLayout? finalMinLevelFilter) { _loggingRule = loggingRule; _levelFilter = levelFilter; _finalMinLevelFilter = finalMinLevelFilter; _activeFilter = new KeyValuePair(string.Empty, LoggingRuleLevelFilter.Off.LogLevels); } public LoggingRuleLevelFilter GetSimpleFilterForUpdate() { return new LoggingRuleLevelFilter(LogLevels, FinalMinLevel); } private bool[] GenerateLogLevels() { string text = _levelFilter?.Render(LogEventInfo.CreateNullEvent())?.Trim() ?? string.Empty; if (string.IsNullOrEmpty(text)) { return LoggingRuleLevelFilter.Off.LogLevels; } KeyValuePair keyValuePair = _activeFilter; if (keyValuePair.Key != text) { bool[] array = ((text.IndexOf(',') < 0) ? ParseSingleLevel(text) : ParseLevels(text)); if (array == LoggingRuleLevelFilter.Off.LogLevels) { return array; } keyValuePair = (_activeFilter = new KeyValuePair(text, array)); } return keyValuePair.Value; } private LogLevel? GenerateFinalMinLevel() { string logLevel = _finalMinLevelFilter?.Render(LogEventInfo.CreateNullEvent())?.Trim() ?? string.Empty; return ParseLogLevel(logLevel, null); } private bool[] ParseSingleLevel(string levelFilter) { LogLevel logLevel = ParseLogLevel(levelFilter, null); if ((object)logLevel == null || logLevel == LogLevel.Off) { return LoggingRuleLevelFilter.Off.LogLevels; } bool[] array = new bool[LogLevel.MaxLevel.Ordinal + 1]; array[logLevel.Ordinal] = true; return array; } private LogLevel? ParseLogLevel(string logLevel, LogLevel? levelIfEmpty) { try { if (string.IsNullOrEmpty(logLevel)) { return levelIfEmpty; } return LogLevel.FromString(logLevel); } catch (ArgumentException ex) { InternalLogger.Warn(ex, "Logging rule {0} with pattern '{1}' has invalid loglevel: {2}", new ReadOnlySpan(new object[3] { _loggingRule.RuleName, _loggingRule.LoggerNamePattern, logLevel })); return null; } } private bool[] ParseLevels(string levelFilter) { string[] array = levelFilter.SplitAndTrimTokens(','); if (array.Length == 0) { return LoggingRuleLevelFilter.Off.LogLevels; } if (array.Length == 1) { return ParseSingleLevel(array[0]); } bool[] array2 = new bool[LogLevel.MaxLevel.Ordinal + 1]; string[] array3 = array; foreach (string levelName in array3) { try { LogLevel logLevel = LogLevel.FromString(levelName); if (!(logLevel == LogLevel.Off)) { array2[logLevel.Ordinal] = true; } } catch (ArgumentException ex) { InternalLogger.Warn(ex, "Logging rule {0} with pattern '{1}' has invalid loglevel: {2}", new ReadOnlySpan(new object[3] { _loggingRule.RuleName, _loggingRule.LoggerNamePattern, levelFilter })); } } return array2; } } internal sealed class DynamicRangeLevelFilter : ILoggingRuleLevelFilter { private readonly struct MinMaxLevels : IEquatable { private readonly string _minLevel; private readonly string _maxLevel; public MinMaxLevels(string minLevel, string maxLevel) { _minLevel = minLevel; _maxLevel = maxLevel; } public bool Equals(MinMaxLevels other) { if (_minLevel == other._minLevel) { return _maxLevel == other._maxLevel; } return false; } } private readonly LoggingRule _loggingRule; private readonly SimpleLayout? _minLevel; private readonly SimpleLayout? _maxLevel; private readonly SimpleLayout? _finalMinLevelFilter; private KeyValuePair _activeFilter; public bool[] LogLevels => GenerateLogLevels(); public LogLevel? FinalMinLevel => GenerateFinalMinLevel(); public DynamicRangeLevelFilter(LoggingRule loggingRule, SimpleLayout? minLevel, SimpleLayout? maxLevel, SimpleLayout? finalMinLevelFilter) { _loggingRule = loggingRule; _minLevel = minLevel; _maxLevel = maxLevel; _finalMinLevelFilter = finalMinLevelFilter; _activeFilter = new KeyValuePair(new MinMaxLevels(string.Empty, string.Empty), LoggingRuleLevelFilter.Off.LogLevels); } public LoggingRuleLevelFilter GetSimpleFilterForUpdate() { return new LoggingRuleLevelFilter(LogLevels, FinalMinLevel); } private bool[] GenerateLogLevels() { string text = _minLevel?.Render(LogEventInfo.CreateNullEvent())?.Trim() ?? string.Empty; string text2 = _maxLevel?.Render(LogEventInfo.CreateNullEvent())?.Trim() ?? string.Empty; KeyValuePair keyValuePair = _activeFilter; if (!keyValuePair.Key.Equals(new MinMaxLevels(text, text2))) { bool[] value = ParseLevelRange(text, text2); keyValuePair = (_activeFilter = new KeyValuePair(new MinMaxLevels(text, text2), value)); } return keyValuePair.Value; } private LogLevel? GenerateFinalMinLevel() { string logLevel = _finalMinLevelFilter?.Render(LogEventInfo.CreateNullEvent())?.Trim() ?? string.Empty; return ParseLogLevel(logLevel, null); } private bool[] ParseLevelRange(string minLevelFilter, string maxLevelFilter) { if (string.IsNullOrEmpty(minLevelFilter) && string.IsNullOrEmpty(maxLevelFilter)) { return LoggingRuleLevelFilter.Off.LogLevels; } LogLevel logLevel = ParseLogLevel(minLevelFilter, LogLevel.MinLevel); LogLevel logLevel2 = ParseLogLevel(maxLevelFilter, LogLevel.MaxLevel); bool[] array = new bool[LogLevel.MaxLevel.Ordinal + 1]; if (logLevel != null && logLevel2 != null) { for (int i = logLevel.Ordinal; i <= array.Length - 1 && i <= logLevel2.Ordinal; i++) { array[i] = true; } } return array; } private LogLevel? ParseLogLevel(string logLevel, LogLevel? levelIfEmpty) { try { if (string.IsNullOrEmpty(logLevel)) { return levelIfEmpty; } return LogLevel.FromString(logLevel); } catch (ArgumentException ex) { InternalLogger.Warn(ex, "Logging rule {0} with pattern '{1}' has invalid loglevel: {2}", new ReadOnlySpan(new object[3] { _loggingRule.RuleName, _loggingRule.LoggerNamePattern, logLevel })); return null; } } } public enum ExceptionRenderingFormat { Message, Type, ShortType, ToString, Method, StackTrace, Data, Serialize, Source, HResult, Properties } internal class Factory : IFactory, IFactory where TBaseType : class where TAttributeType : NameBaseAttribute { private delegate Type GetTypeDelegate(); private readonly Dictionary> _items = new Dictionary>(16, StringComparer.OrdinalIgnoreCase); private readonly ConfigurationItemFactory _parentFactory; public bool Initialized { get; private set; } internal Factory(ConfigurationItemFactory parentFactory) { _parentFactory = parentFactory; } public void Initialize(Action itemRegistration) { lock (ConfigurationItemFactory.SyncRoot) { if (Initialized) { return; } try { bool obj = _items.Count != 0; itemRegistration(obj); } finally { Initialized = true; } } } public void RegisterType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] TType>(string typeAlias, bool checkTypeExists = false) where TType : TBaseType, new() { typeAlias = FactoryExtensions.NormalizeName(typeAlias); if (checkTypeExists && _items.ContainsKey(typeAlias)) { return; } lock (ConfigurationItemFactory.SyncRoot) { _parentFactory.RegisterTypeProperties(() => new TType()); _items[typeAlias] = () => (TBaseType)(object)new TType(); } } public void RegisterType<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] TType>(string typeAlias, Func itemCreator) where TType : TBaseType { Func itemCreator2 = itemCreator; typeAlias = FactoryExtensions.NormalizeName(typeAlias); lock (ConfigurationItemFactory.SyncRoot) { _parentFactory.RegisterTypeProperties(() => itemCreator2()); _items[typeAlias] = () => (TBaseType)(object)itemCreator2(); } } public void RegisterType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicProperties)] Type type, string itemNamePrefix) { if (!typeof(TBaseType).IsAssignableFrom(type)) { return; } IEnumerable customAttributes = type.GetCustomAttributes(inherit: false); if (customAttributes == null) { return; } foreach (TAttributeType item in customAttributes) { RegisterDefinition(type, item.Name, itemNamePrefix); } } [Obsolete("Instead use RegisterType, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] [UnconditionalSuppressMessage("Trimming - Ignore since obsolete", "IL2072")] public void RegisterNamedType(string itemName, string typeName, bool checkTypeExists = false) { string typeName2 = typeName; itemName = FactoryExtensions.NormalizeName(itemName); if (checkTypeExists && _items.ContainsKey(itemName)) { return; } Type itemType = null; GetTypeDelegate typeLookup = delegate { if ((object)itemType == null) { InternalLogger.Debug("Object reflection needed to resolve type: {0}", typeName2); itemType = PropertyTypeConverter.ConvertToType(typeName2, throwOnError: false); } return itemType; }; Func value = delegate { Type type = typeLookup(); return (!(type != null)) ? null : ((TBaseType)Activator.CreateInstance(type)); }; lock (ConfigurationItemFactory.SyncRoot) { _items[itemName] = value; } } public virtual void Clear() { lock (ConfigurationItemFactory.SyncRoot) { _items.Clear(); } } [Obsolete("Instead use RegisterType, as dynamic Assembly loading will be moved out. Marked obsolete with NLog v5.2")] public void RegisterDefinition(string typeAlias, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type itemType) { if (string.IsNullOrEmpty(typeAlias)) { throw new ArgumentException("Missing NLog " + typeof(TBaseType).Name + " type-alias", "typeAlias"); } if (!typeof(TBaseType).IsAssignableFrom(itemType)) { throw new ArgumentException("Not of type NLog " + typeof(TBaseType).Name, "itemType"); } RegisterDefinition(itemType, typeAlias, string.Empty); } private void RegisterDefinition([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicProperties)] Type itemType, string typeAlias, string itemNamePrefix) { Type itemType2 = itemType; typeAlias = FactoryExtensions.NormalizeName(typeAlias); Func itemCreator = () => (TBaseType)Activator.CreateInstance(itemType2); lock (ConfigurationItemFactory.SyncRoot) { _parentFactory.RegisterTypeProperties(itemType2, () => itemCreator()); _items[itemNamePrefix + typeAlias] = () => itemCreator(); } } private bool TryGetItemFactory(string typeAlias, out Func? itemFactory) { lock (ConfigurationItemFactory.SyncRoot) { return _items.TryGetValue(typeAlias, out itemFactory); } } public virtual bool TryCreateInstance(string typeAlias, out TBaseType? result) { typeAlias = FactoryExtensions.NormalizeName(typeAlias); if (!TryGetItemFactory(typeAlias, out Func itemFactory) || itemFactory == null) { result = null; return false; } result = itemFactory(); return result != null; } } internal static class FactoryExtensions { public static TBaseType CreateInstance(this IFactory factory, string typeAlias) where TBaseType : class { try { if (factory.TryCreateInstance(typeAlias, out TBaseType result)) { if (result == null) { throw new NLogConfigurationException("Failed to create " + typeof(TBaseType).Name + " of type: '" + typeAlias + "' - Factory method returned null"); } return result; } } catch (Exception ex) { throw new NLogConfigurationException("Failed to create " + typeof(TBaseType).Name + " of type: '" + typeAlias + "' - " + ex.Message, ex); } string text = NormalizeName(typeAlias); string text2 = "Failed to create " + typeof(TBaseType).Name + " with unknown type-alias: '" + typeAlias + "'"; text2 = ((!text.StartsWith("aspnet", StringComparison.OrdinalIgnoreCase) && !text.StartsWith("iis", StringComparison.OrdinalIgnoreCase)) ? (text.StartsWith("HostAppName", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Web.AspNetCore not included?") : (text.StartsWith("HostEnvironment", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Web.AspNetCore not included?") : (text.StartsWith("HostRootDir", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Web.AspNetCore not included?") : (text.StartsWith("configsetting", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Extensions.Logging not included?") : (text.StartsWith("MicrosoftConsoleJsonLayout", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Extensions.Logging not included?") : (text.StartsWith("MicrosoftConsoleLayout", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Extensions.Logging not included?") : (text.StartsWith("database", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Database not included?") : (text.StartsWith("network", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Network not included?") : (text.StartsWith("nlogviewer", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Network not included?") : (text.StartsWith("chainsaw", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Network not included?") : (text.StartsWith("Log4JXml", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Network not included?") : (text.StartsWith("syslog", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Network not included?") : (text.StartsWith("gelf", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Network not included?") : (text.StartsWith("localip", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Network not included?") : (text.StartsWith("webservice", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.WebService not included?") : ((text.StartsWith("atomFile", StringComparison.OrdinalIgnoreCase) || text.StartsWith("atomicFile", StringComparison.OrdinalIgnoreCase)) ? (text2 + " - Extension NLog.Targets.AtomicFile not included?") : (text.StartsWith("GZipFile", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.GZipFile not included?") : (text.StartsWith("trace", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Trace not included?") : (text.StartsWith("activityid", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Trace not included?") : (text.StartsWith("mailkit", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.MailKit not included?") : (text.StartsWith("mail", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.Targets.Mail not included?") : (text.StartsWith("eventlog", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.WindowsEventLog not included?") : (text.StartsWith("windowsidentity", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.WindowsIdentity not included?") : (text.StartsWith("outputdebugstring", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.OutputDebugString not included?") : (text.StartsWith("performancecounter", StringComparison.OrdinalIgnoreCase) ? (text2 + " - Extension NLog.PerformanceCounter not included?") : ((!text.StartsWith("regexreplace", StringComparison.OrdinalIgnoreCase)) ? (text2 + " - Verify type-alias and check extension is included.") : (text2 + " - Extension NLog.RegEx not included?"))))))))))))))))))))))))))) : (text2 + " - Extension NLog.Web.AspNetCore not included?")); throw new NLogConfigurationException(text2); } public static string NormalizeName(string itemName) { if (itemName == null) { return string.Empty; } if (itemName.IndexOf('-') < 0) { return itemName; } int num = itemName.IndexOf(','); if (num >= 0) { string text = itemName.Substring(0, num).Replace("-", string.Empty); string text2 = itemName.Substring(num); return text + text2; } return itemName.Replace("-", string.Empty); } } internal sealed class LayoutRendererFactory : Factory { private readonly Dictionary _funcRenderers = new Dictionary(StringComparer.OrdinalIgnoreCase); public LayoutRendererFactory(ConfigurationItemFactory parentFactory) : base(parentFactory) { } public override void Clear() { _funcRenderers.Clear(); base.Clear(); } public void RegisterFuncLayout(string itemName, FuncLayoutRenderer renderer) { itemName = FactoryExtensions.NormalizeName(itemName); lock (ConfigurationItemFactory.SyncRoot) { _funcRenderers[itemName] = renderer; } } public override bool TryCreateInstance(string typeAlias, out LayoutRenderer? result) { typeAlias = FactoryExtensions.NormalizeName(typeAlias); if (_funcRenderers.Count > 0) { lock (ConfigurationItemFactory.SyncRoot) { if (_funcRenderers.TryGetValue(typeAlias, out FuncLayoutRenderer value)) { result = value; return true; } } } return base.TryCreateInstance(typeAlias, out result); } } internal interface IFactory { void Clear(); void RegisterType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicProperties)] Type type, string itemNamePrefix); } public interface IFactory where TBaseType : class { bool TryCreateInstance(string typeAlias, out TBaseType? result); } internal interface IIncludeContext { bool IncludeEventProperties { get; set; } bool IncludeScopeProperties { get; set; } bool IncludeScopeNested { get; set; } } public interface IInstallable { void Install(InstallationContext installationContext); void Uninstall(InstallationContext installationContext); bool? IsInstalled(InstallationContext installationContext); } public interface ILoggingConfigurationElement { string Name { get; } IEnumerable> Values { get; } IEnumerable Children { get; } } internal interface ILoggingConfigurationLoader : IDisposable { LoggingConfiguration? Load(LogFactory logFactory, string? filename = null); IEnumerable GetDefaultCandidateConfigFilePaths(string? filename = null); } internal interface ILoggingRuleLevelFilter { bool[] LogLevels { get; } LogLevel? FinalMinLevel { get; } LoggingRuleLevelFilter GetSimpleFilterForUpdate(); } public sealed class InstallationContext : IDisposable { private static readonly Dictionary LogLevel2ConsoleColor = new Dictionary { { NLog.LogLevel.Trace, ConsoleColor.DarkGray }, { NLog.LogLevel.Debug, ConsoleColor.Gray }, { NLog.LogLevel.Info, ConsoleColor.White }, { NLog.LogLevel.Warn, ConsoleColor.Yellow }, { NLog.LogLevel.Error, ConsoleColor.Red }, { NLog.LogLevel.Fatal, ConsoleColor.DarkRed } }; public LogLevel LogLevel { get; set; } public bool IgnoreFailures { get; set; } public bool ThrowExceptions { get; set; } public IDictionary Parameters { get; } public TextWriter? LogOutput { get; set; } public InstallationContext() : this(TextWriter.Null) { } public InstallationContext(TextWriter logOutput) { LogOutput = logOutput; Parameters = new Dictionary(); LogLevel = NLog.LogLevel.Info; ThrowExceptions = false; } public void Trace([Localizable(false)] string message, params object[] arguments) { Log(NLog.LogLevel.Trace, message, arguments); } public void Debug([Localizable(false)] string message, params object[] arguments) { Log(NLog.LogLevel.Debug, message, arguments); } public void Info([Localizable(false)] string message, params object[] arguments) { Log(NLog.LogLevel.Info, message, arguments); } public void Warning([Localizable(false)] string message, params object[] arguments) { Log(NLog.LogLevel.Warn, message, arguments); } public void Error([Localizable(false)] string message, params object[] arguments) { Log(NLog.LogLevel.Error, message, arguments); } public void Dispose() { LogOutput?.Close(); LogOutput = null; } public LogEventInfo CreateLogEvent() { LogEventInfo logEventInfo = LogEventInfo.CreateNullEvent(); foreach (KeyValuePair parameter in Parameters) { logEventInfo.Properties.Add(parameter.Key, parameter.Value); } return logEventInfo; } private void Log(LogLevel logLevel, string message, object[] arguments) { if (logLevel >= LogLevel) { if (arguments != null && arguments.Length != 0) { message = string.Format(CultureInfo.InvariantCulture, message, arguments); } ConsoleColor foregroundColor = Console.ForegroundColor; Console.ForegroundColor = LogLevel2ConsoleColor[logLevel]; try { LogOutput?.WriteLine(message); } finally { Console.ForegroundColor = foregroundColor; } } } } public interface IPropertyTypeConverter { object? Convert(object? propertyValue, Type propertyType, string? format, IFormatProvider? formatProvider); } public interface ISetupBuilder { LogFactory LogFactory { get; } } public interface ISetupConfigurationLoggingRuleBuilder : ISetupConfigurationTargetBuilder { LoggingRule LoggingRule { get; } } public interface ISetupConfigurationTargetBuilder { LoggingConfiguration Configuration { get; } LogFactory LogFactory { get; } IList Targets { get; } } public interface ISetupExtensionsBuilder { LogFactory LogFactory { get; } } public interface ISetupInternalLoggerBuilder { LogFactory LogFactory { get; } } public interface ISetupLoadConfigurationBuilder { LogFactory LogFactory { get; } LoggingConfiguration Configuration { get; set; } } public interface ISetupLogFactoryBuilder { LogFactory LogFactory { get; } } public interface ISetupSerializationBuilder { LogFactory LogFactory { get; } } public interface IUsesStackTrace { StackTraceUsage StackTraceUsage { get; } } internal abstract class LoggerNameMatcher { private sealed class NoneLoggerNameMatcher : LoggerNameMatcher { public static readonly NoneLoggerNameMatcher Instance = new NoneLoggerNameMatcher(); protected override string MatchMode => "None"; private NoneLoggerNameMatcher() : base(string.Empty, null) { } public override bool NameMatches(string loggerName) { return false; } } private sealed class AllLoggerNameMatcher : LoggerNameMatcher { public static readonly AllLoggerNameMatcher Instance = new AllLoggerNameMatcher(); protected override string MatchMode => "All"; private AllLoggerNameMatcher() : base("*", null) { } public override bool NameMatches(string loggerName) { return true; } } private sealed class EqualsLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "Equals"; public EqualsLoggerNameMatcher(string pattern) : base(pattern, pattern) { } public override bool NameMatches(string loggerName) { if (loggerName == null || _matchingArgument == null) { return _matchingArgument == null; } return loggerName.Equals(_matchingArgument, StringComparison.Ordinal); } } private sealed class StartsWithLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "StartsWith"; public StartsWithLoggerNameMatcher(string pattern) : base(pattern, pattern.Substring(0, pattern.Length - 1)) { } public override bool NameMatches(string loggerName) { if (loggerName == null || _matchingArgument == null) { return _matchingArgument == null; } return loggerName.StartsWith(_matchingArgument, StringComparison.Ordinal); } } private sealed class EndsWithLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "EndsWith"; public EndsWithLoggerNameMatcher(string pattern) : base(pattern, pattern.Substring(1)) { } public override bool NameMatches(string loggerName) { if (loggerName == null || _matchingArgument == null) { return _matchingArgument == null; } return loggerName.EndsWith(_matchingArgument, StringComparison.Ordinal); } } private sealed class ContainsLoggerNameMatcher : LoggerNameMatcher { protected override string MatchMode => "Contains"; public ContainsLoggerNameMatcher(string pattern) : base(pattern, pattern.Substring(1, pattern.Length - 2)) { } public override bool NameMatches(string loggerName) { if (loggerName == null || _matchingArgument == null) { return _matchingArgument == null; } return loggerName.IndexOf(_matchingArgument, StringComparison.Ordinal) >= 0; } } private sealed class MultiplePatternLoggerNameMatcher : LoggerNameMatcher { private readonly string _wildCardPattern; protected override string MatchMode => "MultiplePattern"; public MultiplePatternLoggerNameMatcher(string pattern) : base(pattern, pattern) { _wildCardPattern = Guard.ThrowIfNull(pattern, "pattern"); } public override bool NameMatches(string loggerName) { return MatchingName(0, _wildCardPattern.Length, loggerName, 0, loggerName?.Length ?? 0); } private bool MatchingName(int wildcardStart, int wildcardEnd, string loggerName, int loggerNameStart, int loggerNameEnd) { for (int i = wildcardStart; i < wildcardEnd; i++) { char c = _wildCardPattern[i]; if (c == '*') { break; } if (loggerNameStart >= loggerNameEnd) { return false; } char c2 = loggerName[loggerNameStart]; if (c != '?' && c != c2) { return false; } loggerNameStart++; wildcardStart++; } for (int num = wildcardEnd - 1; num >= wildcardStart; num--) { char c3 = _wildCardPattern[num]; if (c3 == '*') { break; } if (loggerNameStart >= loggerNameEnd) { return false; } char c4 = loggerName[loggerNameEnd - 1]; if (c3 != '?' && c3 != c4) { return false; } loggerNameEnd--; wildcardEnd--; } char c5 = '*'; for (int j = wildcardStart; j < wildcardEnd; j++) { c5 = _wildCardPattern[j]; if (c5 != '*') { break; } wildcardStart++; } if (c5 == '*') { return true; } for (int k = loggerNameStart; k < loggerNameEnd; k++) { char c6 = loggerName[k]; if (c5 == '?' || c6 == c5) { return MatchingName(wildcardStart, wildcardEnd, loggerName, k, loggerNameEnd); } } return false; } } protected readonly string? _matchingArgument; private readonly string _toString; public static LoggerNameMatcher Off => NoneLoggerNameMatcher.Instance; public string Pattern { get; } protected abstract string MatchMode { get; } public static LoggerNameMatcher Create(string loggerNamePattern) { if (loggerNamePattern == null) { return NoneLoggerNameMatcher.Instance; } if (loggerNamePattern.Trim() == "*") { return AllLoggerNameMatcher.Instance; } int num = loggerNamePattern.IndexOf('*'); int num2 = loggerNamePattern.IndexOf('*', num + 1); int num3 = loggerNamePattern.IndexOf('?'); if (num < 0 && num3 < 0) { return new EqualsLoggerNameMatcher(loggerNamePattern); } if (num3 < 0) { if (num == 0 && num2 == loggerNamePattern.Length - 1) { return new ContainsLoggerNameMatcher(loggerNamePattern); } if (num == 0 && num2 < 0) { return new EndsWithLoggerNameMatcher(loggerNamePattern); } if (num == loggerNamePattern.Length - 1 && num2 < 0) { return new StartsWithLoggerNameMatcher(loggerNamePattern); } } return new MultiplePatternLoggerNameMatcher(loggerNamePattern); } protected LoggerNameMatcher(string pattern, string? matchingArgument) { Pattern = pattern; _matchingArgument = matchingArgument; _toString = "logNamePattern: (" + matchingArgument + ":" + MatchMode + ")"; } public override string ToString() { return _toString; } public abstract bool NameMatches(string loggerName); } public class LoggingConfiguration { private readonly IDictionary _targets = new Dictionary(StringComparer.OrdinalIgnoreCase); private List _configItems = new List(); private bool _missingServiceTypes; private readonly ConfigVariablesDictionary _variables; private readonly List _loggingRules = new List(); public LogFactory LogFactory { get; } public IDictionary Variables => _variables; public ReadOnlyCollection ConfiguredNamedTargets => GetAllTargetsThreadSafe().AsReadOnly(); [Obsolete("NLog LogFactory no longer supports FileWatcher. Marked obsolete with NLog v6")] [EditorBrowsable(EditorBrowsableState.Never)] public virtual IEnumerable FileNamesToWatch => ArrayHelper.Empty(); public IList LoggingRules => _loggingRules; public CultureInfo? DefaultCultureInfo { get; set; } public ReadOnlyCollection AllTargets => new HashSet(_configItems.OfType().Concat(GetAllTargetsThreadSafe()), SingleItemOptimizedHashSet.ReferenceEqualityComparer.Default).ToList().AsReadOnly(); public LoggingConfiguration() : this(LogManager.LogFactory) { } public LoggingConfiguration(LogFactory logFactory) { LogFactory = logFactory ?? LogManager.LogFactory; _variables = new ConfigVariablesDictionary(this); DefaultCultureInfo = LogFactory._defaultCultureInfo; } internal LoggingRule[] GetLoggingRulesThreadSafe() { lock (_loggingRules) { return _loggingRules.ToArray(); } } private void AddLoggingRulesThreadSafe(LoggingRule rule) { lock (_loggingRules) { _loggingRules.Add(rule); } } private bool TryGetTargetThreadSafe(string name, out Target? target) { lock (_targets) { return _targets.TryGetValue(name, out target); } } private List GetAllTargetsThreadSafe() { lock (_targets) { return _targets.Values.ToList(); } } private Target? RemoveTargetThreadSafe(string name) { Target value; lock (_targets) { if (_targets.TryGetValue(name, out value)) { _targets.Remove(name); } } if (value != null) { InternalLogger.Debug("Unregistered target {0}(Name={1})", value.GetType(), value.Name); } return value; } private void AddTargetThreadSafe(Target target, string? targetAlias = null) { lock (_targets) { if (targetAlias == null || string.IsNullOrEmpty(targetAlias)) { targetAlias = target.Name ?? string.Empty; if (_targets.ContainsKey(targetAlias)) { return; } } if (_targets.TryGetValue(targetAlias, out Target value) && value == target) { return; } _targets[targetAlias] = target; } if (!string.IsNullOrEmpty(target.Name) && !string.Equals(target.Name, targetAlias, StringComparison.OrdinalIgnoreCase)) { InternalLogger.Info("Registered target {0}(Name={1}) (Extra alias={2})", target.GetType(), target.Name, targetAlias); } else { InternalLogger.Info("Registered target {0}(Name={1})", target.GetType(), target.Name); } } internal void InsertParsedConfigVariable(string key, Layout value) { _variables.InsertParsedConfigVariable(key, value, LogFactory.KeepVariablesOnReload); } internal bool TryLookupDynamicVariable(string key, out Layout value) { return _variables.TryLookupDynamicVariable(key, out value); } public void AddTarget(Target target) { Guard.ThrowIfNull(target, "target"); InternalLogger.Debug("Adding target {0}(Name={1})", target.GetType(), target.Name); if (string.IsNullOrEmpty(target.Name)) { throw new ArgumentException("target.Name cannot be empty", "target"); } AddTargetThreadSafe(target, target.Name); } public void AddTarget(string name, Target target) { Guard.ThrowIfNull(name, "name"); Guard.ThrowIfNull(target, "target"); InternalLogger.Debug("Adding target {0}(Name={1})", target.GetType(), string.IsNullOrEmpty(name) ? target.Name : name); if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Target name cannot be empty", "name"); } AddTargetThreadSafe(target, name); } public Target? FindTargetByName(string name) { Guard.ThrowIfNull(name, "name"); if (TryGetTargetThreadSafe(name, out Target target)) { return target; } return null; } public TTarget? FindTargetByName(string name) where TTarget : Target { Guard.ThrowIfNull(name, "name"); Target target = FindTargetByName(name); if (target is TTarget result) { return result; } if (target is WrapperTargetBase wrapperTargetBase) { if (wrapperTargetBase.WrappedTarget is TTarget result2) { return result2; } if (wrapperTargetBase.WrappedTarget is WrapperTargetBase wrapperTargetBase2 && wrapperTargetBase2.WrappedTarget is TTarget result3) { return result3; } } return null; } public void AddRule(LogLevel minLevel, LogLevel maxLevel, string targetName, string loggerNamePattern = "*") { Guard.ThrowIfNull(targetName, "targetName"); Target target = FindTargetByName(targetName); if (target == null) { throw new NLogConfigurationException("Target '" + targetName + "' not found"); } AddRule(minLevel, maxLevel, target, loggerNamePattern, final: false); } public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern = "*") { AddRule(minLevel, maxLevel, target, loggerNamePattern, final: false); } public void AddRule(LogLevel minLevel, LogLevel maxLevel, Target target, string loggerNamePattern, bool final) { Guard.ThrowIfNull(target, "target"); AddTargetThreadSafe(target); AddLoggingRulesThreadSafe(new LoggingRule(loggerNamePattern, minLevel, maxLevel, target) { Final = final }); } public void AddRule(LoggingRule rule) { Guard.ThrowIfNull(rule, "rule"); IList targets = rule.Targets; if (targets != null && targets.Count > 0) { foreach (Target target in rule.Targets) { AddTargetThreadSafe(target); } } AddLoggingRulesThreadSafe(rule); } public void AddRuleForOneLevel(LogLevel level, string targetName, string loggerNamePattern = "*") { Guard.ThrowIfNull(level, "level"); AddRule(level, level, targetName, loggerNamePattern); } public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern = "*") { Guard.ThrowIfNull(level, "level"); AddRule(level, level, target, loggerNamePattern, final: false); } public void AddRuleForOneLevel(LogLevel level, Target target, string loggerNamePattern, bool final) { Guard.ThrowIfNull(level, "level"); AddRule(level, level, target, loggerNamePattern, final); } public void AddRuleForAllLevels(string targetName, string loggerNamePattern = "*") { AddRule(LogLevel.MinLevel, LogLevel.MaxLevel, targetName, loggerNamePattern); } public void AddRuleForAllLevels(Target target, string loggerNamePattern = "*") { AddRule(LogLevel.MinLevel, LogLevel.MaxLevel, target, loggerNamePattern, final: false); } public void AddRuleForAllLevels(Target target, string loggerNamePattern, bool final) { AddRule(LogLevel.MinLevel, LogLevel.MaxLevel, target, loggerNamePattern, final); } public LoggingRule? FindRuleByName(string ruleName) { Guard.ThrowIfNull(ruleName, "ruleName"); LoggingRule[] loggingRulesThreadSafe = GetLoggingRulesThreadSafe(); for (int num = loggingRulesThreadSafe.Length - 1; num >= 0; num--) { if (string.Equals(loggingRulesThreadSafe[num].RuleName, ruleName, StringComparison.OrdinalIgnoreCase)) { return loggingRulesThreadSafe[num]; } } return null; } public bool RemoveRuleByName(string ruleName) { Guard.ThrowIfNull(ruleName, "ruleName"); HashSet hashSet = new HashSet(); LoggingRule[] loggingRulesThreadSafe = GetLoggingRulesThreadSafe(); foreach (LoggingRule loggingRule in loggingRulesThreadSafe) { if (string.Equals(loggingRule.RuleName, ruleName, StringComparison.OrdinalIgnoreCase)) { hashSet.Add(loggingRule); } } if (hashSet.Count > 0) { lock (LoggingRules) { for (int num = LoggingRules.Count - 1; num >= 0; num--) { if (hashSet.Contains(LoggingRules[num])) { LoggingRules.RemoveAt(num); } } } } return hashSet.Count > 0; } public virtual LoggingConfiguration Reload() { return this; } protected void PrepareForReload(LoggingConfiguration oldConfig) { if (LogFactory.KeepVariablesOnReload) { _variables.PrepareForReload(oldConfig._variables); } } protected internal virtual void OnConfigurationAssigned(LogFactory? logFactory) { if (logFactory != LogFactory && logFactory != null) { if (LogFactory == LogManager.LogFactory) { InternalLogger.Info("Configuration assigned to local LogFactory, but constructed using global LogFactory"); } else { InternalLogger.Info("Configuration assigned to LogFactory, but constructed using other LogFactory"); } } } public void RemoveTarget(string name) { Guard.ThrowIfNull(name, "name"); HashSet hashSet = new HashSet(); Target target = RemoveTargetThreadSafe(name); if (target != null) { hashSet.Add(target); } if (!string.IsNullOrEmpty(name) || target != null) { CleanupRulesForRemovedTarget(name, target, hashSet); } if (hashSet.Count <= 0) { return; } LogFactory.ReconfigExistingLoggers(); ManualResetEvent flushCompleted = new ManualResetEvent(initialState: false); foreach (Target item in hashSet) { flushCompleted.Reset(); item.Flush(delegate { flushCompleted.Set(); }); flushCompleted.WaitOne(TimeSpan.FromSeconds(15.0)); item.Close(); } } private void CleanupRulesForRemovedTarget(string name, Target? removedTarget, HashSet removedTargets) { LoggingRule[] loggingRulesThreadSafe = GetLoggingRulesThreadSafe(); foreach (LoggingRule loggingRule in loggingRulesThreadSafe) { Target[] targetsThreadSafe = loggingRule.GetTargetsThreadSafe(); foreach (Target target in targetsThreadSafe) { if (removedTarget == target || (!string.IsNullOrEmpty(name) && target.Name == name)) { removedTargets.Add(target); loggingRule.RemoveTargetThreadSafe(target); } } } } public void Install(InstallationContext installationContext) { Guard.ThrowIfNull(installationContext, "installationContext"); InitializeAll(); foreach (IInstallable installableItem in GetInstallableItems()) { installationContext.Info("Installing '{0}'", installableItem); try { installableItem.Install(installationContext); installationContext.Info("Finished installing '{0}'.", installableItem); } catch (Exception ex) { InternalLogger.Error(ex, "Install of '{0}' failed.", new ReadOnlySpan(new object[1] { installableItem })); if (ex.MustBeRethrownImmediately() || installationContext.ThrowExceptions) { throw; } installationContext.Error("Install of '{0}' failed: {1}.", installableItem, ex); } } } public void Uninstall(InstallationContext installationContext) { Guard.ThrowIfNull(installationContext, "installationContext"); InitializeAll(); foreach (IInstallable installableItem in GetInstallableItems()) { installationContext.Info("Uninstalling '{0}'", installableItem); try { installableItem.Uninstall(installationContext); installationContext.Info("Finished uninstalling '{0}'.", installableItem); } catch (Exception ex) { InternalLogger.Error(ex, "Uninstall of '{0}' failed.", new ReadOnlySpan(new object[1] { installableItem })); if (ex.MustBeRethrownImmediately()) { throw; } installationContext.Error("Uninstall of '{0}' failed: {1}.", installableItem, ex); } } } internal void Close() { InternalLogger.Debug("Closing logging configuration..."); foreach (ISupportsInitialize supportsInitialize in GetSupportsInitializes()) { InternalLogger.Trace("Closing {0}", supportsInitialize); try { supportsInitialize.Close(); } catch (Exception ex) { InternalLogger.Warn(ex, "Exception while closing."); if (ex.MustBeRethrown()) { throw; } } } InternalLogger.Debug("Finished closing logging configuration."); } internal void Dump() { if (!InternalLogger.IsDebugEnabled) { return; } InternalLogger.Debug("--- NLog configuration dump ---"); InternalLogger.Debug("Targets:"); foreach (Target item in GetAllTargetsThreadSafe()) { InternalLogger.Debug("{0}", item); } InternalLogger.Debug("Rules:"); LoggingRule[] loggingRulesThreadSafe = GetLoggingRulesThreadSafe(); foreach (LoggingRule arg in loggingRulesThreadSafe) { InternalLogger.Debug("{0}", arg); } InternalLogger.Debug("--- End of NLog configuration dump ---"); } internal HashSet GetAllTargetsToFlush() { HashSet hashSet = new HashSet(SingleItemOptimizedHashSet.ReferenceEqualityComparer.Default); LoggingRule[] loggingRulesThreadSafe = GetLoggingRulesThreadSafe(); for (int i = 0; i < loggingRulesThreadSafe.Length; i++) { Target[] targetsThreadSafe = loggingRulesThreadSafe[i].GetTargetsThreadSafe(); foreach (Target item in targetsThreadSafe) { hashSet.Add(item); } } return hashSet; } internal void ValidateConfig() { List list = new List(); LoggingRule[] loggingRulesThreadSafe = GetLoggingRulesThreadSafe(); foreach (LoggingRule item in loggingRulesThreadSafe) { list.Add(item); } foreach (Target item2 in GetAllTargetsThreadSafe()) { list.Add(item2); } _configItems = ObjectGraphScanner.FindReachableObjects(ConfigurationItemFactory.Default, aggressiveSearch: true, list.ToArray()); } internal void InitializeAll() { bool num = _configItems.Count == 0; if (num && (LogFactory.ThrowExceptions || LogManager.ThrowExceptions)) { InternalLogger.Info("LogManager.ThrowExceptions = true can crash the application! Use only for unit-testing and last resort troubleshooting."); } ValidateConfig(); if (num && _targets.Count > 0) { CheckUnusedTargets(); } foreach (ISupportsInitialize supportsInitialize in GetSupportsInitializes(reverse: true)) { InternalLogger.Trace("Initializing {0}", supportsInitialize); try { supportsInitialize.Initialize(this); } catch (Exception exception) { if (exception.MustBeRethrown(supportsInitialize as IInternalLoggerContext)) { throw; } } if (supportsInitialize is Target target && target.InitializeException is NLogDependencyResolveException) { _missingServiceTypes = true; } } } internal void CheckForMissingServiceTypes(Type serviceType) { if (!_missingServiceTypes) { return; } bool flag = false; foreach (Target allTarget in AllTargets) { if (allTarget.InitializeException is NLogDependencyResolveException resolveException) { flag = true; if (typeof(IServiceProvider).IsAssignableFrom(serviceType) || IsMissingServiceType(resolveException, serviceType)) { allTarget.Close(); } } } _missingServiceTypes = flag; if (flag) { InitializeAll(); } } private static bool IsMissingServiceType(NLogDependencyResolveException resolveException, Type serviceType) { if (resolveException.ServiceType.IsAssignableFrom(serviceType)) { return true; } if (resolveException.InnerException is NLogDependencyResolveException resolveException2) { return IsMissingServiceType(resolveException2, serviceType); } return false; } private List GetInstallableItems() { return _configItems.OfType().ToList(); } private List GetSupportsInitializes(bool reverse = false) { IEnumerable source = _configItems.OfType(); if (reverse) { source = source.Reverse(); } return source.ToList(); } internal string ExpandSimpleVariables(string? input) { string matchingVariableName; return ExpandSimpleVariables(input, out matchingVariableName); } internal string ExpandSimpleVariables(string? input, out string? matchingVariableName) { string text = input; matchingVariableName = null; if (text != null && !StringHelpers.IsNullOrWhiteSpace(text) && Variables.Count > 0 && text.IndexOf('$') >= 0) { StringComparison stringComparison = StringComparison.OrdinalIgnoreCase; foreach (KeyValuePair variable in _variables) { Layout value = variable.Value; if (value == null) { continue; } string text2 = "${" + variable.Key + "}"; if (text.IndexOf(text2, stringComparison) >= 0) { if (value is SimpleLayout simpleLayout) { text = StringHelpers.Replace(text, text2, simpleLayout.OriginalText, stringComparison); matchingVariableName = null; } else if (string.Equals(text2, input?.Trim() ?? string.Empty, stringComparison)) { matchingVariableName = variable.Key; } } } } return text ?? string.Empty; } internal void CheckUnusedTargets() { if (!InternalLogger.IsWarnEnabled) { return; } List allTargetsThreadSafe = GetAllTargetsThreadSafe(); InternalLogger.Debug("Unused target checking is started... Rule Count: {0}, Target Count: {1}", LoggingRules.Count, allTargetsThreadSafe.Count); HashSet targetNamesAtRules = new HashSet(from t in GetLoggingRulesThreadSafe().SelectMany((LoggingRule r) => r.Targets) select t.Name); ReadOnlyCollection allTargets = AllTargets; ILookup wrappedTargets = allTargets.OfType().ToLookup((Func)((WrapperTargetBase wt) => wt.WrappedTarget), (Func)((WrapperTargetBase wt) => wt)); ILookup compoundTargets = allTargets.OfType().SelectMany((CompoundTargetBase wt) => wt.Targets.Select((Target t) => new KeyValuePair(t, wt))).ToLookup((KeyValuePair p) => p.Key, (KeyValuePair p) => p.Value); int arg = allTargetsThreadSafe.Count(delegate(Target target) { if (targetNamesAtRules.Contains(target.Name)) { return false; } if (!IsUnusedInList(target, wrappedTargets)) { return false; } if (!IsUnusedInList(target, compoundTargets)) { return false; } InternalLogger.Warn("Unused target detected. Add a rule for this target to the configuration. TargetName: {0}", target.Name); return true; }); InternalLogger.Debug("Unused target checking is completed. Total Rule Count: {0}, Total Target Count: {1}, Unused Target Count: {2}", LoggingRules.Count, allTargetsThreadSafe.Count, arg); bool IsUnusedInList(Target target1, ILookup targets) { if (targets.Contains(target1)) { foreach (Target item in targets[target1]) { if (targetNamesAtRules.Contains(item.Name)) { return false; } if (wrappedTargets.Contains(item)) { return false; } if (compoundTargets.Contains(item)) { return false; } } } return true; } } internal AsyncContinuation? FlushAllTargets(AsyncContinuation flushCompletion) { AsyncContinuation flushCompletion2 = flushCompletion; HashSet pendingTargets = GetAllTargetsToFlush(); if (pendingTargets.Count == 0) { flushCompletion2(null); return null; } InternalLogger.Trace("Flushing all {0} targets...", pendingTargets.Count); Exception lastException = null; Action flushAction = delegate(Target t, Exception? ex) { if (ex != null) { InternalLogger.Warn(ex, "Flush failed for target {0}(Name={1})", new ReadOnlySpan(new object[2] { t.GetType(), t.Name })); } bool flag = false; lock (pendingTargets) { if (ex != null) { lastException = ex; } if (pendingTargets.Remove(t) && pendingTargets.Count == 0) { flag = true; } } if (flag) { if (lastException != null) { InternalLogger.Warn("Flush completed with errors"); AsyncHelpers.StartAsyncTask(delegate(object s) { ((AsyncContinuation)s)(lastException); }, flushCompletion2); } else { InternalLogger.Debug("Flush completed"); AsyncHelpers.StartAsyncTask(delegate(object s) { ((AsyncContinuation)s)(null); }, flushCompletion2); } } }; Target[] array = pendingTargets.ToArray(); foreach (Target target in array) { Target flushTarget = target; AsyncHelpers.StartAsyncTask(delegate { try { flushTarget.Flush(delegate(Exception? ex) { flushAction(flushTarget, ex); }); } catch (Exception arg) { flushAction(flushTarget, arg); throw; } }, null); } return delegate { lock (pendingTargets) { foreach (Target item in pendingTargets) { InternalLogger.Warn("Flush timeout for target {0}(Name={1})", item.GetType(), item.Name); } pendingTargets.Clear(); } }; } internal ITargetWithFilterChain[] BuildLoggerConfiguration(string loggerName, LogLevel globalLogLevel) { if (LoggingRules.Count == 0 || LogLevel.Off.Equals(globalLogLevel)) { return TargetWithFilterChain.NoTargetsByLevel; } LoggingRule[] loggingRulesThreadSafe = GetLoggingRulesThreadSafe(); TargetWithFilterChain[] array = TargetWithFilterChain.BuildLoggerConfiguration(loggerName, loggingRulesThreadSafe, globalLogLevel); if (InternalLogger.IsDebugEnabled && !DumpTargetConfigurationForLogger(loggerName, array)) { InternalLogger.Debug("Targets not configured for Logger: {0}", loggerName); } return array ?? TargetWithFilterChain.NoTargetsByLevel; } private static bool DumpTargetConfigurationForLogger(string loggerName, TargetWithFilterChain[] targetsByLevel) { if (targetsByLevel == null) { return false; } StringBuilder stringBuilder = null; for (int i = 0; i <= LogLevel.MaxLevel.Ordinal; i++) { if (stringBuilder != null) { stringBuilder.Length = 0; stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "Logger {0} [{1}] =>", loggerName, LogLevel.FromOrdinal(i)); } for (TargetWithFilterChain targetWithFilterChain = targetsByLevel[i]; targetWithFilterChain != null; targetWithFilterChain = targetWithFilterChain.NextInChain) { if (stringBuilder == null) { InternalLogger.Debug("Targets configured when LogLevel >= {0} for Logger: {1}", LogLevel.FromOrdinal(i), loggerName); stringBuilder = new StringBuilder(); stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "Logger {0} [{1}] =>", loggerName, LogLevel.FromOrdinal(i)); } stringBuilder.AppendFormat(CultureInfo.InvariantCulture, " {0}", targetWithFilterChain.Target.Name); if (targetWithFilterChain.FilterChain.Count > 0) { stringBuilder.AppendFormat(CultureInfo.InvariantCulture, " ({0} filters)", targetWithFilterChain.FilterChain.Count); } } if (stringBuilder != null) { InternalLogger.Debug(stringBuilder.ToString()); } } return stringBuilder != null; } public override string ToString() { ICollection collection = GetAllTargetsToFlush(); if (collection.Count == 0) { collection = GetAllTargetsThreadSafe(); } if (collection.Count == 0) { collection = AllTargets; } if (collection.Count > 0 && collection.Count < 5) { return string.Format("TargetNames={0}, ConfigItems={1}", string.Join(", ", (from t in collection select t.Name into n where !string.IsNullOrEmpty(n) select n).ToArray()), _configItems.Count); } return $"Targets={collection.Count}, ConfigItems={_configItems.Count}"; } } public class LoggingConfigurationChangedEventArgs : EventArgs { public LoggingConfiguration? DeactivatedConfiguration { get; } public LoggingConfiguration? ActivatedConfiguration { get; } public LoggingConfigurationChangedEventArgs(LoggingConfiguration? activatedConfiguration, LoggingConfiguration? deactivatedConfiguration) { ActivatedConfiguration = activatedConfiguration; DeactivatedConfiguration = deactivatedConfiguration; } } internal static class LoggingConfigurationElementExtensions { [CompilerGenerated] private sealed class d__6 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private ILoggingConfigurationElement <>2__current; private int <>l__initialThreadId; private string elementName; public string <>3__elementName; private ILoggingConfigurationElement element; public ILoggingConfigurationElement <>3__element; private IEnumerator <>7__wrap1; ILoggingConfigurationElement IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__6(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; if (elementName == null || element?.Children == null) { return false; } <>7__wrap1 = element.Children.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } while (<>7__wrap1.MoveNext()) { ILoggingConfigurationElement current = <>7__wrap1.Current; if (current.Name.Equals(elementName, StringComparison.OrdinalIgnoreCase)) { <>2__current = current; <>1__state = 1; return true; } } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { d__6 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__6(0); } d__.element = <>3__element; d__.elementName = <>3__elementName; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } public static bool MatchesName(this ILoggingConfigurationElement section, string expectedName) { return string.Equals(section?.Name?.Trim(), expectedName, StringComparison.OrdinalIgnoreCase); } public static void AssertName(this ILoggingConfigurationElement section, params string[] allowedNames) { foreach (string expectedName in allowedNames) { if (section.MatchesName(expectedName)) { return; } } throw new InvalidOperationException("Assertion failed. Expected element name '" + string.Join("|", allowedNames) + "', actual: '" + section?.Name + "'."); } public static string GetRequiredValue(this ILoggingConfigurationElement element, string attributeName, string section) { string optionalValue = element.GetOptionalValue(attributeName, null); if (optionalValue == null) { throw new NLogConfigurationException("Expected " + attributeName + " on " + element.Name + " in " + section); } if (StringHelpers.IsNullOrWhiteSpace(optionalValue)) { throw new NLogConfigurationException("Expected non-empty " + attributeName + " on " + element.Name + " in " + section); } return optionalValue; } public static string? GetOptionalValue(this ILoggingConfigurationElement element, string attributeName, string? defaultValue) { string attributeName2 = attributeName; return (from configItem in element.Values where string.Equals(configItem.Key, attributeName2, StringComparison.OrdinalIgnoreCase) select configItem.Value).FirstOrDefault() ?? defaultValue; } public static bool GetOptionalBooleanValue(this ILoggingConfigurationElement element, string attributeName, bool defaultValue) { string text = element.GetOptionalValue(attributeName, null)?.Trim() ?? string.Empty; if (string.IsNullOrEmpty(text)) { return defaultValue; } try { return Convert.ToBoolean(text, CultureInfo.InvariantCulture); } catch (Exception ex) { NLogConfigurationException ex2 = new NLogConfigurationException($"'{attributeName}' hasn't a valid boolean value '{text}'. {defaultValue} will be used", ex); if (ex2.MustBeRethrown()) { throw ex2; } InternalLogger.Error(ex, ex2.Message); return defaultValue; } } public static string GetConfigItemTypeAttribute(this ILoggingConfigurationElement element, string? sectionNameForRequiredValue = null) { return StripOptionalNamespacePrefix(((sectionNameForRequiredValue != null) ? element.GetRequiredValue("type", sectionNameForRequiredValue) : element.GetOptionalValue("type", null)) ?? string.Empty).Trim(); } [IteratorStateMachine(typeof(d__6))] public static IEnumerable FilterChildren(this ILoggingConfigurationElement element, string elementName) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__6(-2) { <>3__element = element, <>3__elementName = elementName }; } private static string StripOptionalNamespacePrefix(string attributeValue) { if (attributeValue == null) { return string.Empty; } int num = attributeValue.IndexOf(':'); if (num < 0) { return attributeValue; } return attributeValue.Substring(num + 1); } } internal class LoggingConfigurationFileLoader : ILoggingConfigurationLoader, IDisposable { [CompilerGenerated] private sealed class d__11 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private string <>2__current; private int <>l__initialThreadId; public LoggingConfigurationFileLoader <>4__this; private string entryAssemblyLocation; public string <>3__entryAssemblyLocation; private string baseDirectory; public string <>3__baseDirectory; private string 5__2; private string 5__3; string IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__11(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; 5__3 = null; <>1__state = -2; } private bool MoveNext() { int num = <>1__state; LoggingConfigurationFileLoader loggingConfigurationFileLoader = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; 5__2 = loggingConfigurationFileLoader._appEnvironment.AppDomainConfigurationFile; if (!StringHelpers.IsNullOrWhiteSpace(5__2)) { <>2__current = Path.ChangeExtension(5__2, ".nlog"); <>1__state = 1; return true; } if (string.IsNullOrEmpty(entryAssemblyLocation)) { entryAssemblyLocation = baseDirectory; } if (PathHelpers.IsTempDir(entryAssemblyLocation, loggingConfigurationFileLoader._appEnvironment.UserTempFilePath)) { string currentProcessFilePath = loggingConfigurationFileLoader._appEnvironment.CurrentProcessFilePath; if (!string.IsNullOrEmpty(currentProcessFilePath)) { <>2__current = currentProcessFilePath + ".nlog"; <>1__state = 3; return true; } } goto IL_012e; case 1: <>1__state = -1; if (5__2.Contains(".vshost.")) { <>2__current = Path.ChangeExtension(5__2.Replace(".vshost.", "."), ".nlog"); <>1__state = 2; return true; } break; case 2: <>1__state = -1; break; case 3: <>1__state = -1; goto IL_012e; case 4: <>1__state = -1; goto IL_019c; case 5: { <>1__state = -1; goto IL_01cd; } IL_012e: if (string.IsNullOrEmpty(entryAssemblyLocation)) { break; } 5__3 = loggingConfigurationFileLoader._appEnvironment.EntryAssemblyFileName; if (!string.IsNullOrEmpty(5__3)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(5__3); if (!string.IsNullOrEmpty(fileNameWithoutExtension)) { <>2__current = Path.Combine(entryAssemblyLocation, fileNameWithoutExtension + ".exe.nlog"); <>1__state = 4; return true; } goto IL_019c; } goto IL_01cd; IL_01cd: 5__3 = null; break; IL_019c: <>2__current = Path.Combine(entryAssemblyLocation, 5__3 + ".nlog"); <>1__state = 5; return true; } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { d__11 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__11(0) { <>4__this = <>4__this }; } d__.baseDirectory = <>3__baseDirectory; d__.entryAssemblyLocation = <>3__entryAssemblyLocation; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } [CompilerGenerated] private sealed class d__9 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private string <>2__current; private int <>l__initialThreadId; public LoggingConfigurationFileLoader <>4__this; private string filename; public string <>3__filename; private string 5__2; private string 5__3; private string 5__4; private string 5__5; private bool 5__6; private IEnumerator <>7__wrap6; string IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__9(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { switch (<>1__state) { case -3: case 1: try { } finally { <>m__Finally1(); } break; case -4: case 8: try { } finally { <>m__Finally2(); } break; } 5__2 = null; 5__3 = null; 5__4 = null; 5__5 = null; <>7__wrap6 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; LoggingConfigurationFileLoader loggingConfigurationFileLoader = <>4__this; string text; switch (num) { default: return false; case 0: <>1__state = -1; 5__2 = PathHelpers.TrimDirectorySeparators(loggingConfigurationFileLoader._appEnvironment.AppDomainBaseDirectory); 5__3 = PathHelpers.TrimDirectorySeparators(loggingConfigurationFileLoader._appEnvironment.EntryAssemblyLocation); if (filename == null) { <>7__wrap6 = loggingConfigurationFileLoader.GetAppSpecificNLogLocations(5__2, 5__3).GetEnumerator(); <>1__state = -3; goto IL_00d0; } goto IL_00ea; case 1: <>1__state = -3; goto IL_00d0; case 2: <>1__state = -1; goto IL_0138; case 3: <>1__state = -1; goto IL_01ab; case 4: <>1__state = -1; if (!5__6) { <>2__current = Path.Combine(5__3, 5__5); <>1__state = 5; return true; } goto IL_022c; case 5: <>1__state = -1; goto IL_022c; case 6: <>1__state = -1; if (!5__6) { <>2__current = 5__5; <>1__state = 7; return true; } goto IL_0283; case 7: <>1__state = -1; goto IL_0283; case 8: <>1__state = -4; goto IL_02e7; case 9: { <>1__state = -1; break; } IL_01ab: if (!string.IsNullOrEmpty(5__3) && !string.Equals(5__3, 5__2, StringComparison.OrdinalIgnoreCase)) { <>2__current = Path.Combine(5__3, 5__4); <>1__state = 4; return true; } goto IL_022c; IL_0138: 5__5 = 5__4.ToLower(); 5__6 = 5__4 == 5__5 || PlatformDetector.IsWin32; if (!5__6 && !string.IsNullOrEmpty(5__2)) { <>2__current = Path.Combine(5__2, 5__5); <>1__state = 3; return true; } goto IL_01ab; IL_00d0: if (<>7__wrap6.MoveNext()) { string current = <>7__wrap6.Current; <>2__current = current; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap6 = null; goto IL_00ea; IL_0283: <>7__wrap6 = loggingConfigurationFileLoader.GetPrivateBinPathNLogLocations(5__2, 5__4, 5__6 ? 5__5 : string.Empty).GetEnumerator(); <>1__state = -4; goto IL_02e7; IL_02e7: if (<>7__wrap6.MoveNext()) { string current2 = <>7__wrap6.Current; <>2__current = current2; <>1__state = 8; return true; } <>m__Finally2(); <>7__wrap6 = null; text = ((filename == null) ? LookupNLogAssemblyLocation() : null); if (!string.IsNullOrEmpty(text)) { <>2__current = text + ".nlog"; <>1__state = 9; return true; } break; IL_00ea: 5__4 = filename ?? "NLog.config"; if (!string.IsNullOrEmpty(5__2)) { <>2__current = Path.Combine(5__2, 5__4); <>1__state = 2; return true; } goto IL_0138; IL_022c: if (string.IsNullOrEmpty(5__2)) { <>2__current = 5__4; <>1__state = 6; return true; } goto IL_0283; } return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap6 != null) { <>7__wrap6.Dispose(); } } private void <>m__Finally2() { <>1__state = -1; if (<>7__wrap6 != null) { <>7__wrap6.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { d__9 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__9(0) { <>4__this = <>4__this }; } d__.filename = <>3__filename; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } [CompilerGenerated] private sealed class d__12 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private string <>2__current; private int <>l__initialThreadId; public LoggingConfigurationFileLoader <>4__this; private string baseDirectory; public string <>3__baseDirectory; private string nlogConfigFile; public string <>3__nlogConfigFile; private string nLogConfigFileLowerCase; public string <>3__nLogConfigFileLowerCase; private IEnumerator <>7__wrap1; private string 5__3; string IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__12(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || (uint)(num - 1) <= 1u) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; 5__3 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; LoggingConfigurationFileLoader loggingConfigurationFileLoader = <>4__this; switch (num) { default: return false; case 0: { <>1__state = -1; IEnumerable appDomainPrivateBinPath = loggingConfigurationFileLoader._appEnvironment.AppDomainPrivateBinPath; if (appDomainPrivateBinPath == null) { break; } <>7__wrap1 = appDomainPrivateBinPath.GetEnumerator(); <>1__state = -3; goto IL_00fc; } case 1: <>1__state = -3; if (!string.IsNullOrEmpty(nLogConfigFileLowerCase)) { <>2__current = Path.Combine(5__3, nLogConfigFileLowerCase); <>1__state = 2; return true; } goto IL_00f5; case 2: { <>1__state = -3; goto IL_00f5; } IL_00f5: 5__3 = null; goto IL_00fc; IL_00fc: if (<>7__wrap1.MoveNext()) { string current = <>7__wrap1.Current; 5__3 = PathHelpers.TrimDirectorySeparators(current); if (!StringHelpers.IsNullOrWhiteSpace(5__3) && !string.Equals(5__3, baseDirectory, StringComparison.OrdinalIgnoreCase)) { <>2__current = Path.Combine(5__3, nlogConfigFile); <>1__state = 1; return true; } goto IL_00f5; } <>m__Finally1(); <>7__wrap1 = null; break; } return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { d__12 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__12(0) { <>4__this = <>4__this }; } d__.baseDirectory = <>3__baseDirectory; d__.nlogConfigFile = <>3__nlogConfigFile; d__.nLogConfigFileLowerCase = <>3__nLogConfigFileLowerCase; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } private readonly IAppEnvironment _appEnvironment; public LoggingConfigurationFileLoader(IAppEnvironment appEnvironment) { _appEnvironment = appEnvironment; } public LoggingConfiguration? Load(LogFactory logFactory, string? filename = null) { if (filename == null || StringHelpers.IsNullOrWhiteSpace(filename) || FileInfoHelper.IsRelativeFilePath(filename)) { return TryLoadFromFilePaths(logFactory, filename); } if (TryLoadLoggingConfiguration(logFactory, filename, out LoggingConfiguration config)) { return config; } return null; } private LoggingConfiguration? TryLoadFromFilePaths(LogFactory logFactory, string? filename) { foreach (string candidateConfigFilePath in logFactory.GetCandidateConfigFilePaths(filename)) { if (TryLoadLoggingConfiguration(logFactory, candidateConfigFilePath, out LoggingConfiguration config)) { return config; } } return null; } private bool TryLoadLoggingConfiguration(LogFactory logFactory, string configFile, out LoggingConfiguration? config) { try { if (_appEnvironment.FileExists(configFile)) { config = LoadXmlLoggingConfigurationFile(logFactory, configFile); return true; } InternalLogger.Debug("No file exists at candidate config file location: {0}", configFile); } catch (IOException ex) { InternalLogger.Warn(ex, "Skipping invalid config file location: {0}", new ReadOnlySpan(new object[1] { configFile })); } catch (UnauthorizedAccessException ex2) { InternalLogger.Warn(ex2, "Skipping inaccessible config file location: {0}", new ReadOnlySpan(new object[1] { configFile })); } catch (SecurityException ex3) { InternalLogger.Warn(ex3, "Skipping inaccessible config file location: {0}", new ReadOnlySpan(new object[1] { configFile })); } catch (Exception ex4) { InternalLogger.Error(ex4, "Failed loading from config file location: {0}", new ReadOnlySpan(new object[1] { configFile })); if ((logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions) || ex4.MustBeRethrown()) { throw; } } config = null; return false; } private LoggingConfiguration LoadXmlLoggingConfigurationFile(LogFactory logFactory, string configFile) { InternalLogger.Debug("Reading config from XML file: {0}", configFile); using TextReader xmlSource = _appEnvironment.LoadTextFile(configFile); try { return new XmlLoggingConfiguration(xmlSource, configFile, logFactory); } catch (Exception ex) { if (ex.MustBeRethrown() || (logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions)) { throw; } bool invalidXml = ex is XmlParserException || ex.InnerException is XmlParserException; if (ThrowXmlConfigExceptions(configFile, invalidXml, logFactory, out var autoReload)) { throw; } return CreateEmptyDefaultConfig(configFile, logFactory, autoReload); } } private static LoggingConfiguration CreateEmptyDefaultConfig(string configFile, LogFactory logFactory, bool autoReload) { return new XmlLoggingConfiguration($"", configFile, logFactory); } private static bool ThrowXmlConfigExceptions(string configFile, bool invalidXml, LogFactory logFactory, out bool autoReload) { autoReload = false; try { if (string.IsNullOrEmpty(configFile)) { return false; } string fileContent = File.ReadAllText(configFile); if (invalidXml) { if (ScanForBooleanParameter(fileContent, "throwExceptions", parameterValue: true)) { logFactory.ThrowExceptions = true; return true; } if (ScanForBooleanParameter(fileContent, "throwConfigExceptions", parameterValue: true)) { logFactory.ThrowConfigExceptions = true; return true; } } if (ScanForBooleanParameter(fileContent, "autoReload", parameterValue: true)) { autoReload = true; } return false; } catch (Exception ex) { InternalLogger.Error(ex, "Failed to scan content of config file: {0}", new ReadOnlySpan(new object[1] { configFile })); return false; } } private static bool ScanForBooleanParameter(string fileContent, string parameterName, bool parameterValue) { if (fileContent.IndexOf($"{parameterName}=\"{parameterValue}", StringComparison.OrdinalIgnoreCase) < 0) { return fileContent.IndexOf($"{parameterName}='{parameterValue}", StringComparison.OrdinalIgnoreCase) >= 0; } return true; } [IteratorStateMachine(typeof(d__9))] public IEnumerable GetDefaultCandidateConfigFilePaths(string? filename = null) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__9(-2) { <>4__this = this, <>3__filename = filename }; } private static string? LookupNLogAssemblyLocation() { string assemblyFileLocation = AssemblyHelpers.GetAssemblyFileLocation(typeof(LogFactory).Assembly); if (!string.IsNullOrEmpty(assemblyFileLocation)) { return assemblyFileLocation; } return null; } [IteratorStateMachine(typeof(d__11))] public IEnumerable GetAppSpecificNLogLocations(string baseDirectory, string entryAssemblyLocation) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__11(-2) { <>4__this = this, <>3__baseDirectory = baseDirectory, <>3__entryAssemblyLocation = entryAssemblyLocation }; } [IteratorStateMachine(typeof(d__12))] private IEnumerable GetPrivateBinPathNLogLocations(string baseDirectory, string nlogConfigFile, string nLogConfigFileLowerCase) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__12(-2) { <>4__this = this, <>3__baseDirectory = baseDirectory, <>3__nlogConfigFile = nlogConfigFile, <>3__nLogConfigFileLowerCase = nLogConfigFileLowerCase }; } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public abstract class LoggingConfigurationParser : LoggingConfiguration { private sealed class ValidatedConfigurationElement : ILoggingConfigurationElement { [CompilerGenerated] private sealed class d__13 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private ValidatedConfigurationElement <>2__current; private int <>l__initialThreadId; public ValidatedConfigurationElement <>4__this; private IList 5__2; private IEnumerator <>7__wrap2; ValidatedConfigurationElement IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__13(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } 5__2 = null; <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; ValidatedConfigurationElement validatedConfigurationElement = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; 5__2 = null; <>7__wrap2 = validatedConfigurationElement._element.Children.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap2.MoveNext()) { ILoggingConfigurationElement current = <>7__wrap2.Current; 5__2 = 5__2 ?? new List(); ValidatedConfigurationElement item = new ValidatedConfigurationElement(current, validatedConfigurationElement._throwConfigExceptions); 5__2.Add(item); <>2__current = item; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap2 = null; validatedConfigurationElement._validChildren = 5__2 ?? ArrayHelper.Empty(); return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { d__13 result; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; result = this; } else { result = new d__13(0) { <>4__this = <>4__this }; } return result; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } private readonly ILoggingConfigurationElement _element; private readonly bool _throwConfigExceptions; private IList? _validChildren; private readonly IDictionary? _valueLookup; public string Name { get; } public ICollection> Values { get { ICollection> valueLookup = _valueLookup; return valueLookup ?? ArrayHelper.Empty>(); } } public IEnumerable ValidChildren { get { if (_validChildren == null) { return YieldAndCacheValidChildren(); } return _validChildren; } } IEnumerable ILoggingConfigurationElement.Children => ValidChildren.Cast(); IEnumerable> ILoggingConfigurationElement.Values => Values; public static ValidatedConfigurationElement Create(ILoggingConfigurationElement element, LogFactory logFactory) { if (element is ValidatedConfigurationElement result) { return result; } bool throwConfigExceptions = (logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions) || (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions); return new ValidatedConfigurationElement(element, throwConfigExceptions); } public ValidatedConfigurationElement(ILoggingConfigurationElement element, bool throwConfigExceptions) { _throwConfigExceptions = throwConfigExceptions; Name = element.Name.Trim(); _valueLookup = CreateValueLookup(element, throwConfigExceptions); _element = element; } [IteratorStateMachine(typeof(d__13))] private IEnumerable YieldAndCacheValidChildren() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__13(-2) { <>4__this = this }; } public string GetRequiredValue(string attributeName, string section) { string optionalValue = GetOptionalValue(attributeName, null); if (optionalValue == null) { throw new NLogConfigurationException("Expected " + attributeName + " on " + Name + " in " + section); } if (StringHelpers.IsNullOrWhiteSpace(optionalValue)) { throw new NLogConfigurationException("Expected non-empty " + attributeName + " on " + Name + " in " + section); } return optionalValue; } public string? GetOptionalValue(string attributeName, string? defaultValue) { if (_valueLookup == null) { return defaultValue; } _valueLookup.TryGetValue(attributeName, out string value); return value ?? defaultValue; } private static IDictionary? CreateValueLookup(ILoggingConfigurationElement element, bool throwConfigExceptions) { IDictionary dictionary = null; List list = null; foreach (KeyValuePair value in element.Values) { string text = value.Key?.Trim() ?? string.Empty; dictionary = dictionary ?? new Dictionary(StringComparer.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(text) && !dictionary.ContainsKey(text)) { dictionary[text] = value.Value; continue; } string text2 = (string.IsNullOrEmpty(text) ? ("Invalid property for '" + element.Name + "' without name. Value=" + value.Value) : ("Duplicate value for '" + element.Name + "'. PropertyName=" + text + ". Skips Value=" + value.Value + ". Existing Value=" + dictionary[text])); InternalLogger.Debug("Skipping {0}", text2); if (throwConfigExceptions) { list = list ?? new List(); list.Add(text2); } } if (throwConfigExceptions && list != null && list.Count > 0) { throw new NLogConfigurationException(StringHelpers.Join(Environment.NewLine, list)); } return dictionary; } public override string ToString() { return Name; } } protected LoggingConfigurationParser(LogFactory logFactory) : base(logFactory) { } protected void LoadConfig(ILoggingConfigurationElement nlogConfig, string? basePath) { InternalLogger.Trace("ParseNLogConfig"); nlogConfig.AssertName("nlog"); SetNLogElementSettings(nlogConfig); ValidatedConfigurationElement validatedConfigurationElement = ValidatedConfigurationElement.Create(nlogConfig, base.LogFactory); foreach (ValidatedConfigurationElement validChild in validatedConfigurationElement.ValidChildren) { if (validChild.MatchesName("extensions")) { ParseExtensionsElement(validChild, basePath); } } List list = new List(); int count = base.LoggingRules.Count; foreach (ValidatedConfigurationElement validChild2 in validatedConfigurationElement.ValidChildren) { if (validChild2.MatchesName("rules")) { if (list.Count == 0) { count = base.LoggingRules.Count; } list.Add(validChild2); } else if (!validChild2.MatchesName("extensions") && !ParseNLogSection(validChild2)) { NLogConfigurationException ex = new NLogConfigurationException("Unrecognized element '" + validChild2.Name + "' from section 'NLog'"); if (MustThrowConfigException(ex)) { throw ex; } } } foreach (ValidatedConfigurationElement item in list) { ParseRulesElement(item, base.LoggingRules, count); } } private void SetNLogElementSettings(ILoggingConfigurationElement nlogConfig) { ICollection> collection = CreateUniqueSortedListFromConfig(nlogConfig); CultureInfo cultureInfo = base.DefaultCultureInfo ?? base.LogFactory._defaultCultureInfo; bool? enable = base.LogFactory.ServiceRepository.ResolveParseMessageTemplates(); bool flag = false; foreach (KeyValuePair item in collection) { switch (item.Key.ToUpperInvariant()) { case "THROWEXCEPTIONS": base.LogFactory.ThrowExceptions = ParseBooleanValue(item.Key, item.Value ?? string.Empty, base.LogFactory.ThrowExceptions); continue; case "THROWCONFIGEXCEPTIONS": base.LogFactory.ThrowConfigExceptions = ParseNullableBooleanValue(item.Key, item.Value ?? string.Empty, defaultValue: false); continue; case "INTERNALLOGLEVEL": InternalLogger.LogLevel = ParseLogLevelSafe(item.Key, item.Value ?? string.Empty, InternalLogger.LogLevel); continue; case "USEINVARIANTCULTURE": if (ParseBooleanValue(item.Key, item.Value ?? string.Empty, defaultValue: false)) { CultureInfo cultureInfo2 = (base.DefaultCultureInfo = CultureInfo.InvariantCulture); cultureInfo = cultureInfo2; } continue; case "KEEPVARIABLESONRELOAD": base.LogFactory.KeepVariablesOnReload = ParseBooleanValue(item.Key, item.Value ?? string.Empty, base.LogFactory.KeepVariablesOnReload); continue; case "INTERNALLOGTOCONSOLE": InternalLogger.LogToConsole = ParseBooleanValue(item.Key, item.Value ?? string.Empty, InternalLogger.LogToConsole); continue; case "INTERNALLOGTOCONSOLEERROR": InternalLogger.LogToConsoleError = ParseBooleanValue(item.Key, item.Value ?? string.Empty, InternalLogger.LogToConsoleError); continue; case "INTERNALLOGFILE": InternalLogger.LogFile = item.Value?.Trim(); continue; case "INTERNALLOGINCLUDETIMESTAMP": InternalLogger.IncludeTimestamp = ParseBooleanValue(item.Key, item.Value ?? string.Empty, InternalLogger.IncludeTimestamp); continue; case "GLOBALTHRESHOLD": base.LogFactory.GlobalThreshold = ParseLogLevelSafe(item.Key, item.Value ?? string.Empty, base.LogFactory.GlobalThreshold); continue; case "PARSEMESSAGETEMPLATES": enable = ParseNullableBooleanValue(item.Key, item.Value ?? string.Empty, defaultValue: true); continue; case "AUTOSHUTDOWN": base.LogFactory.AutoShutdown = ParseBooleanValue(item.Key, item.Value ?? string.Empty, defaultValue: true); continue; case "AUTOLOADEXTENSIONS": flag = ParseBooleanValue(item.Key, item.Value ?? string.Empty, defaultValue: false); continue; case "AUTORELOAD": continue; } NLogConfigurationException ex = new NLogConfigurationException("Unrecognized value '" + item.Key + "'='" + item.Value + "' for element '" + nlogConfig.Name + "'"); if (MustThrowConfigException(ex)) { throw ex; } } if (cultureInfo != null && base.DefaultCultureInfo != cultureInfo) { base.DefaultCultureInfo = cultureInfo; } if (flag) { ScanForAutoLoadExtensions(); } base.LogFactory.ServiceRepository.ParseMessageTemplates(base.LogFactory, enable); } [UnconditionalSuppressMessage("Trimming - Allow extension loading from config", "IL2026")] private static void ScanForAutoLoadExtensions() { ConfigurationItemFactory.Default.AssemblyLoader.ScanForAutoLoadExtensions(ConfigurationItemFactory.Default); } private ICollection> CreateUniqueSortedListFromConfig(ILoggingConfigurationElement nlogConfig) { ValidatedConfigurationElement validatedConfigurationElement = ValidatedConfigurationElement.Create(nlogConfig, base.LogFactory); ICollection> values = validatedConfigurationElement.Values; if (values.Count <= 1) { return values; } List> list = new List>(values.Count); HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase) { "ThrowExceptions", "ThrowConfigExceptions", "InternalLogLevel", "InternalLogFile", "InternalLogToConsole" }; foreach (string item in hashSet) { string optionalValue = validatedConfigurationElement.GetOptionalValue(item, null); if (optionalValue != null) { list.Add(new KeyValuePair(item, optionalValue)); } } foreach (KeyValuePair value in validatedConfigurationElement.Values) { if (!hashSet.Contains(value.Key)) { list.Add(value); } } return list; } private LogLevel ParseLogLevelSafe(string propertyName, string propertyValue, LogLevel fallbackValue) { try { return LogLevel.FromString(propertyValue?.Trim() ?? string.Empty); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } NLogConfigurationException ex2 = new NLogConfigurationException($"Property '{propertyName}' assigned invalid LogLevel value '{propertyValue}'. Fallback to '{fallbackValue}'", ex); if (MustThrowConfigException(ex2)) { throw ex2; } return fallbackValue; } } protected virtual bool ParseNLogSection(ILoggingConfigurationElement configSection) { switch (configSection.Name?.Trim().ToUpperInvariant()) { case "TIME": ParseTimeElement(ValidatedConfigurationElement.Create(configSection, base.LogFactory)); return true; case "VARIABLE": ParseVariableElement(ValidatedConfigurationElement.Create(configSection, base.LogFactory)); return true; case "VARIABLES": ParseVariablesElement(ValidatedConfigurationElement.Create(configSection, base.LogFactory)); return true; case "APPENDERS": case "TARGETS": ParseTargetsElement(ValidatedConfigurationElement.Create(configSection, base.LogFactory)); return true; default: return false; } } private void ParseExtensionsElement(ValidatedConfigurationElement extensionsElement, string? baseDirectory) { extensionsElement.AssertName("extensions"); foreach (ValidatedConfigurationElement validChild in extensionsElement.ValidChildren) { string text = string.Empty; string text2 = null; string text3 = null; string text4 = null; foreach (KeyValuePair value in validChild.Values) { if (MatchesName(value.Key, "prefix")) { text = value.Value + "."; continue; } if (MatchesName(value.Key, "type")) { text2 = value.Value; continue; } if (MatchesName(value.Key, "assemblyFile")) { text3 = value.Value; continue; } if (MatchesName(value.Key, "assembly")) { text4 = value.Value; continue; } NLogConfigurationException ex = new NLogConfigurationException("Unrecognized value '" + value.Key + "'='" + value.Value + "' for element '" + validChild.Name + "' in section '" + extensionsElement.Name + "'"); if (!MustThrowConfigException(ex)) { continue; } throw ex; } if (text2 != null && !StringHelpers.IsNullOrWhiteSpace(text2)) { RegisterExtension(text2, text); } if (text3 != null && !StringHelpers.IsNullOrWhiteSpace(text3)) { ParseExtensionWithAssemblyFile(text3, baseDirectory, text); } else if (text4 != null && !StringHelpers.IsNullOrWhiteSpace(text4)) { ParseExtensionWithAssemblyName(text4.Trim(), text); } } } [UnconditionalSuppressMessage("Trimming - Allow extension loading from config", "IL2072")] private void RegisterExtension(string typeName, string itemNamePrefix) { try { Type type = PropertyTypeConverter.ConvertToType(typeName, throwOnError: true); ConfigurationItemFactory.Default.RegisterType(type, itemNamePrefix); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } NLogConfigurationException ex2 = new NLogConfigurationException("Error loading extensions: " + typeName, ex); if (MustThrowConfigException(ex2)) { throw ex2; } } } [UnconditionalSuppressMessage("Trimming - Allow extension loading from config", "IL2026")] private void ParseExtensionWithAssemblyFile(string assemblyFile, string? baseDirectory, string prefix) { try { ConfigurationItemFactory.Default.AssemblyLoader.LoadAssemblyFromPath(ConfigurationItemFactory.Default, assemblyFile, baseDirectory, prefix); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } NLogConfigurationException ex2 = new NLogConfigurationException("Error loading extensions: " + assemblyFile, ex); if (MustThrowConfigException(ex2)) { throw ex2; } } } private bool RegisterExtensionFromAssemblyName(string assemblyName, string originalTypeName) { InternalLogger.Debug("Loading Assembly-Name '{0}' for type: {1}", assemblyName, originalTypeName); return ParseExtensionWithAssemblyName(assemblyName, string.Empty); } [UnconditionalSuppressMessage("Trimming - Allow extension loading from config", "IL2026")] private bool ParseExtensionWithAssemblyName(string assemblyName, string itemNamePrefix) { try { ConfigurationItemFactory.Default.AssemblyLoader.LoadAssemblyFromName(ConfigurationItemFactory.Default, assemblyName, itemNamePrefix); return true; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } NLogConfigurationException ex2 = new NLogConfigurationException("Error loading extensions: " + assemblyName, ex); if (MustThrowConfigException(ex2)) { throw ex2; } } return false; } private void ParseVariableElement(ValidatedConfigurationElement variableElement) { string text = null; string text2 = null; foreach (KeyValuePair value in variableElement.Values) { if (MatchesName(value.Key, "name")) { text = value.Value; continue; } if (MatchesName(value.Key, "value") || MatchesName(value.Key, "layout")) { text2 = value.Value; continue; } NLogConfigurationException ex = new NLogConfigurationException("Unrecognized value '" + value.Key + "'='" + value.Value + "' for element '" + variableElement.Name + "' in section 'variables'"); if (!MustThrowConfigException(ex)) { continue; } throw ex; } if (AssertNonEmptyValue(text, "name", variableElement.Name, "variables") && text != null) { Layout layout = ((text2 == null) ? ParseVariableLayoutValue(variableElement) : CreateSimpleLayout(ExpandSimpleVariables(text2))); if (AssertNotNullValue(layout, "value", variableElement.Name, "variables") && layout != null) { InsertParsedConfigVariable(text, layout); } } } private Layout? ParseVariableLayoutValue(ValidatedConfigurationElement variableElement) { ValidatedConfigurationElement validatedConfigurationElement = variableElement.ValidChildren.FirstOrDefault(); if (validatedConfigurationElement != null) { return TryCreateLayoutInstance(validatedConfigurationElement, typeof(Layout)); } return null; } private void ParseVariablesElement(ValidatedConfigurationElement variableElement) { variableElement.AssertName("variables"); foreach (ValidatedConfigurationElement validChild in variableElement.ValidChildren) { ParseVariableElement(validChild); } } private void ParseTimeElement(ValidatedConfigurationElement timeElement) { timeElement.AssertName("time"); string text = null; foreach (KeyValuePair value in timeElement.Values) { if (MatchesName(value.Key, "type")) { text = value.Value; continue; } NLogConfigurationException ex = new NLogConfigurationException("Unrecognized value '" + value.Key + "'='" + value.Value + "' for element '" + timeElement.Name + "'"); if (!MustThrowConfigException(ex)) { continue; } throw ex; } if (AssertNonEmptyValue(text, "type", timeElement.Name, string.Empty) && text != null) { TimeSource timeSource = FactoryCreateInstance(text, ConfigurationItemFactory.Default.TimeSourceFactory); if (timeSource != null) { ConfigureFromAttributesAndElements(timeSource, timeElement); InternalLogger.Info("Selecting time source {0}", timeSource); TimeSource.Current = timeSource; } } } [ContractAnnotation("value:notnull => true")] private bool AssertNotNullValue(object? value, string propertyName, string elementName, string sectionName) { if (value == null) { return AssertNonEmptyValue(string.Empty, propertyName, elementName, sectionName); } return true; } [ContractAnnotation("value:null => false")] private bool AssertNonEmptyValue(string? value, string propertyName, string elementName, string sectionName) { if (!StringHelpers.IsNullOrWhiteSpace(value)) { return true; } NLogConfigurationException ex = new NLogConfigurationException("Property '" + propertyName + "' has blank value, for element '" + elementName + "' in section '" + sectionName + "'"); if (MustThrowConfigException(ex)) { throw ex; } return false; } private void ParseRulesElement(ValidatedConfigurationElement rulesElement, IList rulesCollection, int rulesInsertPosition) { InternalLogger.Trace("ParseRulesElement"); rulesElement.AssertName("rules"); if (rulesInsertPosition > rulesCollection.Count) { rulesInsertPosition = rulesCollection.Count; } if (rulesElement.Values.Count > 0) { foreach (KeyValuePair value in rulesElement.Values) { NLogConfigurationException ex = new NLogConfigurationException("Unrecognized value '" + value.Key + "'='" + value.Value + "' in section '" + rulesElement.Name + "'"); if (MustThrowConfigException(ex)) { throw ex; } } } foreach (ValidatedConfigurationElement validChild in rulesElement.ValidChildren) { LoggingRule loggingRule = ParseRuleElement(validChild); if (loggingRule != null) { lock (rulesCollection) { rulesCollection.Insert(rulesInsertPosition++, loggingRule); } } } } private LoggingRule? ParseRuleElement(ValidatedConfigurationElement loggerElement) { string minLevel = null; string maxLevel = null; string finalMinLevel = null; string enableLevels = null; string text = null; string text2 = null; bool flag = true; bool flag2 = false; string text3 = null; string filterDefaultAction = null; foreach (KeyValuePair value in loggerElement.Values) { switch (value.Key?.Trim().ToUpperInvariant()) { case "NAME": if (loggerElement.MatchesName("logger")) { text2 = value.Value; } else { text = value.Value; } continue; case "RULENAME": text = value.Value; continue; case "LOGGER": text2 = value.Value; continue; case "ENABLED": flag = ParseBooleanValue(value.Key, value.Value ?? string.Empty, defaultValue: true); continue; case "APPENDTO": text3 = value.Value; continue; case "WRITETO": text3 = value.Value; continue; case "FINAL": flag2 = ParseBooleanValue(value.Key, value.Value ?? string.Empty, defaultValue: false); continue; case "LEVELS": case "LEVEL": enableLevels = value.Value; continue; case "MINLEVEL": minLevel = value.Value; continue; case "MAXLEVEL": maxLevel = value.Value; continue; case "FINALMINLEVEL": finalMinLevel = value.Value; continue; case "FILTERDEFAULTACTION": filterDefaultAction = value.Value; continue; } NLogConfigurationException ex = new NLogConfigurationException("Unrecognized value '" + value.Key + "'='" + value.Value + "' for element '" + loggerElement.Name + "' in section 'rules'"); if (MustThrowConfigException(ex)) { throw ex; } } if (string.IsNullOrEmpty(text) && string.IsNullOrEmpty(text2) && string.IsNullOrEmpty(text3) && !flag2) { InternalLogger.Debug("Logging rule without name or filter or targets is ignored"); return null; } text2 = text2 ?? "*"; if (!flag) { InternalLogger.Debug("Logging rule {0} with name pattern `{1}` is disabled", text, text2); return null; } LoggingRule loggingRule = new LoggingRule(text) { LoggerNamePattern = text2, Final = flag2 }; EnableLevelsForRule(loggingRule, enableLevels, minLevel, maxLevel, finalMinLevel); ParseLoggingRuleTargets(text3, loggingRule); ParseLoggingRuleChildren(loggerElement, loggingRule, filterDefaultAction); ValidateLoggingRuleFilters(loggingRule); return loggingRule; } private void EnableLevelsForRule(LoggingRule rule, string? enableLevels, string? minLevel, string? maxLevel, string? finalMinLevel) { if (enableLevels != null) { enableLevels = ExpandSimpleVariables(enableLevels).Trim(); finalMinLevel = ExpandSimpleVariables(finalMinLevel).Trim(); if (IsLevelLayout(enableLevels) || IsLevelLayout(finalMinLevel)) { SimpleLayout simpleLayout = ParseLevelLayout(enableLevels); SimpleLayout finalMinLevel2 = ParseLevelLayout(finalMinLevel); rule.EnableLoggingForLevelLayout(simpleLayout, finalMinLevel2); return; } string[] array = enableLevels.SplitAndTrimTokens(','); foreach (string levelName in array) { rule.EnableLoggingForLevel(LogLevel.FromString(levelName)); } if (!string.IsNullOrEmpty(finalMinLevel)) { rule.FinalMinLevel = LogLevel.FromString(finalMinLevel); } return; } minLevel = ExpandSimpleVariables(minLevel).Trim(); maxLevel = ExpandSimpleVariables(maxLevel).Trim(); finalMinLevel = ExpandSimpleVariables(finalMinLevel).Trim(); if (IsLevelLayout(minLevel) || IsLevelLayout(maxLevel) || IsLevelLayout(finalMinLevel)) { SimpleLayout simpleLayout2 = ParseLevelLayout(finalMinLevel); SimpleLayout minLevel2 = ParseLevelLayout(minLevel) ?? simpleLayout2; SimpleLayout maxLevel2 = ParseLevelLayout(maxLevel); rule.EnableLoggingForLevelsLayout(minLevel2, maxLevel2, simpleLayout2); return; } LogLevel logLevel = (string.IsNullOrEmpty(finalMinLevel) ? null : LogLevel.FromString(finalMinLevel)); LogLevel minLevel3 = (string.IsNullOrEmpty(minLevel) ? (logLevel ?? LogLevel.MinLevel) : LogLevel.FromString(minLevel)); LogLevel maxLevel3 = (string.IsNullOrEmpty(maxLevel) ? LogLevel.MaxLevel : LogLevel.FromString(maxLevel)); rule.SetLoggingLevels(minLevel3, maxLevel3); if (logLevel != null) { rule.FinalMinLevel = logLevel; } } private static bool IsLevelLayout(string? level) { if (level == null) { return false; } return level.IndexOf('{') >= 0; } private SimpleLayout? ParseLevelLayout(string levelLayout) { if (levelLayout == null || StringHelpers.IsNullOrWhiteSpace(levelLayout)) { return null; } SimpleLayout simpleLayout = CreateSimpleLayout(levelLayout); simpleLayout.Initialize(this); return simpleLayout; } private void ParseLoggingRuleTargets(string? writeTargets, LoggingRule rule) { writeTargets = ExpandSimpleVariables(writeTargets).Trim(); if (string.IsNullOrEmpty(writeTargets)) { return; } string[] array = writeTargets.SplitAndTrimTokens(','); foreach (string text in array) { Target target = FindTargetByName(text); if (target != null) { rule.Targets.Add(target); continue; } NLogConfigurationException ex = new NLogConfigurationException("Target '" + text + "' not found for logging rule: " + (string.IsNullOrEmpty(rule.RuleName) ? rule.LoggerNamePattern : rule.RuleName) + "."); if (MustThrowConfigException(ex)) { throw ex; } } } [Obsolete("Very exotic feature without any unit-tests, not sure if it works. Marked obsolete with NLog v5.3")] private void ParseLoggingRuleChildren(ValidatedConfigurationElement loggerElement, LoggingRule rule, string? filterDefaultAction = null) { foreach (ValidatedConfigurationElement validChild in loggerElement.ValidChildren) { LoggingRule loggingRule = null; if (validChild.MatchesName("filters")) { ParseLoggingRuleFilters(rule, validChild, filterDefaultAction); } else if (validChild.MatchesName("logger") && loggerElement.MatchesName("logger")) { loggingRule = ParseRuleElement(validChild); } else if (validChild.MatchesName("rule") && loggerElement.MatchesName("rule")) { loggingRule = ParseRuleElement(validChild); } else { NLogConfigurationException ex = new NLogConfigurationException("Unrecognized child element '" + validChild.Name + "' for element '" + loggerElement.Name + "' in section 'rules'"); if (MustThrowConfigException(ex)) { throw ex; } } if (loggingRule != null) { ValidateLoggingRuleFilters(rule); lock (rule.ChildRules) { rule.ChildRules.Add(loggingRule); } } } } private void ParseLoggingRuleFilters(LoggingRule rule, ValidatedConfigurationElement filtersElement, string? filterDefaultAction = null) { filtersElement.AssertName("filters"); filterDefaultAction = filtersElement.GetOptionalValue("defaultAction", null) ?? filtersElement.GetOptionalValue("FilterDefaultAction", null) ?? filterDefaultAction; if (filterDefaultAction != null) { if (ConversionHelpers.TryParseEnum(filterDefaultAction, ignoreCase: true, out var resultValue)) { rule.FilterDefaultAction = resultValue; } else { NLogConfigurationException ex = new NLogConfigurationException("Failed to parse Enum-value to assign property 'FilterDefaultAction'='" + filterDefaultAction + "' for logging rule: " + (string.IsNullOrEmpty(rule.RuleName) ? rule.LoggerNamePattern : rule.RuleName) + "."); if (MustThrowConfigException(ex)) { throw ex; } } } foreach (ValidatedConfigurationElement validChild in filtersElement.ValidChildren) { string typeName = validChild.GetOptionalValue("type", null) ?? validChild.Name; Filter filter = FactoryCreateInstance(typeName, ConfigurationItemFactory.Default.FilterFactory); if (filter != null) { ConfigureFromAttributesAndElements(filter, validChild); rule.Filters.Add(filter); } } } private void ValidateLoggingRuleFilters(LoggingRule rule) { bool flag = rule.Filters.Count == 0 || rule.FilterDefaultAction != FilterResult.Ignore; for (int i = 0; i < rule.Filters.Count; i++) { if (rule.Filters[i].Action != FilterResult.Ignore && rule.Filters[i].Action != FilterResult.IgnoreFinal && rule.Filters[i].Action != 0) { flag = true; } } if (!flag) { NLogConfigurationException ex = new NLogConfigurationException($"LoggingRule where all filters and FilterDefaultAction=Ignore : {rule}"); if (MustThrowConfigException(ex)) { throw ex; } } } private void ParseTargetsElement(ValidatedConfigurationElement targetsElement) { targetsElement.AssertName("targets", "appenders"); bool flag = ParseBooleanValue("async", targetsElement.GetOptionalValue("async", "false") ?? string.Empty, defaultValue: false); if (targetsElement.Values.Count > (flag ? 1 : 0)) { foreach (KeyValuePair value in targetsElement.Values) { if (!string.Equals(value.Key?.Trim(), "async", StringComparison.OrdinalIgnoreCase)) { NLogConfigurationException ex = new NLogConfigurationException("Unrecognized value '" + value.Key + "'='" + value.Value + "' in section '" + targetsElement.Name + "'"); if (MustThrowConfigException(ex)) { throw ex; } } } } ValidatedConfigurationElement defaultWrapperElement = null; Dictionary typeNameToDefaultTargetParameters = null; foreach (ValidatedConfigurationElement validChild in targetsElement.ValidChildren) { string configItemTypeAttribute = validChild.GetConfigItemTypeAttribute(); string text = validChild.GetOptionalValue("name", null) ?? string.Empty; text = (string.IsNullOrEmpty(text) ? (validChild.Name ?? string.Empty) : (validChild.Name + "(Name=" + text + ")")); switch (validChild.Name?.Trim().ToUpperInvariant()) { case "DEFAULT-WRAPPER": case "TARGETDEFAULTWRAPPER": if (AssertNonEmptyValue(configItemTypeAttribute, "type", text, targetsElement.Name)) { defaultWrapperElement = validChild; } continue; case "DEFAULT-TARGET-PARAMETERS": case "TARGETDEFAULTPARAMETERS": if (AssertNonEmptyValue(configItemTypeAttribute, "type", text, targetsElement.Name)) { typeNameToDefaultTargetParameters = RegisterNewTargetDefaultParameters(typeNameToDefaultTargetParameters, validChild, configItemTypeAttribute); } continue; case "COMPOUND-TARGET": case "TARGET": case "APPENDER": case "WRAPPER": case "WRAPPER-TARGET": if (AssertNonEmptyValue(configItemTypeAttribute, "type", text, targetsElement.Name)) { AddNewTargetFromConfig(configItemTypeAttribute, validChild, flag, typeNameToDefaultTargetParameters, defaultWrapperElement); } continue; } NLogConfigurationException ex2 = new NLogConfigurationException("Unrecognized element '" + text + "' in section '" + targetsElement.Name + "'"); if (MustThrowConfigException(ex2)) { throw ex2; } } } private static Dictionary RegisterNewTargetDefaultParameters(Dictionary? typeNameToDefaultTargetParameters, ValidatedConfigurationElement targetElement, string targetTypeName) { if (typeNameToDefaultTargetParameters == null) { typeNameToDefaultTargetParameters = new Dictionary(StringComparer.OrdinalIgnoreCase); } typeNameToDefaultTargetParameters[targetTypeName.Trim()] = targetElement; return typeNameToDefaultTargetParameters; } private void AddNewTargetFromConfig(string targetTypeName, ValidatedConfigurationElement targetElement, bool asyncWrap, Dictionary? typeNameToDefaultTargetParameters = null, ValidatedConfigurationElement? defaultWrapperElement = null) { Target target = null; try { target = CreateTargetType(targetTypeName); if (target != null) { ParseTargetElement(target, targetElement, typeNameToDefaultTargetParameters); if (asyncWrap) { target = WrapWithAsyncTargetWrapper(target); } if (defaultWrapperElement != null) { target = WrapWithDefaultWrapper(target, defaultWrapperElement); } AddTarget(target); } } catch (NLogConfigurationException configException) { if (MustThrowConfigException(configException)) { throw; } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } NLogConfigurationException configException2 = new NLogConfigurationException("Target '" + (target?.ToString() ?? targetTypeName) + "' has invalid config. Error: " + ex.Message, ex); if (MustThrowConfigException(configException2)) { throw; } } } private Target? CreateTargetType(string targetTypeName) { return FactoryCreateInstance(targetTypeName, ConfigurationItemFactory.Default.TargetFactory); } private void ParseTargetElement(Target target, ValidatedConfigurationElement targetElement, Dictionary? typeNameToDefaultTargetParameters = null) { string configItemTypeAttribute = targetElement.GetConfigItemTypeAttribute("targets"); if (typeNameToDefaultTargetParameters != null && typeNameToDefaultTargetParameters.TryGetValue(configItemTypeAttribute, out ValidatedConfigurationElement value)) { ParseTargetElement(target, value); } CompoundTargetBase compoundTargetBase = target as CompoundTargetBase; WrapperTargetBase wrapperTargetBase = target as WrapperTargetBase; ConfigureObjectFromAttributes(target, targetElement); foreach (ValidatedConfigurationElement validChild in targetElement.ValidChildren) { if ((compoundTargetBase == null || !ParseCompoundTarget(compoundTargetBase, validChild, typeNameToDefaultTargetParameters, null)) && (wrapperTargetBase == null || !ParseTargetWrapper(wrapperTargetBase, validChild, typeNameToDefaultTargetParameters))) { SetPropertyValuesFromElement(target, validChild, targetElement); } } } private bool ParseTargetWrapper(WrapperTargetBase wrapper, ValidatedConfigurationElement childElement, Dictionary? typeNameToDefaultTargetParameters) { if (IsTargetRefElement(childElement.Name)) { string requiredValue = childElement.GetRequiredValue("name", GetName(wrapper)); Target target = FindTargetByName(requiredValue); if (target == null) { NLogConfigurationException ex = new NLogConfigurationException("Referenced target '" + requiredValue + "' not found."); if (MustThrowConfigException(ex)) { throw ex; } } wrapper.WrappedTarget = target; return true; } if (IsTargetElement(childElement.Name)) { string configItemTypeAttribute = childElement.GetConfigItemTypeAttribute(GetName(wrapper)); Target target2 = CreateTargetType(configItemTypeAttribute); if (target2 != null) { ParseTargetElement(target2, childElement, typeNameToDefaultTargetParameters); if (!string.IsNullOrEmpty(target2.Name)) { AddTarget(target2.Name, target2); } else if (!string.IsNullOrEmpty(wrapper.Name)) { target2.Name = wrapper.Name + "_wrapped"; } if (wrapper.WrappedTarget != null) { NLogConfigurationException ex2 = new NLogConfigurationException("Failed to assign wrapped target " + configItemTypeAttribute + ", because target " + wrapper.Name + " already has one."); if (MustThrowConfigException(ex2)) { throw ex2; } } } wrapper.WrappedTarget = target2; return true; } return false; } private bool ParseCompoundTarget(CompoundTargetBase compound, ValidatedConfigurationElement childElement, Dictionary? typeNameToDefaultTargetParameters, string? targetName) { if (MatchesName(childElement.Name, "targets") || MatchesName(childElement.Name, "appenders")) { foreach (ValidatedConfigurationElement validChild in childElement.ValidChildren) { ParseCompoundTarget(compound, validChild, typeNameToDefaultTargetParameters, null); } return true; } if (IsTargetRefElement(childElement.Name)) { targetName = childElement.GetRequiredValue("name", GetName(compound)); Target target = FindTargetByName(targetName); if (target == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } compound.Targets.Add(target); return true; } if (IsTargetElement(childElement.Name)) { string configItemTypeAttribute = childElement.GetConfigItemTypeAttribute(GetName(compound)); Target target2 = CreateTargetType(configItemTypeAttribute); if (target2 != null) { if (targetName != null) { target2.Name = targetName; } ParseTargetElement(target2, childElement, typeNameToDefaultTargetParameters); if (target2.Name != null) { AddTarget(target2.Name, target2); } compound.Targets.Add(target2); } return true; } return false; } private void ConfigureObjectFromAttributes(T targetObject, ValidatedConfigurationElement element, bool ignoreType = true) where T : class { foreach (KeyValuePair value2 in element.Values) { string key = value2.Key; string value = value2.Value; if (!ignoreType || !MatchesName(key, "type")) { SetPropertyValueFromString(targetObject, key, value, element); } } } private void SetPropertyValueFromString(T targetObject, string propertyName, string? propertyValue, ValidatedConfigurationElement element) where T : class { try { if (targetObject == null) { throw new NLogConfigurationException("'" + typeof(T).Name + "' is null, and cannot assign property '" + propertyName + "'='" + propertyValue + "'"); } if (!PropertyHelper.TryGetPropertyInfo(ConfigurationItemFactory.Default, targetObject, propertyName, out PropertyInfo result) || (object)result == null) { throw new NLogConfigurationException("'" + targetObject.GetType()?.Name + "' cannot assign unknown property '" + propertyName + "'='" + propertyValue + "'"); } string matchingVariableName; string stringValue = ExpandSimpleVariables(propertyValue, out matchingVariableName); if (matchingVariableName != null && TryLookupDynamicVariable(matchingVariableName, out Layout value) && result.PropertyType.IsAssignableFrom(value.GetType())) { PropertyHelper.SetPropertyValueForObject(targetObject, value, result); } else { PropertyHelper.SetPropertyFromString(targetObject, result, stringValue, ConfigurationItemFactory.Default); } } catch (NLogConfigurationException configException) { if (MustThrowConfigException(configException)) { throw; } } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } NLogConfigurationException configException2 = new NLogConfigurationException("'" + targetObject.GetType()?.Name + "' cannot assign property '" + propertyName + "'='" + propertyValue + "' in section '" + element.Name + "'. Error: " + ex.Message, ex); if (MustThrowConfigException(configException2)) { throw; } } } private void SetPropertyValuesFromElement(T targetObject, ValidatedConfigurationElement childElement, ILoggingConfigurationElement parentElement) where T : class { PropertyInfo result; object propertyValue; if (targetObject == null) { NLogConfigurationException ex = new NLogConfigurationException("'" + typeof(T).Name + "' is null, and cannot assign property '" + childElement.Name + "' in section '" + parentElement.Name + "'"); if (MustThrowConfigException(ex)) { throw ex; } } else if (!PropertyHelper.TryGetPropertyInfo(ConfigurationItemFactory.Default, targetObject, childElement.Name, out result) || (object)result == null) { NLogConfigurationException ex2 = new NLogConfigurationException("'" + targetObject.GetType()?.Name + "' cannot assign unknown property '" + childElement.Name + "' in section '" + parentElement.Name + "'"); if (MustThrowConfigException(ex2)) { throw ex2; } } else if (!AddArrayItemFromElement(targetObject, result, childElement) && !SetLayoutFromElement(targetObject, result, childElement) && !SetFilterFromElement(targetObject, result, childElement) && TryGetPropertyValue(targetObject, result, out propertyValue) && propertyValue != null) { ConfigureFromAttributesAndElements(propertyValue, childElement); } } private bool TryGetPropertyValue(T targetObject, PropertyInfo propInfo, out object? propertyValue) where T : class { try { propertyValue = propInfo.GetValue(targetObject, null); return true; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } NLogConfigurationException ex2 = new NLogConfigurationException("Failed getting property " + propInfo.Name + " for type: " + typeof(T).Name, ex); if (MustThrowConfigException(ex2)) { throw ex2; } propertyValue = null; return false; } } private bool AddArrayItemFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element) { Type arrayItemType = PropertyHelper.GetArrayItemType(propInfo); if (arrayItemType != null && TryGetPropertyValue(o, propInfo, out object propertyValue) && propertyValue != null) { IList list = (IList)propertyValue; if (string.Equals(propInfo.Name, element.Name, StringComparison.OrdinalIgnoreCase)) { bool flag = false; foreach (ValidatedConfigurationElement validChild in element.ValidChildren) { flag = true; list.Add(ParseArrayItemFromElement(arrayItemType, validChild)); } if (flag) { return true; } } object value = ParseArrayItemFromElement(arrayItemType, element); list.Add(value); return true; } return false; } private object? ParseArrayItemFromElement(Type elementType, ValidatedConfigurationElement element) { object instance = TryCreateLayoutInstance(element, elementType); if (instance == null) { if (!ConfigurationItemFactory.Default.TryCreateInstance(elementType, out instance) || instance == null) { throw new NLogConfigurationException($"Factory returned null for {elementType}"); } ConfigureFromAttributesAndElements(instance, element); } return instance; } private bool SetLayoutFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element) { Layout layout = TryCreateLayoutInstance(element, propInfo.PropertyType); if (layout != null) { PropertyHelper.SetPropertyValueForObject(o, layout, propInfo); return true; } return false; } private bool SetFilterFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element) { Filter filter = TryCreateFilterInstance(element, propInfo.PropertyType); if (filter != null) { PropertyHelper.SetPropertyValueForObject(o, filter, propInfo); return true; } return false; } private SimpleLayout CreateSimpleLayout(string layoutText) { return new SimpleLayout(layoutText, ConfigurationItemFactory.Default, base.LogFactory.ThrowConfigExceptions); } private Layout? TryCreateLayoutInstance(ValidatedConfigurationElement element, Type type) { if (!typeof(Layout).IsAssignableFrom(type)) { return null; } string configItemTypeAttribute = element.GetConfigItemTypeAttribute(); if (string.IsNullOrEmpty(configItemTypeAttribute)) { return null; } string matchingVariableName; string text = ExpandSimpleVariables(configItemTypeAttribute, out matchingVariableName); if (matchingVariableName != null && TryLookupDynamicVariable(matchingVariableName, out Layout value) && type.IsAssignableFrom(value.GetType())) { return value; } if ("SimpleLayout".Equals(text, StringComparison.OrdinalIgnoreCase) && TryCreateSimpleLayoutInstance(element, out SimpleLayout simpleLayout)) { return simpleLayout; } Layout layout = FactoryCreateInstance(text, ConfigurationItemFactory.Default.LayoutFactory); if (layout != null) { ConfigureFromAttributesAndElements(layout, element); return layout; } return null; } private bool TryCreateSimpleLayoutInstance(ValidatedConfigurationElement element, out SimpleLayout? simpleLayout) { if (!element.ValidChildren.Any()) { ICollection> values = element.Values; if (values.Count == 2) { string text = ("Text".Equals(values.First().Key, StringComparison.OrdinalIgnoreCase) ? (values.First().Value ?? string.Empty) : null) ?? ("Text".Equals(values.Last().Key, StringComparison.OrdinalIgnoreCase) ? (values.Last().Value ?? string.Empty) : null); if (text != null) { string txt = ExpandSimpleVariables(text); simpleLayout = (string.IsNullOrEmpty(text) ? SimpleLayout.Default : new SimpleLayout(txt, ConfigurationItemFactory.Default)); return true; } } } simpleLayout = null; return false; } private Filter? TryCreateFilterInstance(ValidatedConfigurationElement element, Type type) { Filter filter = TryCreateInstance(element, type, ConfigurationItemFactory.Default.FilterFactory); if (filter != null) { ConfigureFromAttributesAndElements(filter, element); return filter; } return null; } private T? TryCreateInstance(ValidatedConfigurationElement element, Type type, IFactory factory) where T : class { if (!typeof(T).IsAssignableFrom(type)) { return null; } string configItemTypeAttribute = element.GetConfigItemTypeAttribute(); if (string.IsNullOrEmpty(configItemTypeAttribute)) { return null; } return FactoryCreateInstance(configItemTypeAttribute, factory); } private T? FactoryCreateInstance(string typeName, IFactory factory) where T : class { T result = null; try { typeName = ExpandSimpleVariables(typeName).Trim(); if (typeName.Contains(',')) { string text = typeName.Substring(0, typeName.IndexOf(',')).Trim(); if (factory.TryCreateInstance(text, out result) && result != null) { return result; } string text2 = typeName.Substring(typeName.IndexOf(',') + 1).Trim(); if (!string.IsNullOrEmpty(text2) && RegisterExtensionFromAssemblyName(text2, typeName)) { typeName = text; } } result = factory.CreateInstance(typeName); if (result == null) { throw new NLogConfigurationException("Failed to create " + typeof(T).Name + " of type: '" + typeName + "' - Factory returned null"); } } catch (NLogConfigurationException ex) { InternalLogger.Error(ex, ex.Message); if (MustThrowConfigException(ex)) { throw; } } catch (Exception ex2) { if (ex2.MustBeRethrownImmediately()) { throw; } NLogConfigurationException ex3 = new NLogConfigurationException("Failed to create " + typeof(T).Name + " of type: " + typeName, ex2); InternalLogger.Error(ex3, "Failed to create " + typeof(T).Name + " of type: " + typeName); if (MustThrowConfigException(ex3)) { throw ex3; } } return result; } private void ConfigureFromAttributesAndElements(T targetObject, ValidatedConfigurationElement element) where T : class { ConfigureObjectFromAttributes(targetObject, element); foreach (ValidatedConfigurationElement validChild in element.ValidChildren) { SetPropertyValuesFromElement(targetObject, validChild, element); } } private static Target WrapWithAsyncTargetWrapper(Target target) { if (target is AsyncTaskTarget) { InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name); return target; } if (target is AsyncTargetWrapper) { InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name); return target; } AsyncTargetWrapper asyncTargetWrapper = new AsyncTargetWrapper(); asyncTargetWrapper.WrappedTarget = target; asyncTargetWrapper.Name = target.Name; target.Name += "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}'", asyncTargetWrapper.Name, target.Name); target = asyncTargetWrapper; return target; } private Target WrapWithDefaultWrapper(Target target, ValidatedConfigurationElement defaultWrapperElement) { string configItemTypeAttribute = defaultWrapperElement.GetConfigItemTypeAttribute("targets"); if (!(CreateTargetType(configItemTypeAttribute) is WrapperTargetBase wrapperTargetBase)) { throw new NLogConfigurationException("Target type '" + configItemTypeAttribute + "' cannot be used as default target wrapper."); } WrapperTargetBase wrapperTargetBase2 = wrapperTargetBase; ParseTargetElement(wrapperTargetBase, defaultWrapperElement); while (wrapperTargetBase2.WrappedTarget != null) { if (wrapperTargetBase2.WrappedTarget is WrapperTargetBase wrapperTargetBase3) { wrapperTargetBase2 = wrapperTargetBase3; continue; } throw new NLogConfigurationException($"Target type '{configItemTypeAttribute}' with nested {wrapperTargetBase2.WrappedTarget.GetType()} cannot be used as default target wrapper."); } if (target is AsyncTaskTarget && wrapperTargetBase is AsyncTargetWrapper && wrapperTargetBase == wrapperTargetBase2) { InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name); return target; } wrapperTargetBase2.WrappedTarget = target; wrapperTargetBase.Name = target.Name; target.Name += "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}'", wrapperTargetBase.Name, wrapperTargetBase.GetType(), target.Name); return wrapperTargetBase; } private bool ParseBooleanValue(string propertyName, string value, bool defaultValue) { try { return Convert.ToBoolean(value?.Trim(), CultureInfo.InvariantCulture); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } NLogConfigurationException ex2 = new NLogConfigurationException($"'{propertyName}' hasn't a valid boolean value '{value}'. {defaultValue} will be used", ex); if (MustThrowConfigException(ex2)) { throw ex2; } return defaultValue; } } private bool? ParseNullableBooleanValue(string propertyName, string value, bool defaultValue) { if (!StringHelpers.IsNullOrWhiteSpace(value)) { return ParseBooleanValue(propertyName, value, defaultValue); } return null; } private bool MustThrowConfigException(NLogConfigurationException configException) { if (configException.MustBeRethrown()) { return true; } if (base.LogFactory.ThrowConfigExceptions ?? base.LogFactory.ThrowExceptions) { return true; } return false; } private static bool MatchesName(string key, string expectedKey) { return string.Equals(key?.Trim(), expectedKey, StringComparison.OrdinalIgnoreCase); } private static bool IsTargetElement(string name) { if (!name.Equals("target", StringComparison.OrdinalIgnoreCase) && !name.Equals("wrapper", StringComparison.OrdinalIgnoreCase) && !name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase)) { return name.Equals("compound-target", StringComparison.OrdinalIgnoreCase); } return true; } private static bool IsTargetRefElement(string name) { if (!name.Equals("target-ref", StringComparison.OrdinalIgnoreCase) && !name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase)) { return name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase); } return true; } private static string GetName(Target target) { if (!string.IsNullOrEmpty(target.Name)) { return target.Name; } return target.GetType().Name; } } [NLogConfigurationItem] public class LoggingRule { private ILoggingRuleLevelFilter _logLevelFilter = LoggingRuleLevelFilter.Off; private LoggerNameMatcher _loggerNameMatcher = LoggerNameMatcher.Off; private readonly List _targets = new List(); [Obsolete("Very exotic feature without any unit-tests, not sure if it works. Marked obsolete with NLog v5.3")] private readonly List _childRules = new List(); public string? RuleName { get; set; } public IList Targets => _targets; [Obsolete("Very exotic feature without any unit-tests, not sure if it works. Marked obsolete with NLog v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public IList ChildRules => _childRules; public IList Filters { get; } = new List(); public bool Final { get; set; } public LogLevel? FinalMinLevel { get { return _logLevelFilter.FinalMinLevel; } set { _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetFinalMinLevel(value); } } public string LoggerNamePattern { get { return _loggerNameMatcher.Pattern; } set { _loggerNameMatcher = LoggerNameMatcher.Create(value); } } internal bool[] LogLevels => _logLevelFilter.LogLevels; [NLogConfigurationIgnoreProperty] public ReadOnlyCollection Levels { get { List list = new List(); bool[] logLevels = _logLevelFilter.LogLevels; for (int i = LogLevel.MinLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; i++) { if (logLevels[i]) { list.Add(LogLevel.FromOrdinal(i)); } } return list.AsReadOnly(); } } [Obsolete("Replaced by FilterDefaultAction. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public FilterResult DefaultFilterResult { get { return FilterDefaultAction; } set { FilterDefaultAction = value; } } public FilterResult FilterDefaultAction { get; set; } = FilterResult.Ignore; public LoggingRule() { } public LoggingRule(string? ruleName) { RuleName = ruleName; } public LoggingRule(string loggerNamePattern, LogLevel minLevel, LogLevel maxLevel, Target target) { Guard.ThrowIfNull(target, "target"); LoggerNamePattern = loggerNamePattern; _targets.Add(target); EnableLoggingForLevels(minLevel, maxLevel); } public LoggingRule(string loggerNamePattern, LogLevel minLevel, Target target) { Guard.ThrowIfNull(target, "target"); LoggerNamePattern = loggerNamePattern; _targets.Add(target); EnableLoggingForLevels(minLevel, LogLevel.MaxLevel); } public LoggingRule(string loggerNamePattern, Target target) { Guard.ThrowIfNull(target, "target"); LoggerNamePattern = loggerNamePattern; _targets.Add(target); } [Obsolete("Very exotic feature without any unit-tests, not sure if it works. Marked obsolete with NLog v5.3")] internal LoggingRule[] GetChildRulesThreadSafe() { lock (_childRules) { return _childRules.ToArray(); } } internal Target[] GetTargetsThreadSafe() { lock (_targets) { return (_targets.Count == 0) ? ArrayHelper.Empty() : _targets.ToArray(); } } internal bool RemoveTargetThreadSafe(Target target) { lock (_targets) { return _targets.Remove(target); } } public void EnableLoggingForLevel(LogLevel level) { if (!(level == LogLevel.Off)) { Guard.ThrowIfNull(level, "level"); _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(level, level, enable: true); } } public void EnableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel) { if (!(minLevel == LogLevel.Off)) { Guard.ThrowIfNull(minLevel, "minLevel"); Guard.ThrowIfNull(maxLevel, "maxLevel"); _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(minLevel, maxLevel, enable: true); } } internal void EnableLoggingForLevelLayout(SimpleLayout? simpleLayout, SimpleLayout? finalMinLevel) { _logLevelFilter = new DynamicLogLevelFilter(this, simpleLayout, finalMinLevel); } internal void EnableLoggingForLevelsLayout(SimpleLayout? minLevel, SimpleLayout? maxLevel, SimpleLayout? finalMinLevel) { _logLevelFilter = new DynamicRangeLevelFilter(this, minLevel, maxLevel, finalMinLevel); } public void DisableLoggingForLevel(LogLevel level) { if (!(level == LogLevel.Off)) { Guard.ThrowIfNull(level, "level"); _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(level, level, enable: false); } } public void DisableLoggingForLevels(LogLevel minLevel, LogLevel maxLevel) { if (!(minLevel == LogLevel.Off)) { Guard.ThrowIfNull(minLevel, "minLevel"); Guard.ThrowIfNull(maxLevel, "maxLevel"); _logLevelFilter = _logLevelFilter.GetSimpleFilterForUpdate().SetLoggingLevels(minLevel, maxLevel, enable: false); } } public void SetLoggingLevels(LogLevel minLevel, LogLevel maxLevel) { DisableLoggingForLevels(LogLevel.MinLevel, LogLevel.MaxLevel); EnableLoggingForLevels(minLevel, maxLevel); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(_loggerNameMatcher.ToString()); stringBuilder.Append(" levels: [ "); Target[] targetsThreadSafe = GetTargetsThreadSafe(); bool[] logLevels = _logLevelFilter.LogLevels; for (int i = 0; i < logLevels.Length; i++) { if (targetsThreadSafe.Length == 0 && !Final && FinalMinLevel != null) { if (i < FinalMinLevel.Ordinal) { stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0} ", LogLevel.FromOrdinal(i).ToString()); } } else if (logLevels[i]) { stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0} ", LogLevel.FromOrdinal(i).ToString()); } } stringBuilder.Append("] writeTo: [ "); Target[] array = targetsThreadSafe; foreach (Target target in array) { string arg = (string.IsNullOrEmpty(target.Name) ? target.ToString() : target.Name); stringBuilder.AppendFormat(CultureInfo.InvariantCulture, "{0} ", arg); } stringBuilder.Append(']'); if (Final) { stringBuilder.Append(" final: True"); } if (FinalMinLevel != null) { stringBuilder.Append(" finalMinLevel: ").Append(FinalMinLevel); } return stringBuilder.ToString(); } public bool IsLoggingEnabledForLevel(LogLevel level) { if (level == LogLevel.Off) { return false; } return _logLevelFilter.LogLevels[level.Ordinal]; } public bool NameMatches(string loggerName) { return _loggerNameMatcher.NameMatches(loggerName); } } internal sealed class LoggingRuleLevelFilter : ILoggingRuleLevelFilter { public static readonly ILoggingRuleLevelFilter Off = new LoggingRuleLevelFilter(); public bool[] LogLevels { get; } public LogLevel? FinalMinLevel { get; private set; } public LoggingRuleLevelFilter(bool[]? logLevels = null, LogLevel? finalMinLevel = null) { LogLevels = new bool[LogLevel.MaxLevel.Ordinal + 1]; if (logLevels != null) { for (int i = 0; i < Math.Min(logLevels.Length, LogLevels.Length); i++) { LogLevels[i] = logLevels[i]; } } FinalMinLevel = finalMinLevel; } public LoggingRuleLevelFilter GetSimpleFilterForUpdate() { if (this == Off) { return new LoggingRuleLevelFilter(); } return this; } public LoggingRuleLevelFilter SetLoggingLevels(LogLevel minLevel, LogLevel maxLevel, bool enable) { for (int i = minLevel.Ordinal; i <= Math.Min(maxLevel.Ordinal, LogLevels.Length - 1); i++) { LogLevels[i] = enable; } return this; } public LoggingRuleLevelFilter SetFinalMinLevel(LogLevel? finalMinLevel) { FinalMinLevel = finalMinLevel; return this; } } internal sealed class MethodFactory : IFactory { private readonly struct MethodDetails { public readonly MethodInfo MethodInfo; public readonly Func NoParameters; public readonly Func OneParameter; public readonly Func TwoParameters; public readonly Func ThreeParameters; public readonly Func ManyParameters; public readonly int ManyParameterMinCount; public readonly int ManyParameterMaxCount; public readonly bool ManyParameterWithLogEvent; public MethodDetails(MethodInfo methodInfo, Func noParameters, Func oneParameter, Func twoParameters, Func threeParameters, Func manyParameters, int manyParameterMinCount, int manyParameterMaxCount, bool manyParameterWithLogEvent) { MethodInfo = methodInfo; NoParameters = noParameters; OneParameter = oneParameter; TwoParameters = twoParameters; ThreeParameters = threeParameters; ManyParameters = manyParameters; ManyParameterMinCount = manyParameterMinCount; ManyParameterMaxCount = manyParameterMaxCount; ManyParameterWithLogEvent = manyParameterWithLogEvent; } } private readonly Dictionary _nameToMethodDetails = new Dictionary(StringComparer.OrdinalIgnoreCase); public bool Initialized { get; private set; } public void Initialize(Action itemRegistration) { lock (ConfigurationItemFactory.SyncRoot) { if (Initialized) { return; } try { bool obj = _nameToMethodDetails.Count != 0; itemRegistration(obj); } finally { Initialized = true; } } } public bool CheckTypeAliasExists(string typeAlias) { return _nameToMethodDetails.ContainsKey(typeAlias); } void IFactory.RegisterType([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicProperties)] Type type, string itemNamePrefix) { if (!type.IsClass) { return; } IList> list = ExtractClassMethods(type); if (list != null && list.Count > 0) { for (int i = 0; i < list.Count; i++) { string methodName = (string.IsNullOrEmpty(itemNamePrefix) ? list[i].Key : (itemNamePrefix + list[i].Key)); RegisterDefinition(methodName, list[i].Value); } } } private static IList> ExtractClassMethods([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type) where TClassAttributeType : Attribute where TMethodAttributeType : NameBaseAttribute { if (!type.IsDefined(typeof(TClassAttributeType), inherit: false)) { return ArrayHelper.Empty>(); } List> list = new List>(); MethodInfo[] methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { TMethodAttributeType[] array = (TMethodAttributeType[])methodInfo.GetCustomAttributes(typeof(TMethodAttributeType), inherit: false); foreach (TMethodAttributeType val in array) { list.Add(new KeyValuePair(val.Name, methodInfo)); } } return list; } public void Clear() { lock (_nameToMethodDetails) { _nameToMethodDetails.Clear(); } } internal void RegisterDefinition(string methodName, MethodInfo methodInfo) { MethodInfo methodInfo2 = methodInfo; int manyParameterMinCount; int manyParameterMaxCount; bool includeLogEvent; object?[] defaultMethodParameters = ResolveDefaultMethodParameters(methodInfo2, out manyParameterMinCount, out manyParameterMaxCount, out includeLogEvent); if (manyParameterMaxCount > 0) { RegisterManyParameters(methodName, (object?[] inputArgs) => InvokeMethodInfo(methodInfo2, ResolveMethodParameters(defaultMethodParameters, inputArgs)), manyParameterMinCount, manyParameterMaxCount, includeLogEvent, methodInfo2); } if (manyParameterMinCount == 0) { if (!includeLogEvent) { RegisterNoParameters(methodName, (LogEventInfo logEvent) => InvokeMethodInfo(methodInfo2, defaultMethodParameters), methodInfo2); } else { RegisterNoParameters(methodName, (LogEventInfo logEvent) => InvokeMethodInfo(methodInfo2, ResolveMethodParameters(defaultMethodParameters, logEvent)), methodInfo2); } } if (manyParameterMinCount <= 1 && manyParameterMaxCount >= 1) { if (!includeLogEvent) { RegisterOneParameter(methodName, (LogEventInfo logEvent, object? arg1) => InvokeMethodInfo(methodInfo2, ResolveMethodParameters(defaultMethodParameters, arg1)), methodInfo2); } else { RegisterOneParameter(methodName, (LogEventInfo logEvent, object? arg1) => InvokeMethodInfo(methodInfo2, ResolveMethodParameters(defaultMethodParameters, logEvent, arg1)), methodInfo2); } } if (manyParameterMinCount <= 2 && manyParameterMaxCount >= 2) { if (!includeLogEvent) { RegisterTwoParameters(methodName, (LogEventInfo logEvent, object? arg1, object? arg2) => InvokeMethodInfo(methodInfo2, ResolveMethodParameters(defaultMethodParameters, arg1, arg2)), methodInfo2); } else { RegisterTwoParameters(methodName, (LogEventInfo logEvent, object? arg1, object? arg2) => InvokeMethodInfo(methodInfo2, ResolveMethodParameters(defaultMethodParameters, logEvent, arg1, arg2)), methodInfo2); } } if (manyParameterMinCount > 3 || manyParameterMaxCount < 3) { return; } if (!includeLogEvent) { RegisterThreeParameters(methodName, (LogEventInfo logEvent, object? arg1, object? arg2, object? arg3) => InvokeMethodInfo(methodInfo2, ResolveMethodParameters(defaultMethodParameters, arg1, arg2, arg3)), methodInfo2); } else { RegisterThreeParameters(methodName, (LogEventInfo logEvent, object? arg1, object? arg2, object? arg3) => InvokeMethodInfo(methodInfo2, ResolveMethodParameters(defaultMethodParameters, logEvent, arg1, arg2, arg3)), methodInfo2); } } private static object? InvokeMethodInfo(MethodInfo methodInfo, object?[] methodArgs) { try { return methodInfo.Invoke(null, methodArgs); } catch (TargetInvocationException ex) { if (ex.InnerException == null) { throw; } throw ex.InnerException; } } private static object?[] ResolveDefaultMethodParameters(MethodInfo methodInfo, out int manyParameterMinCount, out int manyParameterMaxCount, out bool includeLogEvent) { ParameterInfo[] parameters = methodInfo.GetParameters(); manyParameterMinCount = 0; manyParameterMaxCount = parameters.Length; object[] array = new object[parameters.Length]; for (int i = 0; i < array.Length; i++) { if (parameters[i].IsOptional) { array[i] = parameters[i].DefaultValue; } else { manyParameterMinCount++; } } includeLogEvent = parameters.Length != 0 && parameters[0].ParameterType == typeof(LogEventInfo); if (includeLogEvent) { manyParameterMaxCount--; if (manyParameterMinCount > 0) { manyParameterMinCount--; } } return array; } private static object?[] ResolveMethodParameters(object?[] defaultMethodParameters, object?[] inputParameters) { if (defaultMethodParameters.Length == inputParameters.Length) { return inputParameters; } object[] array = new object[defaultMethodParameters.Length]; for (int i = 0; i < inputParameters.Length; i++) { array[i] = inputParameters[i]; } for (int j = inputParameters.Length; j < defaultMethodParameters.Length; j++) { array[j] = defaultMethodParameters[j]; } return array; } private static object?[] ResolveMethodParameters(object?[] defaultMethodParameters, object? inputParameterArg1) { object[] array = new object[defaultMethodParameters.Length]; array[0] = inputParameterArg1; for (int i = 1; i < defaultMethodParameters.Length; i++) { array[i] = defaultMethodParameters[i]; } return array; } private static object?[] ResolveMethodParameters(object?[] defaultMethodParameters, object? inputParameterArg1, object? inputParameterArg2) { object[] array = new object[defaultMethodParameters.Length]; array[0] = inputParameterArg1; array[1] = inputParameterArg2; for (int i = 2; i < defaultMethodParameters.Length; i++) { array[i] = defaultMethodParameters[i]; } return array; } private static object?[] ResolveMethodParameters(object?[] defaultMethodParameters, object? inputParameterArg1, object? inputParameterArg2, object? inputParameterArg3) { object[] array = new object[defaultMethodParameters.Length]; array[0] = inputParameterArg1; array[1] = inputParameterArg2; array[2] = inputParameterArg3; for (int i = 3; i < defaultMethodParameters.Length; i++) { array[i] = defaultMethodParameters[i]; } return array; } private static object?[] ResolveMethodParameters(object?[] defaultMethodParameters, object? inputParameterArg1, object? inputParameterArg2, object? inputParameterArg3, object? inputParameterArg4) { object[] array = new object[defaultMethodParameters.Length]; array[0] = inputParameterArg1; array[1] = inputParameterArg2; array[2] = inputParameterArg3; array[3] = inputParameterArg4; for (int i = 4; i < defaultMethodParameters.Length; i++) { array[i] = defaultMethodParameters[i]; } return array; } public void RegisterNoParameters(string methodName, Func noParameters, MethodInfo? legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var value); legacyMethodInfo = legacyMethodInfo ?? value.MethodInfo ?? noParameters.Method; _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, noParameters, value.OneParameter, value.TwoParameters, value.ThreeParameters, value.ManyParameters, value.ManyParameterMinCount, value.ManyParameterMaxCount, value.ManyParameterWithLogEvent); } } public void RegisterOneParameter(string methodName, Func oneParameter, MethodInfo? legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var value); legacyMethodInfo = legacyMethodInfo ?? value.MethodInfo ?? oneParameter.Method; _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, value.NoParameters, oneParameter, value.TwoParameters, value.ThreeParameters, value.ManyParameters, value.ManyParameterMinCount, value.ManyParameterMaxCount, value.ManyParameterWithLogEvent); } } public void RegisterTwoParameters(string methodName, Func twoParameters, MethodInfo? legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var value); legacyMethodInfo = legacyMethodInfo ?? value.MethodInfo ?? twoParameters.Method; _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, value.NoParameters, value.OneParameter, twoParameters, value.ThreeParameters, value.ManyParameters, value.ManyParameterMinCount, value.ManyParameterMaxCount, value.ManyParameterWithLogEvent); } } public void RegisterThreeParameters(string methodName, Func threeParameters, MethodInfo? legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var value); legacyMethodInfo = legacyMethodInfo ?? value.MethodInfo ?? threeParameters.Method; _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, value.NoParameters, value.OneParameter, value.TwoParameters, threeParameters, value.ManyParameters, value.ManyParameterMinCount, value.ManyParameterMaxCount, value.ManyParameterWithLogEvent); } } public void RegisterManyParameters(string methodName, Func manyParameters, int manyParameterMinCount, int manyParameterMaxCount, bool manyParameterWithLogEvent, MethodInfo? legacyMethodInfo = null) { lock (_nameToMethodDetails) { _nameToMethodDetails.TryGetValue(methodName, out var value); legacyMethodInfo = legacyMethodInfo ?? value.MethodInfo ?? manyParameters.Method; _nameToMethodDetails[methodName] = new MethodDetails(legacyMethodInfo, value.NoParameters, value.OneParameter, value.TwoParameters, value.ThreeParameters, manyParameters, manyParameterMinCount, manyParameterMaxCount, manyParameterWithLogEvent); } } public Func? TryCreateInstanceWithNoParameters(string methodName) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var value)) { return value.NoParameters; } return null; } } public Func? TryCreateInstanceWithOneParameter(string methodName) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var value)) { return value.OneParameter; } return null; } } public Func? TryCreateInstanceWithTwoParameters(string methodName) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var value)) { return value.TwoParameters; } return null; } } public Func? TryCreateInstanceWithThreeParameters(string methodName) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var value)) { return value.ThreeParameters; } return null; } } public Func? TryCreateInstanceWithManyParameters(string methodName, out int manyParameterMinCount, out int manyParameterMaxCount, out bool manyParameterWithLogEvent) { lock (_nameToMethodDetails) { if (_nameToMethodDetails.TryGetValue(methodName, out var methodDetails)) { if (methodDetails.ManyParameters != null) { manyParameterMaxCount = methodDetails.ManyParameterMaxCount; manyParameterMinCount = methodDetails.ManyParameterMinCount; manyParameterWithLogEvent = methodDetails.ManyParameterWithLogEvent; return methodDetails.ManyParameters; } if (methodDetails.ThreeParameters != null) { manyParameterMaxCount = 3; manyParameterMinCount = ((methodDetails.TwoParameters == null) ? 3 : 2); manyParameterWithLogEvent = true; return (object?[] args) => methodDetails.ThreeParameters((LogEventInfo)(args[0] ?? throw new ArgumentNullException("LogEventInfo")), args[1], args[2], args[3]); } if (methodDetails.TwoParameters != null) { manyParameterMaxCount = 2; manyParameterMinCount = ((methodDetails.OneParameter != null) ? 1 : 2); manyParameterWithLogEvent = true; return (object?[] args) => methodDetails.TwoParameters((LogEventInfo)(args[0] ?? throw new ArgumentNullException("LogEventInfo")), args[1], args[2]); } if (methodDetails.OneParameter != null) { manyParameterMaxCount = 1; manyParameterMinCount = ((methodDetails.NoParameters == null) ? 1 : 0); manyParameterWithLogEvent = true; return (object?[] args) => methodDetails.OneParameter((LogEventInfo)(args[0] ?? throw new ArgumentNullException("LogEventInfo")), args[1]); } if (methodDetails.NoParameters != null) { manyParameterMaxCount = 0; manyParameterMinCount = 0; manyParameterWithLogEvent = true; return (object?[] args) => methodDetails.NoParameters((LogEventInfo)(args[0] ?? throw new ArgumentNullException("LogEventInfo"))); } } manyParameterMinCount = 0; manyParameterMaxCount = 0; manyParameterWithLogEvent = false; return null; } } } [Obsolete("Marked obsolete on NLog 5.3, instead use ThreadAgnosticImmutableAttribute")] [AttributeUsage(AttributeTargets.Class)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed class MutableUnsafeAttribute : Attribute { } [MeansImplicitUse] public abstract class NameBaseAttribute : Attribute { public string Name { get; } protected NameBaseAttribute(string name) { Name = name; } } [AttributeUsage(AttributeTargets.Property)] public sealed class NLogConfigurationIgnorePropertyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class)] [MeansImplicitUse] public sealed class NLogConfigurationItemAttribute : Attribute { } public sealed class NLogDependencyResolveException : Exception { public Type ServiceType { get; } public NLogDependencyResolveException(string message, Type serviceType) : base(CreateFullMessage(serviceType, message)) { ServiceType = Guard.ThrowIfNull(serviceType, "serviceType"); } public NLogDependencyResolveException(string message, Exception innerException, Type serviceType) : base(CreateFullMessage(serviceType, message), innerException) { ServiceType = Guard.ThrowIfNull(serviceType, "serviceType"); } private static string CreateFullMessage(Type typeToResolve, string message) { return ("Cannot resolve the type: '" + typeToResolve.Name + "'. " + message).Trim(); } } internal sealed class PropertyTypeConverter : IPropertyTypeConverter { private static Dictionary>? _stringConverters; public static PropertyTypeConverter Instance { get; } = new PropertyTypeConverter(); private static Dictionary> StringConverterLookup => _stringConverters ?? (_stringConverters = BuildStringConverterLookup()); private static Dictionary> BuildStringConverterLookup() { return new Dictionary> { { typeof(Encoding), (string stringvalue, string? format, IFormatProvider? formatProvider) => ConvertToEncoding(stringvalue) }, { typeof(CultureInfo), (string stringvalue, string? format, IFormatProvider? formatProvider) => ConvertToCultureInfo(stringvalue) }, { typeof(Type), (string stringvalue, string? format, IFormatProvider? formatProvider) => ConvertToType(stringvalue, throwOnError: true) }, { typeof(LineEndingMode), (string stringvalue, string? format, IFormatProvider? formatProvider) => LineEndingMode.FromString(stringvalue) }, { typeof(LogLevel), (string stringvalue, string? format, IFormatProvider? formatProvider) => LogLevel.FromString(stringvalue) }, { typeof(Uri), (string stringvalue, string? format, IFormatProvider? formatProvider) => new Uri(stringvalue) }, { typeof(DateTime), (string stringvalue, string? format, IFormatProvider? formatProvider) => ConvertToDateTime(format, formatProvider, stringvalue) }, { typeof(DateTimeOffset), (string stringvalue, string? format, IFormatProvider? formatProvider) => ConvertToDateTimeOffset(format, formatProvider, stringvalue) }, { typeof(TimeSpan), (string stringvalue, string? format, IFormatProvider? formatProvider) => ConvertToTimeSpan(format, formatProvider, stringvalue) }, { typeof(Guid), (string stringvalue, string? format, IFormatProvider? formatProvider) => ConvertGuid(format, stringvalue) } }; } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2057")] internal static Type ConvertToType(string stringvalue, bool throwOnError) { return Type.GetType(stringvalue, throwOnError); } internal static bool IsComplexType(Type type) { if (!type.IsValueType && !typeof(IConvertible).IsAssignableFrom(type) && !StringConverterLookup.ContainsKey(type)) { return type.GetFirstCustomAttribute() == null; } return false; } public object? Convert(object? propertyValue, Type propertyType, string? format, IFormatProvider? formatProvider) { if (propertyValue == null || (object)propertyType == null || propertyType.Equals(typeof(object))) { return propertyValue; } Type type = propertyValue.GetType(); if (propertyType.IsAssignableFrom(type)) { return propertyValue; } Type underlyingType = Nullable.GetUnderlyingType(propertyType); if (underlyingType != null) { if (underlyingType.IsAssignableFrom(type)) { return propertyValue; } if (propertyValue is string value && StringHelpers.IsNullOrWhiteSpace(value)) { return null; } propertyType = underlyingType; } return ChangeObjectType(propertyValue, propertyType, format, formatProvider); } private static bool TryConvertFromString(string propertyString, Type propertyType, string? format, IFormatProvider? formatProvider, out object? propertyValue) { propertyValue = (propertyString = propertyString.Trim()); if (StringConverterLookup.TryGetValue(propertyType, out Func value)) { propertyValue = value(propertyString, format, formatProvider); return true; } if (propertyType.IsEnum) { return ConversionHelpers.TryParseEnum(propertyString, propertyType, out propertyValue); } if (PropertyHelper.TryTypeConverterConversion(propertyType, propertyString, out object newValue)) { propertyValue = newValue; return true; } return false; } private static object? ChangeObjectType(object propertyValue, Type propertyType, string? format, IFormatProvider? formatProvider) { if (propertyValue is string propertyString && TryConvertFromString(propertyString, propertyType, format, formatProvider, out object propertyValue2)) { return propertyValue2; } object convertedValue; if (propertyValue is IConvertible convertible) { switch (convertible.GetTypeCode()) { case TypeCode.DBNull: return convertible; case TypeCode.Empty: return null; } } else if (TryConvertToType(propertyValue, propertyType, out convertedValue)) { return convertedValue; } if (!string.IsNullOrEmpty(format) && propertyValue is IFormattable formattable) { propertyValue = formattable.ToString(format, formatProvider); } return System.Convert.ChangeType(propertyValue, propertyType, formatProvider); } [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2026")] [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2067")] [UnconditionalSuppressMessage("Trimming - Allow converting option-values from config", "IL2072")] private static bool TryConvertToType(object propertyValue, Type propertyType, out object? convertedValue) { if (propertyValue == null || propertyType.IsAssignableFrom(propertyValue.GetType())) { convertedValue = null; return false; } TypeConverter converter = TypeDescriptor.GetConverter(propertyValue.GetType()); if (converter != null && converter.CanConvertTo(propertyType)) { convertedValue = converter.ConvertTo(propertyValue, propertyType); return true; } convertedValue = null; return false; } private static Guid ConvertGuid(string? format, string propertyString) { if (!string.IsNullOrEmpty(format)) { return Guid.ParseExact(propertyString, format); } return Guid.Parse(propertyString); } internal static CultureInfo? ConvertToCultureInfo(string? stringValue) { if (stringValue == null || StringHelpers.IsNullOrWhiteSpace(stringValue)) { return null; } if ("InvariantCulture".Equals(stringValue, StringComparison.OrdinalIgnoreCase)) { return CultureInfo.InvariantCulture; } if ("CurrentCulture".Equals(stringValue, StringComparison.OrdinalIgnoreCase)) { return CultureInfo.CurrentCulture; } return new CultureInfo(stringValue); } internal static Encoding ConvertToEncoding(string stringValue) { stringValue = stringValue.Trim(); if (string.Equals(stringValue, "UTF8", StringComparison.OrdinalIgnoreCase)) { stringValue = Encoding.UTF8.WebName; } return Encoding.GetEncoding(stringValue); } private static TimeSpan ConvertToTimeSpan(string? format, IFormatProvider? formatProvider, string propertyString) { if (!string.IsNullOrEmpty(format)) { return TimeSpan.ParseExact(propertyString, format, formatProvider); } return TimeSpan.Parse(propertyString, formatProvider); } private static DateTimeOffset ConvertToDateTimeOffset(string? format, IFormatProvider? formatProvider, string propertyString) { if (!string.IsNullOrEmpty(format)) { return DateTimeOffset.ParseExact(propertyString, format, formatProvider); } return DateTimeOffset.Parse(propertyString, formatProvider); } private static DateTime ConvertToDateTime(string? format, IFormatProvider? formatProvider, string propertyString) { if (!string.IsNullOrEmpty(format)) { return DateTime.ParseExact(propertyString, format, formatProvider); } return DateTime.Parse(propertyString, formatProvider); } } [AttributeUsage(AttributeTargets.Property)] [MeansImplicitUse] [Obsolete("Instead perform relevant config validation in InitializeTarget / InitializeLayout. Marked obsolete with NLog v6.0")] [EditorBrowsable(EditorBrowsableState.Never)] public sealed class RequiredParameterAttribute : Attribute { } public abstract class ServiceRepository : IServiceProvider { public abstract void RegisterService(Type type, object instance); public abstract object GetService(Type serviceType); internal abstract bool TryGetService(out T? serviceInstance) where T : class; internal ServiceRepository() { } } internal static class ServiceRepositoryExtensions { internal static ServiceRepository GetServiceProvider(this LoggingConfiguration? loggingConfiguration) { return loggingConfiguration?.LogFactory?.ServiceRepository ?? LogManager.LogFactory.ServiceRepository; } internal static T ResolveService(this ServiceRepository serviceProvider, bool ignoreExternalProvider = true) where T : class { if (ignoreExternalProvider) { return serviceProvider.GetService(); } IServiceProvider service; try { if (serviceProvider.TryGetService(out T serviceInstance) && serviceInstance != null) { return serviceInstance; } service = serviceProvider.GetService(); } catch (NLogDependencyResolveException) { service = serviceProvider.GetService(); if (service == serviceProvider) { throw; } } catch (Exception ex2) { if (ex2.MustBeRethrownImmediately()) { throw; } throw new NLogDependencyResolveException("Service Provider failed with exception - " + ex2.Message, ex2, typeof(T)); } if (service == serviceProvider) { throw new NLogDependencyResolveException("Type not registered in Service Provider", typeof(T)); } T service2 = service.GetService(); serviceProvider.RegisterService(typeof(T), service2); return service2; } internal static T GetService(this IServiceProvider serviceProvider) where T : class { try { return ((serviceProvider ?? LogManager.LogFactory.ServiceRepository).GetService(typeof(T)) as T) ?? throw new NLogDependencyResolveException("Type not registered in Service Provider", typeof(T)); } catch (NLogDependencyResolveException ex) { if (ex.ServiceType == typeof(T)) { throw; } throw new NLogDependencyResolveException(ex.Message, ex, typeof(T)); } catch (Exception ex2) { if (ex2.MustBeRethrownImmediately()) { throw; } throw new NLogDependencyResolveException("Service Provider failed with exception - " + ex2.Message, ex2, typeof(T)); } } internal static ServiceRepository RegisterSingleton(this ServiceRepository serviceRepository, T singleton) where T : class { serviceRepository.RegisterService(typeof(T), singleton); return serviceRepository; } internal static ServiceRepository RegisterValueFormatter(this ServiceRepository serviceRepository, IValueFormatter valueFormatter) { Guard.ThrowIfNull(valueFormatter, "valueFormatter"); serviceRepository.RegisterSingleton(valueFormatter); return serviceRepository; } internal static ServiceRepository RegisterJsonConverter(this ServiceRepository serviceRepository, IJsonConverter jsonConverter) { Guard.ThrowIfNull(jsonConverter, "jsonConverter"); serviceRepository.RegisterSingleton(jsonConverter); return serviceRepository; } internal static ServiceRepository RegisterPropertyTypeConverter(this ServiceRepository serviceRepository, IPropertyTypeConverter converter) { Guard.ThrowIfNull(converter, "converter"); serviceRepository.RegisterSingleton(converter); return serviceRepository; } internal static ServiceRepository RegisterObjectTypeTransformer(this ServiceRepository serviceRepository, IObjectTypeTransformer transformer) { Guard.ThrowIfNull(transformer, "transformer"); serviceRepository.RegisterSingleton(transformer); return serviceRepository; } internal static ServiceRepository ParseMessageTemplates(this ServiceRepository serviceRepository, LogFactory logFactory, bool? enable) { if (enable.GetValueOrDefault()) { InternalLogger.Debug("Message Template Format always enabled"); serviceRepository.RegisterSingleton((ILogMessageFormatter)new LogMessageTemplateFormatter(logFactory, forceMessageTemplateRenderer: true, singleTargetOnly: false)); } else if (enable == false) { InternalLogger.Debug("Message Template String Format always enabled"); serviceRepository.RegisterSingleton((ILogMessageFormatter)LogMessageStringFormatter.Default); } else { InternalLogger.Debug("Message Template Auto Format enabled"); serviceRepository.RegisterSingleton((ILogMessageFormatter)new LogMessageTemplateFormatter(logFactory, forceMessageTemplateRenderer: false, singleTargetOnly: false)); } return serviceRepository; } internal static bool? ResolveParseMessageTemplates(this ServiceRepository serviceRepository) { return serviceRepository.GetService()?.EnableMessageTemplateParser; } internal static ServiceRepository RegisterDefaults(this ServiceRepository serviceRepository, LogFactory logFactory) { serviceRepository.RegisterSingleton((IServiceProvider)serviceRepository); serviceRepository.RegisterSingleton((ILogMessageFormatter)new LogMessageTemplateFormatter(logFactory, forceMessageTemplateRenderer: false, singleTargetOnly: false)); serviceRepository.RegisterJsonConverter(new DefaultJsonSerializer(serviceRepository)); serviceRepository.RegisterValueFormatter(new ValueFormatter(serviceRepository, legacyStringQuotes: false)); serviceRepository.RegisterPropertyTypeConverter(PropertyTypeConverter.Instance); serviceRepository.RegisterObjectTypeTransformer(new ObjectReflectionCache(serviceRepository)); return serviceRepository; } } internal sealed class ServiceRepositoryInternal : ServiceRepository { private readonly Dictionary> _creatorMap = new Dictionary>(); private readonly object _lockObject = new object(); public event EventHandler? TypeRegistered; internal ServiceRepositoryInternal(LogFactory logFactory) { this.RegisterDefaults(logFactory); } public override void RegisterService(Type type, object instance) { object instance2 = instance; Guard.ThrowIfNull(type, "type"); Guard.ThrowIfNull(instance2, "instance"); lock (_lockObject) { _creatorMap[type] = () => instance2; } this.TypeRegistered?.Invoke(this, new ServiceRepositoryUpdateEventArgs(type)); } public override object GetService(Type serviceType) { return TryGetService(serviceType) ?? throw new NLogDependencyResolveException("Type not registered in Service Provider", serviceType); } private object? TryGetService(Type serviceType) { Guard.ThrowIfNull(serviceType, "serviceType"); Func value = null; lock (_lockObject) { _creatorMap.TryGetValue(serviceType, out value); } return value?.Invoke(); } internal override bool TryGetService(out T? serviceInstance) { if (TryGetService(typeof(T)) is T val) { serviceInstance = val; return true; } serviceInstance = null; return false; } } public class ServiceRepositoryUpdateEventArgs : EventArgs { public Type ServiceType { get; } public ServiceRepositoryUpdateEventArgs(Type serviceType) { ServiceType = Guard.ThrowIfNull(serviceType, "serviceType"); } } [Obsolete("Use LogManager.Setup().LoadConfiguration() instead. Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static class SimpleConfigurator { [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteToConsole()) instead. Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ConfigureForConsoleLogging() { ConfigureForConsoleLogging(LogLevel.Info); } [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger(minLevel).WriteToConsole()) instead. Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ConfigureForConsoleLogging(LogLevel minLevel) { ConsoleTarget target = new ConsoleTarget(); LoggingConfiguration loggingConfiguration = new LoggingConfiguration(); loggingConfiguration.AddRule(minLevel, LogLevel.MaxLevel, target); LogManager.Configuration = loggingConfiguration; } [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteTo(target)) instead. Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ConfigureForTargetLogging(Target target) { Guard.ThrowIfNull(target, "target"); ConfigureForTargetLogging(target, LogLevel.Info); } [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger(minLevel).WriteTo(target)) instead. Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ConfigureForTargetLogging(Target target, LogLevel minLevel) { Guard.ThrowIfNull(target, "target"); LoggingConfiguration loggingConfiguration = new LoggingConfiguration(); loggingConfiguration.AddRule(minLevel, LogLevel.MaxLevel, target); LogManager.Configuration = loggingConfiguration; } [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger().WriteToFile(fileName)) instead. Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ConfigureForFileLogging(string fileName) { ConfigureForFileLogging(fileName, LogLevel.Info); } [Obsolete("Use LogManager.Setup().LoadConfiguration(c => c.ForLogger(minLevel).WriteToFile(fileName)) instead. Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ConfigureForFileLogging(string fileName, LogLevel minLevel) { ConfigureForTargetLogging(new FileTarget { FileName = fileName }, minLevel); } } [Flags] public enum StackTraceUsage { None = 0, WithStackTrace = 1, WithFileNameAndLineNumber = 2, WithCallSite = 4, WithCallSiteClassName = 8, [Obsolete("Replace with `WithStackTrace`. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] WithoutSource = 1, WithSource = 3, Max = 3 } [AttributeUsage(AttributeTargets.Class)] public sealed class ThreadAgnosticAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class)] public sealed class ThreadAgnosticImmutableAttribute : Attribute { } [Obsolete("All LayoutRenderer's and Layout's should be ThreadSafe by default. Marked obsolete with NLog 5.0")] [AttributeUsage(AttributeTargets.Class)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed class ThreadSafeAttribute : Attribute { } public class XmlLoggingConfiguration : LoggingConfigurationParser { private sealed class AutoReloadConfigFileWatcher : IDisposable { private readonly LogFactory _logFactory; private readonly MultiFileWatcher _fileWatcher = new MultiFileWatcher(); private readonly object _lockObject = new object(); private Timer? _reloadTimer; private bool _isDisposing; internal bool IsDisposed => _isDisposing; public AutoReloadConfigFileWatcher(LogFactory logFactory) { _logFactory = logFactory; _fileWatcher.FileChanged += FileWatcher_FileChanged; } private void FileWatcher_FileChanged(object sender, FileSystemEventArgs e) { lock (_lockObject) { if (_isDisposing) { return; } Timer reloadTimer = _reloadTimer; if (reloadTimer == null) { LoggingConfiguration configuration = _logFactory.Configuration; if (configuration != null) { _reloadTimer = new Timer(delegate(object s) { ReloadTimer(s); }, configuration, 1000, -1); } } else { reloadTimer.Change(1000, -1); } } } private void ReloadTimer(object state) { if (_isDisposing) { return; } LoggingConfiguration loggingConfiguration = (LoggingConfiguration)state; InternalLogger.Info("AutoReload Config File Monitor reloading configuration..."); lock (_lockObject) { if (_isDisposing) { return; } Timer? reloadTimer = _reloadTimer; _reloadTimer = null; reloadTimer?.Dispose(); } LoggingConfiguration loggingConfiguration2 = null; try { if (_logFactory.Configuration != loggingConfiguration) { InternalLogger.Debug("AutoReload Config File Monitor skipping reload, since existing NLog config has changed."); return; } loggingConfiguration2 = loggingConfiguration.Reload(); if (loggingConfiguration2 == null || loggingConfiguration2 == loggingConfiguration) { InternalLogger.Debug("AutoReload Config File Monitor skipping reload, since new configuration has not changed."); return; } if (_logFactory.Configuration != loggingConfiguration) { InternalLogger.Debug("AutoReload Config File Monitor skipping reload, since existing NLog config has changed."); return; } } catch (Exception ex) { InternalLogger.Warn(ex, "AutoReload Config File Monitor failed to reload NLog LoggingConfiguration."); return; } try { TryUnwatchConfigFile(); _logFactory.Configuration = loggingConfiguration2; } catch (Exception ex2) { InternalLogger.Warn(ex2, "AutoReload Config File Monitor failed to activate new NLog LoggingConfiguration."); _fileWatcher.Watch((loggingConfiguration as XmlLoggingConfiguration)?.AutoReloadFileNames ?? ArrayHelper.Empty()); } } public void RefreshFileWatcher(IEnumerable fileNamesToWatch) { _fileWatcher.Watch(fileNamesToWatch); } public void Dispose() { Timer reloadTimer = _reloadTimer; lock (_lockObject) { if (_isDisposing) { return; } reloadTimer = _reloadTimer; _isDisposing = true; _reloadTimer = null; } _fileWatcher.FileChanged -= FileWatcher_FileChanged; reloadTimer?.Dispose(); _fileWatcher.Dispose(); } private void TryUnwatchConfigFile() { try { _fileWatcher?.StopWatching(); } catch (Exception ex) { InternalLogger.Warn(ex, "AutoReload Config File Monitor failed to stop file watcher."); if (LogManager.ThrowExceptions || _logFactory.ThrowExceptions) { throw; } } } } private static readonly Dictionary _watchers = new Dictionary(); private readonly Dictionary _fileMustAutoReloadLookup = new Dictionary(StringComparer.OrdinalIgnoreCase); private string? _originalFileName; private readonly Stack _currentFilePath = new Stack(); public bool AutoReload { get { return AutoReloadFileNames.Any(); } set { foreach (string item in _fileMustAutoReloadLookup.Keys.ToList()) { _fileMustAutoReloadLookup[item] = value; } } } public IEnumerable AutoReloadFileNames { get { if (_fileMustAutoReloadLookup.Count == 0) { return ArrayHelper.Empty(); } return from entry in _fileMustAutoReloadLookup where entry.Value select entry.Key; } } [Obsolete("Replaced by AutoReloadFileNames. Marked obsolete with NLog v6")] [EditorBrowsable(EditorBrowsableState.Never)] public override IEnumerable FileNamesToWatch => AutoReloadFileNames; internal XmlLoggingConfiguration(LogFactory logFactory) : base(logFactory) { } public XmlLoggingConfiguration(string fileName) : this(fileName, LogManager.LogFactory) { } public XmlLoggingConfiguration(string fileName, LogFactory logFactory) : base(logFactory) { Guard.ThrowIfNullOrEmpty(fileName, "fileName"); LoadFromXmlFile(fileName); } public XmlLoggingConfiguration(TextReader xmlSource) : this(xmlSource, null) { } public XmlLoggingConfiguration(TextReader xmlSource, string? filePath) : this(xmlSource, filePath, LogManager.LogFactory) { } public XmlLoggingConfiguration(TextReader xmlSource, string? filePath, LogFactory logFactory) : base(logFactory) { Guard.ThrowIfNull(xmlSource, "xmlSource"); ParseFromTextReader(xmlSource, filePath); } internal XmlLoggingConfiguration(string xmlContents, string filePath, LogFactory logFactory) : base(logFactory) { Guard.ThrowIfNullOrEmpty(xmlContents, "xmlContents"); LoadFromXmlContent(xmlContents, filePath); } public static XmlLoggingConfiguration CreateFromXmlString(string xml) { return CreateFromXmlString(xml, LogManager.LogFactory); } public static XmlLoggingConfiguration CreateFromXmlString(string xml, LogFactory logFactory) { return new XmlLoggingConfiguration(xml, string.Empty, logFactory); } public override LoggingConfiguration Reload() { string text = _originalFileName ?? string.Empty; if (!string.IsNullOrEmpty(text)) { XmlLoggingConfiguration xmlLoggingConfiguration = new XmlLoggingConfiguration(base.LogFactory); xmlLoggingConfiguration.PrepareForReload(this); xmlLoggingConfiguration.LoadFromXmlFile(text); return xmlLoggingConfiguration; } return base.Reload(); } protected internal override void OnConfigurationAssigned(LogFactory? logFactory) { base.OnConfigurationAssigned(logFactory); try { LogFactory logFactory2 = logFactory ?? base.LogFactory ?? LogManager.LogFactory; AutoReloadConfigFileWatcher value = null; lock (_watchers) { _watchers.TryGetValue(logFactory2, out value); } if (logFactory == null || !AutoReload) { if (value != null && !value.IsDisposed) { InternalLogger.Debug("AutoReload Config File Monitor stopping, since no active configuration"); value.Dispose(); } return; } InternalLogger.Debug("AutoReload Config File Monitor refreshing after configuration changed"); if (value == null || value.IsDisposed) { InternalLogger.Debug("AutoReload Config File Monitor starting"); value = new AutoReloadConfigFileWatcher(logFactory2); lock (_watchers) { _watchers[logFactory2] = value; } } value.RefreshFileWatcher(AutoReloadFileNames); } catch (Exception ex) { InternalLogger.Error(ex, "AutoReload Config File Monitor failed to refresh after configuration changed."); } } [Obsolete("Replaced by chaining LogManager.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static IEnumerable GetCandidateConfigFilePaths() { return LogManager.LogFactory.GetCandidateConfigFilePaths(); } [Obsolete("Replaced by chaining LogManager.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void SetCandidateConfigFilePaths(IEnumerable filePaths) { LogManager.LogFactory.SetCandidateConfigFilePaths(filePaths); } [Obsolete("Replaced by chaining LogManager.Setup().LoadConfigurationFromFile(). Marked obsolete on NLog 5.2")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ResetCandidateConfigFilePath() { LogManager.LogFactory.ResetCandidateConfigFilePath(); } private void LoadFromXmlFile(string filePath) { using TextReader textReader = base.LogFactory.CurrentAppEnvironment.LoadTextFile(filePath); ParseFromTextReader(textReader, filePath); } internal void LoadFromXmlContent(string xmlContents, string filePath) { using StringReader textReader = new StringReader(xmlContents); ParseFromTextReader(textReader, filePath); } private void ParseFromTextReader(TextReader textReader, string? filePath) { try { _originalFileName = ((filePath == null || StringHelpers.IsNullOrWhiteSpace(filePath)) ? null : GetFileLookupKey(filePath)); IList processingInstructions; XmlParserConfigurationElement content = new XmlParserConfigurationElement(new XmlParser(textReader).LoadDocument(out processingInstructions)); if (!string.IsNullOrEmpty(_originalFileName)) { InternalLogger.Info("Loading NLog config from XML file: {0}", _originalFileName); ParseTopLevel(content, filePath, autoReloadDefault: false); } else { ParseTopLevel(content, null, autoReloadDefault: false); } } catch (Exception ex) { string text = (string.IsNullOrEmpty(filePath) ? "" : (" FilePath: " + filePath)); NLogConfigurationException ex2 = new NLogConfigurationException("Failed loading NLog configuration. " + ex.Message + " " + text, ex); InternalLogger.Error(ex2, ex2.Message); throw ex2; } } private void IncludeNewConfigFile(string filePath, bool autoReloadDefault) { if (!_fileMustAutoReloadLookup.ContainsKey(GetFileLookupKey(filePath))) { using (TextReader xmlSource = base.LogFactory.CurrentAppEnvironment.LoadTextFile(filePath)) { IList processingInstructions; XmlParserConfigurationElement content = new XmlParserConfigurationElement(new XmlParser(xmlSource).LoadDocument(out processingInstructions), nestedElement: false); ParseTopLevel(content, filePath, autoReloadDefault); } } } private void ParseTopLevel(ILoggingConfigurationElement content, string? filePath, bool autoReloadDefault) { content.AssertName("nlog", "configuration"); string text = content.Name.ToUpperInvariant(); if (!(text == "CONFIGURATION")) { if (text == "NLOG") { ParseNLogElement(content, filePath, autoReloadDefault); } } else { ParseConfigurationElement(content, filePath, autoReloadDefault); } } private void ParseConfigurationElement(ILoggingConfigurationElement configurationElement, string? filePath, bool autoReloadDefault) { InternalLogger.Trace("ParseConfigurationElement"); configurationElement.AssertName("configuration"); foreach (ILoggingConfigurationElement item in configurationElement.FilterChildren("nlog")) { ParseNLogElement(item, filePath, autoReloadDefault); } } private void ParseNLogElement(ILoggingConfigurationElement nlogElement, string? filePath, bool autoReloadDefault) { InternalLogger.Trace("ParseNLogElement"); nlogElement.AssertName("nlog"); bool optionalBooleanValue = nlogElement.GetOptionalBooleanValue("autoReload", autoReloadDefault); try { string basePath = null; if (filePath != null && !StringHelpers.IsNullOrWhiteSpace(filePath)) { _fileMustAutoReloadLookup[GetFileLookupKey(filePath)] = optionalBooleanValue; _currentFilePath.Push(filePath); basePath = Path.GetDirectoryName(filePath); } LoadConfig(nlogElement, basePath); } finally { if (!string.IsNullOrEmpty(filePath)) { _currentFilePath.Pop(); } } } protected override bool ParseNLogSection(ILoggingConfigurationElement configSection) { if (configSection.MatchesName("include")) { string text = _currentFilePath.Peek(); bool autoReloadDefault = !string.IsNullOrEmpty(text) && _fileMustAutoReloadLookup[GetFileLookupKey(text)]; ParseIncludeElement(configSection, (!string.IsNullOrEmpty(text)) ? Path.GetDirectoryName(text) : null, autoReloadDefault); return true; } return base.ParseNLogSection(configSection); } private void ParseIncludeElement(ILoggingConfigurationElement includeElement, string? baseDirectory, bool autoReloadDefault) { includeElement.AssertName("include"); string text = includeElement.GetRequiredValue("file", "nlog"); bool optionalBooleanValue = includeElement.GetOptionalBooleanValue("ignoreErrors", defaultValue: false); try { text = ExpandSimpleVariables(text); text = SimpleLayout.Evaluate(text, this); string text2 = text; if (baseDirectory != null) { text2 = Path.Combine(baseDirectory, text); } if (File.Exists(text2)) { InternalLogger.Debug("Including file '{0}'", text2); IncludeNewConfigFile(text2, autoReloadDefault); return; } if (text.IndexOf('*') >= 0) { IncludeConfigFilesByMask(baseDirectory ?? ".", text, autoReloadDefault); return; } if (optionalBooleanValue) { InternalLogger.Debug("Skipping included file '{0}' as it can't be found", text2); return; } throw new FileNotFoundException("Included file not found: " + text2); } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) { throw; } NLogConfigurationException ex2 = new NLogConfigurationException("Error when including '" + text + "'.", ex); InternalLogger.Error(ex, ex2.Message); if (!optionalBooleanValue) { throw ex2; } } } private void IncludeConfigFilesByMask(string baseDirectory, string fileMask, bool autoReloadDefault) { string text = baseDirectory; if (Path.IsPathRooted(fileMask)) { text = Path.GetDirectoryName(fileMask); if (text == null) { InternalLogger.Warn("directory is empty for include of '{0}'", fileMask); return; } string fileName = Path.GetFileName(fileMask); if (fileName == null) { InternalLogger.Warn("filename is empty for include of '{0}'", fileMask); return; } fileMask = fileName; } string[] files = Directory.GetFiles(text, fileMask); foreach (string filePath in files) { IncludeNewConfigFile(filePath, autoReloadDefault); } } private static string GetFileLookupKey(string fileName) { return Path.GetFullPath(fileName); } public override string ToString() { if (AutoReload) { return base.ToString() + ", AutoReload=true, FilePath=" + _originalFileName; } return base.ToString() + ", FilePath=" + _originalFileName; } } internal sealed class XmlParserConfigurationElement : ILoggingConfigurationElement { public string Name { get; private set; } public string? Value { get; private set; } public IList> AttributeValues { get; } public IList Children { get; } public IEnumerable> Values { get { for (int i = 0; i < Children.Count; i++) { if (SingleValueElement(Children[i])) { return AttributeValues.Concat>(from item in Children where SingleValueElement(item) select new KeyValuePair(item.Name, item.Value ?? string.Empty)); } } return AttributeValues; } } IEnumerable ILoggingConfigurationElement.Children { get { for (int i = 0; i < Children.Count; i++) { if (!SingleValueElement(Children[i])) { return Children.Where((XmlParserConfigurationElement item) => !SingleValueElement(item)).Cast(); } } return ArrayHelper.Empty(); } } public XmlParserConfigurationElement(XmlParser.XmlParserElement xmlElement) : this(xmlElement, nestedElement: false) { } public XmlParserConfigurationElement(XmlParser.XmlParserElement xmlElement, bool nestedElement) { int num = xmlElement.Name.IndexOf(':'); Name = ((num >= 0) ? xmlElement.Name.Substring(num + 1) : xmlElement.Name); Value = xmlElement.InnerText; AttributeValues = ParseAttributes(xmlElement, nestedElement); Children = ParseChildren(xmlElement, nestedElement); } private static bool SingleValueElement(XmlParserConfigurationElement child) { if (child.Children.Count == 0 && child.AttributeValues.Count == 0) { return child.Value != null; } return false; } private static IList> ParseAttributes(XmlParser.XmlParserElement xmlElement, bool nestedElement) { IList> attributes = xmlElement.Attributes; if (attributes != null && attributes.Count > 0) { if (!nestedElement) { for (int num = attributes.Count - 1; num >= 0; num--) { if (IsSpecialXmlRootAttribute(attributes[num].Key)) { attributes.RemoveAt(num); } } } for (int i = 0; i < attributes.Count; i++) { int num2 = attributes[i].Key.IndexOf(':'); if (num2 >= 0) { attributes[i] = new KeyValuePair(attributes[i].Key.Substring(num2 + 1), attributes[i].Value); } } } return attributes ?? ArrayHelper.Empty>(); } private static IList ParseChildren(XmlParser.XmlParserElement xmlElement, bool nestedElement) { IList children = xmlElement.Children; if (children == null || children.Count == 0) { return ArrayHelper.Empty(); } List list = new List(); for (int i = 0; i < children.Count; i++) { XmlParser.XmlParserElement xmlParserElement = children[i]; bool nestedElement2 = nestedElement || !string.Equals(xmlParserElement.Name, "nlog", StringComparison.OrdinalIgnoreCase); list.Add(new XmlParserConfigurationElement(xmlParserElement, nestedElement2)); } return list; } private static bool IsSpecialXmlRootAttribute(string attributeName) { if (attributeName != null && attributeName.StartsWith("xmlns", StringComparison.OrdinalIgnoreCase)) { return true; } if (attributeName != null && attributeName.IndexOf(":xmlns", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } if (attributeName != null && attributeName.StartsWith("schemaLocation", StringComparison.OrdinalIgnoreCase)) { return true; } if (attributeName != null && attributeName.IndexOf(":schemaLocation", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } if (attributeName != null && attributeName.StartsWith("xsi:", StringComparison.OrdinalIgnoreCase)) { return true; } return false; } } public sealed class XmlParserException : NLogConfigurationException { public XmlParserException() { } public XmlParserException(string message) : base(message) { } public XmlParserException(string message, Exception? innerException) : base(message, innerException) { } } } namespace NLog.Conditions { internal sealed class ConditionAndExpression : ConditionExpression { public ConditionExpression Left { get; } public ConditionExpression Right { get; } public ConditionAndExpression(ConditionExpression left, ConditionExpression right) { Left = left; Right = right; } public override string ToString() { return $"({Left} and {Right})"; } protected override object EvaluateNode(LogEventInfo context) { if (!(bool)(Left.Evaluate(context) ?? ConditionExpression.BoxedFalse)) { return ConditionExpression.BoxedFalse; } if (!(bool)(Right.Evaluate(context) ?? ConditionExpression.BoxedFalse)) { return ConditionExpression.BoxedFalse; } return ConditionExpression.BoxedTrue; } } public class ConditionEvaluationException : Exception { public ConditionEvaluationException() { } public ConditionEvaluationException(string message) : base(message) { } public ConditionEvaluationException(string message, Exception? innerException) : base(message, innerException) { } } internal sealed class ConditionExceptionExpression : ConditionExpression { public override string ToString() { return "exception"; } protected override object? EvaluateNode(LogEventInfo context) { return context.Exception; } } [NLogConfigurationItem] public abstract class ConditionExpression { internal static readonly object BoxedTrue = true; internal static readonly object BoxedFalse = false; [return: NotNullIfNotNull("conditionExpressionText")] public static implicit operator ConditionExpression?(string? conditionExpressionText) { if (conditionExpressionText == null) { return null; } return ConditionParser.ParseExpression(conditionExpressionText); } public object? Evaluate(LogEventInfo context) { try { return EvaluateNode(context); } catch (Exception ex) { InternalLogger.Warn(ex, "Exception occurred when evaluating condition"); if (ex.MustBeRethrownImmediately()) { throw; } throw new ConditionEvaluationException("Exception occurred when evaluating condition", ex); } } public abstract override string ToString(); protected abstract object? EvaluateNode(LogEventInfo context); } internal sealed class ConditionLayoutExpression : ConditionExpression { private readonly SimpleLayout _simpleLayout; private StringBuilder? _fastObjectPool; public Layout Layout => _simpleLayout; public ConditionLayoutExpression(SimpleLayout layout) { _simpleLayout = layout; } public override string ToString() { return "'" + _simpleLayout.ToString() + "'"; } protected override object EvaluateNode(LogEventInfo context) { if (_simpleLayout.IsSimpleStringText || !_simpleLayout.ThreadAgnostic) { return _simpleLayout.Render(context); } StringBuilder stringBuilder = Interlocked.Exchange(ref _fastObjectPool, null) ?? new StringBuilder(); try { _simpleLayout.Render(context, stringBuilder); return stringBuilder.ToString(); } finally { stringBuilder.ClearBuilder(); Interlocked.Exchange(ref _fastObjectPool, stringBuilder); } } } internal sealed class ConditionLevelExpression : ConditionExpression { public override string ToString() { return "level"; } protected override object EvaluateNode(LogEventInfo context) { return context.Level; } } internal sealed class ConditionLiteralExpression : ConditionExpression { public static readonly ConditionLiteralExpression Null = new ConditionLiteralExpression(null); public static readonly ConditionLiteralExpression True = new ConditionLiteralExpression(ConditionExpression.BoxedTrue); public static readonly ConditionLiteralExpression False = new ConditionLiteralExpression(ConditionExpression.BoxedFalse); public object? LiteralValue { get; } public ConditionLiteralExpression(object? literalValue) { LiteralValue = literalValue; } public override string ToString() { if (LiteralValue == null) { return "null"; } if (LiteralValue is string text) { return "'" + text + "'"; } if (LiteralValue is char c) { return $"'{c}'"; } return Convert.ToString(LiteralValue, CultureInfo.InvariantCulture) ?? string.Empty; } protected override object? EvaluateNode(LogEventInfo context) { return LiteralValue; } } internal sealed class ConditionLoggerNameExpression : ConditionExpression { public override string ToString() { return "logger"; } protected override object EvaluateNode(LogEventInfo context) { return context.LoggerName; } } internal sealed class ConditionMessageExpression : ConditionExpression { public override string ToString() { return "message"; } protected override object EvaluateNode(LogEventInfo context) { return context.FormattedMessage; } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class ConditionMethodAttribute : NameBaseAttribute { public ConditionMethodAttribute(string name) : base(name) { } } internal sealed class ConditionMethodExpression : ConditionExpression { private interface IEvaluateMethod { object? EvaluateNode(LogEventInfo logEvent); } private sealed class EvaluateMethodNoParameters : IEvaluateMethod { private readonly Func _method; public EvaluateMethodNoParameters(Func method) { _method = Guard.ThrowIfNull(method, "method"); } public object? EvaluateNode(LogEventInfo logEvent) { return _method(logEvent); } } private sealed class EvaluateMethodOneParameter : IEvaluateMethod { private readonly Func _method; private readonly Func _methodParameter; public EvaluateMethodOneParameter(Func method, Func methodParameter) { _method = Guard.ThrowIfNull(method, "method"); _methodParameter = Guard.ThrowIfNull(methodParameter, "methodParameter"); } public object? EvaluateNode(LogEventInfo logEvent) { object arg = _methodParameter(logEvent); return _method(logEvent, arg); } } private sealed class EvaluateMethodTwoParameters : IEvaluateMethod { private readonly Func _method; private readonly Func _methodParameterArg1; private readonly Func _methodParameterArg2; public EvaluateMethodTwoParameters(Func method, Func methodParameterArg1, Func methodParameterArg2) { _method = Guard.ThrowIfNull(method, "method"); _methodParameterArg1 = Guard.ThrowIfNull(methodParameterArg1, "methodParameterArg1"); _methodParameterArg2 = Guard.ThrowIfNull(methodParameterArg2, "methodParameterArg2"); } public object? EvaluateNode(LogEventInfo logEvent) { object arg = _methodParameterArg1(logEvent); object arg2 = _methodParameterArg2(logEvent); return _method(logEvent, arg, arg2); } } private sealed class EvaluateMethodThreeParameters : IEvaluateMethod { private readonly Func _method; private readonly Func _methodParameterArg1; private readonly Func _methodParameterArg2; private readonly Func _methodParameterArg3; public EvaluateMethodThreeParameters(Func method, Func methodParameterArg1, Func methodParameterArg2, Func methodParameterArg3) { _method = Guard.ThrowIfNull(method, "method"); _methodParameterArg1 = Guard.ThrowIfNull(methodParameterArg1, "methodParameterArg1"); _methodParameterArg2 = Guard.ThrowIfNull(methodParameterArg2, "methodParameterArg2"); _methodParameterArg3 = Guard.ThrowIfNull(methodParameterArg3, "methodParameterArg3"); } public object? EvaluateNode(LogEventInfo logEvent) { object arg = _methodParameterArg1(logEvent); object arg2 = _methodParameterArg2(logEvent); object arg3 = _methodParameterArg3(logEvent); return _method(logEvent, arg, arg2, arg3); } } private sealed class EvaluateMethodManyParameters : IEvaluateMethod { private readonly Func _method; private readonly IList _methodParameters; private readonly bool _includeLogEvent; public EvaluateMethodManyParameters(Func method, IList inputParameters, bool includeLogEvent) { _method = Guard.ThrowIfNull(method, "method"); _methodParameters = Guard.ThrowIfNull(inputParameters, "inputParameters"); _includeLogEvent = includeLogEvent; } public object? EvaluateNode(LogEventInfo logEvent) { int num = (_includeLogEvent ? 1 : 0); object[] array = new object[_methodParameters.Count + num]; if (_includeLogEvent) { array[0] = logEvent; } for (int i = 0; i < _methodParameters.Count; i++) { object obj = _methodParameters[i].Evaluate(logEvent); array[num++] = obj; } return _method(array); } } private readonly IEvaluateMethod _method; public string MethodName { get; } public IList MethodParameters { get; } private ConditionMethodExpression(string methodName, IList methodParameters, IEvaluateMethod method) { MethodName = Guard.ThrowIfNull(methodName, "methodName"); _method = Guard.ThrowIfNull(method, "method"); MethodParameters = Guard.ThrowIfNull(methodParameters, "methodParameters"); } protected override object? EvaluateNode(LogEventInfo context) { return _method.EvaluateNode(context); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(MethodName); stringBuilder.Append('('); string value = string.Empty; foreach (ConditionExpression methodParameter in MethodParameters) { stringBuilder.Append(value); stringBuilder.Append(methodParameter); value = ", "; } stringBuilder.Append(')'); return stringBuilder.ToString(); } public static ConditionMethodExpression CreateMethodNoParameters(string conditionMethodName, Func method) { return new ConditionMethodExpression(conditionMethodName, ArrayHelper.Empty(), new EvaluateMethodNoParameters(method)); } public static ConditionMethodExpression CreateMethodNoParameters(string conditionMethodName, Func method) { Func method2 = method; return CreateMethodNoParameters(conditionMethodName, (LogEventInfo evt) => (!method2(evt)) ? ConditionExpression.BoxedFalse : ConditionExpression.BoxedTrue); } public static ConditionMethodExpression CreateMethodOneParameter(string conditionMethodName, Func method, IList methodParameters) { ConditionExpression methodParameter = methodParameters[0]; return new ConditionMethodExpression(conditionMethodName, methodParameters, new EvaluateMethodOneParameter(method, (LogEventInfo logEvent) => methodParameter.Evaluate(logEvent))); } public static ConditionMethodExpression CreateMethodTwoParameters(string conditionMethodName, Func method, IList methodParameters) { ConditionExpression methodParameterArg1 = methodParameters[0]; ConditionExpression methodParameterArg2 = methodParameters[1]; return new ConditionMethodExpression(conditionMethodName, methodParameters, new EvaluateMethodTwoParameters(method, (LogEventInfo logEvent) => methodParameterArg1.Evaluate(logEvent), (LogEventInfo logEvent) => methodParameterArg2.Evaluate(logEvent))); } public static ConditionMethodExpression CreateMethodThreeParameters(string conditionMethodName, Func method, IList methodParameters) { ConditionExpression methodParameterArg1 = methodParameters[0]; ConditionExpression methodParameterArg2 = methodParameters[1]; ConditionExpression methodParameterArg3 = methodParameters[2]; return new ConditionMethodExpression(conditionMethodName, methodParameters, new EvaluateMethodThreeParameters(method, (LogEventInfo logEvent) => methodParameterArg1.Evaluate(logEvent), (LogEventInfo logEvent) => methodParameterArg2.Evaluate(logEvent), (LogEventInfo logEvent) => methodParameterArg3.Evaluate(logEvent))); } public static ConditionMethodExpression CreateMethodManyParameters(string conditionMethodName, Func method, IList methodParameters, bool includeLogEvent) { return new ConditionMethodExpression(conditionMethodName, methodParameters, new EvaluateMethodManyParameters(method, methodParameters, includeLogEvent)); } } [ConditionMethods] public static class ConditionMethods { [ConditionMethod("equals")] public static bool Equals2(object? firstValue, object? secondValue) { if (firstValue != secondValue) { return firstValue?.Equals(secondValue) ?? false; } return true; } [ConditionMethod("strequals")] public static bool Equals2(string? firstValue, string? secondValue, bool ignoreCase = false) { return string.Equals(firstValue, secondValue, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } [ConditionMethod("contains")] public static bool Contains(string? haystack, string? needle, bool ignoreCase = true) { if (haystack == null || needle == null) { return false; } return haystack.IndexOf(needle, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) >= 0; } [ConditionMethod("starts-with")] public static bool StartsWith(string? haystack, string? needle, bool ignoreCase = true) { if (haystack == null || needle == null) { return false; } return haystack.StartsWith(needle, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } [ConditionMethod("ends-with")] public static bool EndsWith(string? haystack, string? needle, bool ignoreCase = true) { if (haystack == null || needle == null) { return false; } return haystack.EndsWith(needle, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } [ConditionMethod("length")] public static int Length(string? text) { return text?.Length ?? 0; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class ConditionMethodsAttribute : Attribute { } internal sealed class ConditionNotExpression : ConditionExpression { public ConditionExpression Expression { get; } public ConditionNotExpression(ConditionExpression expression) { Expression = expression; } public override string ToString() { return $"(not {Expression})"; } protected override object EvaluateNode(LogEventInfo context) { if (!(bool)(Expression.Evaluate(context) ?? ConditionExpression.BoxedFalse)) { return ConditionExpression.BoxedTrue; } return ConditionExpression.BoxedFalse; } } internal sealed class ConditionOrExpression : ConditionExpression { public ConditionExpression LeftExpression { get; } public ConditionExpression RightExpression { get; } public ConditionOrExpression(ConditionExpression left, ConditionExpression right) { LeftExpression = left; RightExpression = right; } public override string ToString() { return $"({LeftExpression} or {RightExpression})"; } protected override object EvaluateNode(LogEventInfo context) { if ((bool)(LeftExpression.Evaluate(context) ?? ConditionExpression.BoxedFalse)) { return ConditionExpression.BoxedTrue; } if ((bool)(RightExpression.Evaluate(context) ?? ConditionExpression.BoxedFalse)) { return ConditionExpression.BoxedTrue; } return ConditionExpression.BoxedFalse; } } public class ConditionParseException : Exception { public ConditionParseException() { } public ConditionParseException(string message) : base(message) { } public ConditionParseException(string message, Exception innerException) : base(message, innerException) { } } public class ConditionParser { private readonly ConditionTokenizer _tokenizer; private readonly ConfigurationItemFactory _configurationItemFactory; private ConditionParser(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactory) { _configurationItemFactory = configurationItemFactory; _tokenizer = new ConditionTokenizer(stringReader); } public static ConditionExpression ParseExpression(string expressionText) { Guard.ThrowIfNull(expressionText, "expressionText"); return ParseExpression(expressionText, ConfigurationItemFactory.Default); } public static ConditionExpression ParseExpression(string expressionText, ConfigurationItemFactory configurationItemFactories) { Guard.ThrowIfNull(expressionText, "expressionText"); ConditionParser conditionParser = new ConditionParser(new SimpleStringReader(expressionText), configurationItemFactories); ConditionExpression result = conditionParser.ParseExpression(); if (!conditionParser._tokenizer.IsEOF()) { throw new ConditionParseException("Unexpected token: " + conditionParser._tokenizer.TokenValue); } return result; } internal static ConditionExpression ParseExpression(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactories) { return new ConditionParser(stringReader, configurationItemFactories).ParseExpression(); } private ConditionMethodExpression ParseMethodPredicate(string functionName) { List list = new List(); while (!_tokenizer.IsEOF() && _tokenizer.TokenType != ConditionTokenType.RightParen) { list.Add(ParseExpression()); if (_tokenizer.TokenType != ConditionTokenType.Comma) { break; } _tokenizer.GetNextToken(); } _tokenizer.Expect(ConditionTokenType.RightParen); try { return CreateMethodExpression(functionName, list); } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to resolve condition method: '{0}'", new ReadOnlySpan(new object[1] { functionName })); if (ex.MustBeRethrownImmediately()) { throw; } throw new ConditionParseException("Cannot resolve function '" + functionName + "'", ex); } } private ConditionMethodExpression CreateMethodExpression(string functionName, List inputParameters) { if (inputParameters.Count == 0) { Func func = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithNoParameters(functionName); if (func != null) { return ConditionMethodExpression.CreateMethodNoParameters(functionName, func); } } else if (inputParameters.Count == 1) { Func func2 = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithOneParameter(functionName); if (func2 != null) { return ConditionMethodExpression.CreateMethodOneParameter(functionName, func2, inputParameters); } } else if (inputParameters.Count == 2) { Func func3 = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithTwoParameters(functionName); if (func3 != null) { return ConditionMethodExpression.CreateMethodTwoParameters(functionName, func3, inputParameters); } } else if (inputParameters.Count == 3) { Func func4 = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithThreeParameters(functionName); if (func4 != null) { return ConditionMethodExpression.CreateMethodThreeParameters(functionName, func4, inputParameters); } } int manyParameterMinCount; int manyParameterMaxCount; bool manyParameterWithLogEvent; Func func5 = _configurationItemFactory.ConditionMethodFactory.TryCreateInstanceWithManyParameters(functionName, out manyParameterMinCount, out manyParameterMaxCount, out manyParameterWithLogEvent); if (func5 == null) { throw new ConditionParseException("Unknown condition method '" + functionName + "'"); } if (manyParameterMinCount > inputParameters.Count) { throw new ConditionParseException($"Condition method '{functionName}' requires minimum {manyParameterMinCount} parameters, but passed {inputParameters.Count}."); } if (manyParameterMaxCount < inputParameters.Count) { throw new ConditionParseException($"Condition method '{functionName}' requires maximum {manyParameterMaxCount} parameters, but passed {inputParameters.Count}."); } return ConditionMethodExpression.CreateMethodManyParameters(functionName, func5, inputParameters, manyParameterWithLogEvent); } private ConditionExpression ParseLiteralExpression() { if (_tokenizer.IsToken(ConditionTokenType.LeftParen)) { _tokenizer.GetNextToken(); ConditionExpression result = ParseExpression(); _tokenizer.Expect(ConditionTokenType.RightParen); return result; } if (_tokenizer.IsToken(ConditionTokenType.Minus)) { _tokenizer.GetNextToken(); if (!_tokenizer.IsNumber()) { throw new ConditionParseException($"Number expected, got {_tokenizer.TokenType}"); } return ParseNumber(negative: true); } if (_tokenizer.IsNumber()) { return ParseNumber(negative: false); } if (_tokenizer.TokenType == ConditionTokenType.String) { string text = _tokenizer.TokenValue.Substring(1, _tokenizer.TokenValue.Length - 2).Replace("''", "'"); SimpleLayout simpleLayout = (string.IsNullOrEmpty(text) ? SimpleLayout.Default : new SimpleLayout(text, _configurationItemFactory)); _tokenizer.GetNextToken(); if (simpleLayout.IsFixedText) { return new ConditionLiteralExpression(simpleLayout.FixedText); } return new ConditionLayoutExpression(simpleLayout); } if (_tokenizer.TokenType == ConditionTokenType.Keyword) { string text2 = _tokenizer.EatKeyword(); if (TryPlainKeywordToExpression(text2, out ConditionExpression expression) && expression != null) { return expression; } if (_tokenizer.TokenType == ConditionTokenType.LeftParen) { _tokenizer.GetNextToken(); return ParseMethodPredicate(text2); } } throw new ConditionParseException("Unexpected token: " + _tokenizer.TokenValue); } private bool TryPlainKeywordToExpression(string keyword, out ConditionExpression? expression) { if (string.Equals(keyword, "level", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionLevelExpression(); return true; } if (string.Equals(keyword, "logger", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionLoggerNameExpression(); return true; } if (string.Equals(keyword, "message", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionMessageExpression(); return true; } if (string.Equals(keyword, "exception", StringComparison.OrdinalIgnoreCase)) { expression = new ConditionExceptionExpression(); return true; } if (string.Equals(keyword, "loglevel", StringComparison.OrdinalIgnoreCase)) { _tokenizer.Expect(ConditionTokenType.Dot); expression = new ConditionLiteralExpression(LogLevel.FromString(_tokenizer.EatKeyword())); return true; } if (string.Equals(keyword, "true", StringComparison.OrdinalIgnoreCase)) { expression = ConditionLiteralExpression.True; return true; } if (string.Equals(keyword, "false", StringComparison.OrdinalIgnoreCase)) { expression = ConditionLiteralExpression.False; return true; } if (string.Equals(keyword, "null", StringComparison.OrdinalIgnoreCase)) { expression = ConditionLiteralExpression.Null; return true; } expression = null; return false; } private ConditionExpression ParseNumber(bool negative) { string tokenValue = _tokenizer.TokenValue; _tokenizer.GetNextToken(); if (tokenValue.IndexOf('.') >= 0) { double num = double.Parse(tokenValue, CultureInfo.InvariantCulture); return new ConditionLiteralExpression(negative ? (0.0 - num) : num); } int num2 = int.Parse(tokenValue, CultureInfo.InvariantCulture); return new ConditionLiteralExpression(negative ? (-num2) : num2); } private ConditionExpression ParseBooleanRelation() { ConditionExpression conditionExpression = ParseLiteralExpression(); if (_tokenizer.IsToken(ConditionTokenType.EqualTo)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(conditionExpression, ParseLiteralExpression(), ConditionRelationalOperator.Equal); } if (_tokenizer.IsToken(ConditionTokenType.NotEqual)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(conditionExpression, ParseLiteralExpression(), ConditionRelationalOperator.NotEqual); } if (_tokenizer.IsToken(ConditionTokenType.LessThan)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(conditionExpression, ParseLiteralExpression(), ConditionRelationalOperator.Less); } if (_tokenizer.IsToken(ConditionTokenType.GreaterThan)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(conditionExpression, ParseLiteralExpression(), ConditionRelationalOperator.Greater); } if (_tokenizer.IsToken(ConditionTokenType.LessThanOrEqualTo)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(conditionExpression, ParseLiteralExpression(), ConditionRelationalOperator.LessOrEqual); } if (_tokenizer.IsToken(ConditionTokenType.GreaterThanOrEqualTo)) { _tokenizer.GetNextToken(); return new ConditionRelationalExpression(conditionExpression, ParseLiteralExpression(), ConditionRelationalOperator.GreaterOrEqual); } return conditionExpression; } private ConditionExpression ParseBooleanPredicate() { if (_tokenizer.IsKeyword("not") || _tokenizer.IsToken(ConditionTokenType.Not)) { _tokenizer.GetNextToken(); return new ConditionNotExpression(ParseBooleanPredicate()); } return ParseBooleanRelation(); } private ConditionExpression ParseBooleanAnd() { ConditionExpression conditionExpression = ParseBooleanPredicate(); while (_tokenizer.IsKeyword("and") || _tokenizer.IsToken(ConditionTokenType.And)) { _tokenizer.GetNextToken(); conditionExpression = new ConditionAndExpression(conditionExpression, ParseBooleanPredicate()); } return conditionExpression; } private ConditionExpression ParseBooleanOr() { ConditionExpression conditionExpression = ParseBooleanAnd(); while (_tokenizer.IsKeyword("or") || _tokenizer.IsToken(ConditionTokenType.Or)) { _tokenizer.GetNextToken(); conditionExpression = new ConditionOrExpression(conditionExpression, ParseBooleanAnd()); } return conditionExpression; } private ConditionExpression ParseBooleanExpression() { return ParseBooleanOr(); } private ConditionExpression ParseExpression() { return ParseBooleanExpression(); } } internal sealed class ConditionRelationalExpression : ConditionExpression { private static Dictionary TypePromoteOrder = BuildTypeOrderDictionary(); public ConditionExpression LeftExpression { get; } public ConditionExpression RightExpression { get; } public ConditionRelationalOperator RelationalOperator { get; } public ConditionRelationalExpression(ConditionExpression leftExpression, ConditionExpression rightExpression, ConditionRelationalOperator relationalOperator) { LeftExpression = leftExpression; RightExpression = rightExpression; RelationalOperator = relationalOperator; } public override string ToString() { return $"({LeftExpression} {GetOperatorString()} {RightExpression})"; } protected override object EvaluateNode(LogEventInfo context) { object? leftValue = LeftExpression.Evaluate(context); object rightValue = RightExpression.Evaluate(context); if (!Compare(leftValue, rightValue, RelationalOperator)) { return ConditionExpression.BoxedFalse; } return ConditionExpression.BoxedTrue; } private static bool Compare(object? leftValue, object? rightValue, ConditionRelationalOperator relationalOperator) { IComparer ordinal = StringComparer.Ordinal; PromoteTypes(ref leftValue, ref rightValue); return relationalOperator switch { ConditionRelationalOperator.Equal => ordinal.Compare(leftValue, rightValue) == 0, ConditionRelationalOperator.NotEqual => ordinal.Compare(leftValue, rightValue) != 0, ConditionRelationalOperator.Greater => ordinal.Compare(leftValue, rightValue) > 0, ConditionRelationalOperator.GreaterOrEqual => ordinal.Compare(leftValue, rightValue) >= 0, ConditionRelationalOperator.LessOrEqual => ordinal.Compare(leftValue, rightValue) <= 0, ConditionRelationalOperator.Less => ordinal.Compare(leftValue, rightValue) < 0, _ => throw new NotSupportedException($"Relational operator {relationalOperator} is not supported."), }; } private static void PromoteTypes(ref object? leftValue, ref object? rightValue) { if (leftValue == rightValue || leftValue == null || rightValue == null) { return; } Type type = leftValue.GetType(); Type type2 = rightValue.GetType(); if (type == type2) { return; } int order = GetOrder(type); int order2 = GetOrder(type2); if (order < order2) { if (TryPromoteTypes(ref rightValue, type, ref leftValue, type2)) { return; } } else if (TryPromoteTypes(ref leftValue, type2, ref rightValue, type)) { return; } throw new ConditionEvaluationException("Cannot find common type for '" + type.Name + "' and '" + type2.Name + "'."); } private static bool TryPromoteType(ref object val, Type type1) { try { if (type1 == typeof(DateTime)) { val = Convert.ToDateTime(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(double)) { val = Convert.ToDouble(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(float)) { val = Convert.ToSingle(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(decimal)) { val = Convert.ToDecimal(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(long)) { val = Convert.ToInt64(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(int)) { val = Convert.ToInt32(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(bool)) { val = Convert.ToBoolean(val, CultureInfo.InvariantCulture); return true; } if (type1 == typeof(LogLevel)) { string levelName = Convert.ToString(val, CultureInfo.InvariantCulture) ?? string.Empty; val = LogLevel.FromString(levelName); return true; } if (type1 == typeof(string)) { val = Convert.ToString(val, CultureInfo.InvariantCulture) ?? string.Empty; return true; } } catch (Exception ex) { InternalLogger.Debug("conversion of {0} to {1} failed - {2}", val, type1.Name, ex.Message); } return false; } private static bool TryPromoteTypes(ref object val1, Type type1, ref object val2, Type type2) { if (!TryPromoteType(ref val1, type1)) { return TryPromoteType(ref val2, type2); } return true; } private static int GetOrder(Type type1) { if (TypePromoteOrder.TryGetValue(type1, out var value)) { return value; } return int.MaxValue; } private static Dictionary BuildTypeOrderDictionary() { List list = new List { typeof(DateTime), typeof(double), typeof(float), typeof(decimal), typeof(long), typeof(int), typeof(bool), typeof(LogLevel), typeof(string) }; Dictionary dictionary = new Dictionary(list.Count); for (int i = 0; i < list.Count; i++) { dictionary.Add(list[i], i); } return dictionary; } private string GetOperatorString() { return RelationalOperator switch { ConditionRelationalOperator.Equal => "==", ConditionRelationalOperator.NotEqual => "!=", ConditionRelationalOperator.Greater => ">", ConditionRelationalOperator.Less => "<", ConditionRelationalOperator.GreaterOrEqual => ">=", ConditionRelationalOperator.LessOrEqual => "<=", _ => throw new NotSupportedException($"Relational operator {RelationalOperator} is not supported."), }; } } internal enum ConditionRelationalOperator { Equal, NotEqual, Less, Greater, LessOrEqual, GreaterOrEqual } internal sealed class ConditionTokenizer { private readonly struct CharToTokenType { public readonly char Character; public readonly ConditionTokenType TokenType; public CharToTokenType(char character, ConditionTokenType tokenType) { Character = character; TokenType = tokenType; } } private static readonly ConditionTokenType[] CharIndexToTokenType = BuildCharIndexToTokenType(); private readonly SimpleStringReader _stringReader; public ConditionTokenType TokenType { get; private set; } public string TokenValue { get; private set; } public ConditionTokenizer(SimpleStringReader stringReader) { _stringReader = stringReader; TokenType = ConditionTokenType.BeginningOfInput; TokenValue = string.Empty; GetNextToken(); } public void Expect(ConditionTokenType tokenType) { if (TokenType != tokenType) { throw new ConditionParseException($"Expected token of type: {tokenType}, got {TokenType} ({TokenValue})."); } GetNextToken(); } public string EatKeyword() { if (TokenType != ConditionTokenType.Keyword) { throw new ConditionParseException("Identifier expected"); } string tokenValue = TokenValue; GetNextToken(); return tokenValue; } public bool IsKeyword(string keyword) { if (TokenType != ConditionTokenType.Keyword) { return false; } return TokenValue.Equals(keyword, StringComparison.OrdinalIgnoreCase); } public bool IsEOF() { return TokenType == ConditionTokenType.EndOfInput; } public bool IsNumber() { return TokenType == ConditionTokenType.Number; } public bool IsToken(ConditionTokenType tokenType) { return TokenType == tokenType; } public void GetNextToken() { if (TokenType == ConditionTokenType.EndOfInput) { throw new ConditionParseException("Cannot read past end of stream."); } SkipWhitespace(); int num = PeekChar(); if (num == -1) { TokenType = ConditionTokenType.EndOfInput; return; } char c = (char)num; if (char.IsDigit(c)) { ParseNumber(c); return; } switch (c) { case '\'': ParseSingleQuotedString(c); break; default: if (!char.IsLetter(c)) { if (c == '}' || c == ':') { TokenType = ConditionTokenType.EndOfInput; break; } TokenValue = c.ToString(); if (!TryGetComparisonToken(c) && !TryGetLogicalToken(c)) { if (c < ' ' || c >= '\u0080') { throw new ConditionParseException($"Invalid token: {c}"); } ConditionTokenType conditionTokenType = CharIndexToTokenType[(uint)c]; if (conditionTokenType == ConditionTokenType.Invalid) { throw new ConditionParseException($"Invalid punctuation: {c}"); } TokenType = conditionTokenType; TokenValue = new string(c, 1); ReadChar(); } break; } goto case '_'; case '_': ParseKeyword(c); break; } } private bool TryGetComparisonToken(char ch) { switch (ch) { case '<': ReadChar(); switch (PeekChar()) { case 62: TokenType = ConditionTokenType.NotEqual; TokenValue = "<>"; ReadChar(); return true; case 61: TokenType = ConditionTokenType.LessThanOrEqualTo; TokenValue = "<="; ReadChar(); return true; default: TokenType = ConditionTokenType.LessThan; TokenValue = "<"; return true; } case '>': ReadChar(); if (PeekChar() == 61) { TokenType = ConditionTokenType.GreaterThanOrEqualTo; TokenValue = ">="; ReadChar(); return true; } TokenType = ConditionTokenType.GreaterThan; TokenValue = ">"; return true; default: return false; } } private bool TryGetLogicalToken(char ch) { switch (ch) { case '!': ReadChar(); if (PeekChar() == 61) { TokenType = ConditionTokenType.NotEqual; TokenValue = "!="; ReadChar(); return true; } TokenType = ConditionTokenType.Not; TokenValue = "!"; return true; case '&': ReadChar(); if (PeekChar() == 38) { TokenType = ConditionTokenType.And; TokenValue = "&&"; ReadChar(); return true; } throw new ConditionParseException("Expected '&&' but got '&'"); case '|': ReadChar(); if (PeekChar() == 124) { TokenType = ConditionTokenType.Or; TokenValue = "||"; ReadChar(); return true; } throw new ConditionParseException("Expected '||' but got '|'"); case '=': ReadChar(); if (PeekChar() == 61) { TokenType = ConditionTokenType.EqualTo; TokenValue = "=="; ReadChar(); return true; } TokenType = ConditionTokenType.EqualTo; TokenValue = "="; return true; default: return false; } } private static ConditionTokenType[] BuildCharIndexToTokenType() { CharToTokenType[] array = new CharToTokenType[6] { new CharToTokenType('(', ConditionTokenType.LeftParen), new CharToTokenType(')', ConditionTokenType.RightParen), new CharToTokenType('.', ConditionTokenType.Dot), new CharToTokenType(',', ConditionTokenType.Comma), new CharToTokenType('!', ConditionTokenType.Not), new CharToTokenType('-', ConditionTokenType.Minus) }; ConditionTokenType[] array2 = new ConditionTokenType[128]; for (int i = 0; i < 128; i++) { array2[i] = ConditionTokenType.Invalid; } CharToTokenType[] array3 = array; for (int j = 0; j < array3.Length; j++) { CharToTokenType charToTokenType = array3[j]; array2[(uint)charToTokenType.Character] = charToTokenType.TokenType; } return array2; } private void ParseSingleQuotedString(char ch) { TokenType = ConditionTokenType.String; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(ch); ReadChar(); int num; while ((num = PeekChar()) != -1) { ch = (char)num; stringBuilder.Append((char)ReadChar()); if (ch == '\'') { if (PeekChar() != 39) { break; } stringBuilder.Append('\''); ReadChar(); } } if (num == -1) { throw new ConditionParseException("String literal is missing a closing quote character."); } TokenValue = stringBuilder.ToString(); } private void ParseKeyword(char ch) { TokenType = ConditionTokenType.Keyword; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(ch); ReadChar(); int num; while ((num = PeekChar()) != -1 && ((ushort)num == 95 || (ushort)num == 45 || char.IsLetterOrDigit((char)num))) { stringBuilder.Append((char)ReadChar()); } TokenValue = stringBuilder.ToString(); } private void ParseNumber(char ch) { TokenType = ConditionTokenType.Number; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(ch); ReadChar(); int num; while ((num = PeekChar()) != -1) { ch = (char)num; if (!char.IsDigit(ch) && ch != '.') { break; } stringBuilder.Append((char)ReadChar()); } TokenValue = stringBuilder.ToString(); } private void SkipWhitespace() { int num; while ((num = PeekChar()) != -1 && char.IsWhiteSpace((char)num)) { ReadChar(); } } private int PeekChar() { return _stringReader.Peek(); } private int ReadChar() { return _stringReader.Read(); } } internal enum ConditionTokenType { EndOfInput, BeginningOfInput, Number, String, Keyword, Whitespace, FirstPunct, LessThan, GreaterThan, LessThanOrEqualTo, GreaterThanOrEqualTo, EqualTo, NotEqual, LeftParen, RightParen, Dot, Comma, Not, And, Or, Minus, LastPunct, Invalid, ClosingCurlyBrace, Colon, Exclamation, Ampersand, Pipe } } namespace NLog.Common { public delegate void AsyncContinuation(Exception? exception); public static class AsyncHelpers { internal static int GetManagedThreadId() { return Thread.CurrentThread.ManagedThreadId; } internal static void StartAsyncTask(WaitCallback asyncDelegate, object? state) { ThreadPool.QueueUserWorkItem(asyncDelegate, state); } internal static void WaitForDelay(TimeSpan delay) { Thread.Sleep(delay); } [Obsolete("Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static void ForEachItemSequentially(IEnumerable items, AsyncContinuation asyncContinuation, AsynchronousAction action) { AsyncContinuation asyncContinuation2 = asyncContinuation; AsynchronousAction action2 = action; action2 = ExceptionGuard(action2); IEnumerator enumerator = items.GetEnumerator(); InvokeNext(null); void InvokeNext(Exception? ex) { if (ex != null) { asyncContinuation2(ex); } else if (!enumerator.MoveNext()) { enumerator.Dispose(); asyncContinuation2(null); } else { action2(enumerator.Current, PreventMultipleCalls(InvokeNext)); } } } public static void Repeat(int repeatCount, AsyncContinuation asyncContinuation, AsynchronousAction action) { AsyncContinuation asyncContinuation2 = asyncContinuation; AsynchronousAction action2 = action; action2 = ExceptionGuard(action2); int remaining = repeatCount; InvokeNext(null); void InvokeNext(Exception? ex) { if (ex != null) { asyncContinuation2(ex); } else if (remaining-- <= 0) { asyncContinuation2(null); } else { action2(PreventMultipleCalls(InvokeNext)); } } } [Obsolete("Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static AsyncContinuation PrecededBy(AsyncContinuation asyncContinuation, AsynchronousAction action) { AsyncContinuation asyncContinuation2 = asyncContinuation; AsynchronousAction action2 = action; action2 = ExceptionGuard(action2); return delegate(Exception? ex) { if (ex != null) { asyncContinuation2(ex); } else { action2(PreventMultipleCalls(asyncContinuation2)); } }; } [Obsolete("Marked obsolete on NLog 6.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static AsyncContinuation WithTimeout(AsyncContinuation asyncContinuation, TimeSpan timeout) { return new TimeoutContinuation(asyncContinuation, timeout).Function; } public static void ForEachItemInParallel(IEnumerable values, AsyncContinuation asyncContinuation, AsynchronousAction action) { AsyncContinuation asyncContinuation2 = asyncContinuation; AsynchronousAction action2 = action; List list = new List(values); int remaining = list.Count; InternalLogger.Trace("ForEachItemInParallel() {0} items", list.Count); if (remaining == 0) { asyncContinuation2(null); return; } action2 = ExceptionGuard(action2); IList exceptions = null; AsyncContinuation continuation = delegate(Exception? ex) { InternalLogger.Trace("Continuation invoked: {0}", ex); if (ex != null) { if (exceptions == null) { Interlocked.CompareExchange(ref exceptions, new List(), null); } lock (exceptions) { exceptions.Add(ex); } } int num = Interlocked.Decrement(ref remaining); InternalLogger.Trace("Parallel task completed. {0} items remaining", num); if (num == 0) { Exception combinedException = GetCombinedException(exceptions ?? ArrayHelper.Empty()); if (combinedException == null) { StartAsyncTask(delegate(object s) { ((AsyncContinuation)s)(null); }, asyncContinuation2); } else { StartAsyncTask(delegate(object s) { ((AsyncContinuation)s)(combinedException); }, asyncContinuation2); } } }; foreach (T item in list) { T itemCopy = item; StartAsyncTask(delegate { AsyncContinuation asyncContinuation3 = PreventMultipleCalls(continuation); try { action2(itemCopy, asyncContinuation3); } catch (Exception ex2) { InternalLogger.Error(ex2, "ForEachItemInParallel - Unhandled Exception"); asyncContinuation3(ex2); } }, null); } } [Obsolete("Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public static void RunSynchronously(AsynchronousAction action) { ManualResetEvent ev = new ManualResetEvent(initialState: false); Exception lastException = null; action(PreventMultipleCalls(delegate(Exception? ex) { lastException = ex; ev.Set(); })); ev.WaitOne(); if (lastException != null) { throw new NLogRuntimeException("Asynchronous exception has occurred.", lastException); } } public static AsyncContinuation PreventMultipleCalls(AsyncContinuation asyncContinuation) { if (asyncContinuation.Target is SingleCallContinuation) { return asyncContinuation; } return new SingleCallContinuation(asyncContinuation).Function; } public static Exception? GetCombinedException(IList exceptions) { if (exceptions.Count == 0) { return null; } if (exceptions.Count == 1) { return exceptions[0]; } StringBuilder stringBuilder = new StringBuilder(); string value = string.Empty; string newLine = Environment.NewLine; foreach (Exception exception in exceptions) { stringBuilder.Append(value); stringBuilder.Append(exception.ToString()); stringBuilder.Append(newLine); value = newLine; } return new NLogRuntimeException("Got multiple exceptions:\r\n" + stringBuilder); } private static AsynchronousAction ExceptionGuard(AsynchronousAction action) { AsynchronousAction action2 = action; return delegate(AsyncContinuation cont) { try { action2(cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } private static AsynchronousAction ExceptionGuard(AsynchronousAction action) { AsynchronousAction action2 = action; return delegate(T argument, AsyncContinuation cont) { try { action2(argument, cont); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } cont(exception); } }; } internal static bool WaitForDispose(this Timer timer, TimeSpan timeout) { timer.Change(-1, -1); if (timeout != TimeSpan.Zero) { ManualResetEvent manualResetEvent = new ManualResetEvent(initialState: false); if (timer.Dispose(manualResetEvent) && !manualResetEvent.WaitOne((int)timeout.TotalMilliseconds)) { return false; } manualResetEvent.Close(); } else { timer.Dispose(); } return true; } } public delegate void AsynchronousAction(AsyncContinuation asyncContinuation); public delegate void AsynchronousAction(T argument, AsyncContinuation asyncContinuation); public readonly struct AsyncLogEventInfo : IEquatable { public LogEventInfo LogEvent { get; } public AsyncContinuation Continuation { get; } public AsyncLogEventInfo(LogEventInfo logEvent, AsyncContinuation continuation) { LogEvent = logEvent; Continuation = continuation; } public static bool operator ==(AsyncLogEventInfo eventInfo1, AsyncLogEventInfo eventInfo2) { return eventInfo1.Equals(eventInfo2); } public static bool operator !=(AsyncLogEventInfo eventInfo1, AsyncLogEventInfo eventInfo2) { return !eventInfo1.Equals(eventInfo2); } public bool Equals(AsyncLogEventInfo other) { if ((object)Continuation == other.Continuation) { return LogEvent == other.LogEvent; } return false; } public override bool Equals(object? obj) { if (obj is AsyncLogEventInfo other) { return Equals(other); } return false; } public override int GetHashCode() { return LogEvent.GetHashCode() ^ Continuation.GetHashCode(); } } public static class ConversionHelpers { [Obsolete("Instead use .NET method Enum.TryParse(). Marked obsolete with NLog v6.1")] [EditorBrowsable(EditorBrowsableState.Never)] public static bool TryParseEnum(string inputValue, out TEnum resultValue, TEnum defaultValue = default(TEnum)) where TEnum : struct { if (!TryParseEnum(inputValue, ignoreCase: true, out resultValue)) { resultValue = defaultValue; return false; } return true; } internal static bool TryParseEnum(string inputValue, Type enumType, out object? resultValue) { if (StringHelpers.IsNullOrWhiteSpace(inputValue)) { resultValue = null; return false; } return Enum.TryParse(enumType, inputValue, ignoreCase: true, out resultValue); } internal static bool TryParseEnum(string inputValue, bool ignoreCase, out TEnum resultValue) where TEnum : struct { if (StringHelpers.IsNullOrWhiteSpace(inputValue)) { resultValue = default(TEnum); return false; } return Enum.TryParse(inputValue, ignoreCase, out resultValue); } } internal interface IInternalLoggerContext { string Name { get; } LogFactory? LogFactory { get; } } public delegate void InternalEventOccurredHandler(object? sender, InternalLogEventArgs e); public readonly struct InternalLogEventArgs { public string Message { get; } public LogLevel Level { get; } public Exception? Exception { get; } public Type? SenderType { get; } public string? SenderName { get; } internal InternalLogEventArgs(string message, LogLevel level, Exception? exception, Type? senderType, string? senderName) { Message = message; Level = level; Exception = exception; SenderType = senderType; SenderName = senderName; } } public static class InternalLogger { private static readonly object LockObject = new object(); private static LogLevel? _logLevel; private static bool _logToConsole; private static bool _logToConsoleError; private static string? _logFile; private static TextWriter? _logWriter; public static bool IsTraceEnabled => IsLogLevelEnabled(NLog.LogLevel.Trace); public static bool IsDebugEnabled => IsLogLevelEnabled(NLog.LogLevel.Debug); public static bool IsInfoEnabled => IsLogLevelEnabled(NLog.LogLevel.Info); public static bool IsWarnEnabled => IsLogLevelEnabled(NLog.LogLevel.Warn); public static bool IsErrorEnabled => IsLogLevelEnabled(NLog.LogLevel.Error); public static bool IsFatalEnabled => IsLogLevelEnabled(NLog.LogLevel.Fatal); public static LogLevel LogLevel { get { return _logLevel ?? NLog.LogLevel.Off; } set { _logLevel = value; } } public static bool LogToConsole { get { return _logToConsole; } set { if (_logToConsole == value) { return; } InternalEventOccurred -= LogToConsoleSubscription; if (value) { InternalEventOccurred += LogToConsoleSubscription; if ((object)_logLevel == null) { _logLevel = NLog.LogLevel.Info; } } _logToConsole = value; } } public static bool LogToConsoleError { get { return _logToConsoleError; } set { if (_logToConsoleError == value) { return; } InternalEventOccurred -= LogToConsoleErrorSubscription; if (value) { InternalEventOccurred += LogToConsoleErrorSubscription; if ((object)_logLevel == null) { _logLevel = NLog.LogLevel.Info; } } _logToConsoleError = value; } } public static string? LogFile { get { return _logFile; } set { if (!string.Equals(_logFile, value, StringComparison.Ordinal)) { InternalEventOccurred -= LogToFileSubscription; if (!string.IsNullOrEmpty(value)) { InternalEventOccurred += LogToFileSubscription; if ((object)_logLevel == null) { _logLevel = NLog.LogLevel.Info; } } _logFile = value; } string text = (_logFile = ((value != null && !string.IsNullOrEmpty(value)) ? ExpandFilePathVariables(value) : null)); if (text != null) { CreateDirectoriesIfNeeded(text); } } } public static TextWriter? LogWriter { get { return _logWriter; } set { if (value != null && (object)_logLevel == null) { _logLevel = NLog.LogLevel.Info; } _logWriter = value; } } public static bool IncludeTimestamp { get; set; } = true; internal static bool ExceptionThrowWhenWriting { get; private set; } public static event InternalEventOccurredHandler? InternalEventOccurred; [StringFormatMethod("message")] public static void Trace([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsTraceEnabled) { Write(null, NLog.LogLevel.Trace, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Trace(Exception? ex, [Localizable(false)] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsTraceEnabled) { Write(ex, NLog.LogLevel.Trace, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Trace([Localizable(false)] string message, params object?[] args) { Write(null, NLog.LogLevel.Trace, message, args); } public static void Trace([Localizable(false)] string message) { Write(null, NLog.LogLevel.Trace, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Trace(Func messageFunc) { if (IsTraceEnabled) { Write(null, NLog.LogLevel.Trace, messageFunc(), null); } } [StringFormatMethod("message")] public static void Trace(Exception? ex, [Localizable(false)] string message, params object?[] args) { Write(ex, NLog.LogLevel.Trace, message, args); } [StringFormatMethod("message")] public static void Trace([Localizable(false)] string message, TArgument1? arg0) { if (IsTraceEnabled) { Log(null, NLog.LogLevel.Trace, message, new ReadOnlySpan(new object[1] { arg0 })); } } [StringFormatMethod("message")] public static void Trace([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1) { if (IsTraceEnabled) { Log(null, NLog.LogLevel.Trace, message, new ReadOnlySpan(new object[2] { arg0, arg1 })); } } [StringFormatMethod("message")] public static void Trace([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1, TArgument3? arg2) { if (IsTraceEnabled) { Log(null, NLog.LogLevel.Trace, message, new ReadOnlySpan(new object[3] { arg0, arg1, arg2 })); } } public static void Trace(Exception? ex, [Localizable(false)] string message) { Write(ex, NLog.LogLevel.Trace, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Trace(Exception? ex, Func messageFunc) { if (IsTraceEnabled) { Write(ex, NLog.LogLevel.Trace, messageFunc(), null); } } [StringFormatMethod("message")] public static void Debug([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsDebugEnabled) { Write(null, NLog.LogLevel.Debug, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Debug(Exception? ex, [Localizable(false)] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsDebugEnabled) { Write(ex, NLog.LogLevel.Debug, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Debug([Localizable(false)] string message, params object?[] args) { Write(null, NLog.LogLevel.Debug, message, args); } public static void Debug([Localizable(false)] string message) { Write(null, NLog.LogLevel.Debug, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Debug(Func messageFunc) { if (IsDebugEnabled) { Write(null, NLog.LogLevel.Debug, messageFunc(), null); } } [StringFormatMethod("message")] public static void Debug(Exception? ex, [Localizable(false)] string message, params object?[] args) { Write(ex, NLog.LogLevel.Debug, message, args); } [StringFormatMethod("message")] public static void Debug([Localizable(false)] string message, TArgument1? arg0) { if (IsDebugEnabled) { Log(null, NLog.LogLevel.Debug, message, new ReadOnlySpan(new object[1] { arg0 })); } } [StringFormatMethod("message")] public static void Debug([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1) { if (IsDebugEnabled) { Log(null, NLog.LogLevel.Debug, message, new ReadOnlySpan(new object[2] { arg0, arg1 })); } } [StringFormatMethod("message")] public static void Debug([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1, TArgument3? arg2) { if (IsDebugEnabled) { Log(null, NLog.LogLevel.Debug, message, new ReadOnlySpan(new object[3] { arg0, arg1, arg2 })); } } public static void Debug(Exception? ex, [Localizable(false)] string message) { Write(ex, NLog.LogLevel.Debug, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Debug(Exception? ex, Func messageFunc) { if (IsDebugEnabled) { Write(ex, NLog.LogLevel.Debug, messageFunc(), null); } } [StringFormatMethod("message")] public static void Info([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsInfoEnabled) { Write(null, NLog.LogLevel.Info, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Info(Exception? ex, [Localizable(false)] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsInfoEnabled) { Write(ex, NLog.LogLevel.Info, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Info([Localizable(false)] string message, params object?[] args) { Write(null, NLog.LogLevel.Info, message, args); } public static void Info([Localizable(false)] string message) { Write(null, NLog.LogLevel.Info, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Info(Func messageFunc) { if (IsInfoEnabled) { Write(null, NLog.LogLevel.Info, messageFunc(), null); } } [StringFormatMethod("message")] public static void Info(Exception? ex, [Localizable(false)] string message, params object?[] args) { Write(ex, NLog.LogLevel.Info, message, args); } [StringFormatMethod("message")] public static void Info([Localizable(false)] string message, TArgument1? arg0) { if (IsInfoEnabled) { Log(null, NLog.LogLevel.Info, message, new ReadOnlySpan(new object[1] { arg0 })); } } [StringFormatMethod("message")] public static void Info([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1) { if (IsInfoEnabled) { Log(null, NLog.LogLevel.Info, message, new ReadOnlySpan(new object[2] { arg0, arg1 })); } } [StringFormatMethod("message")] public static void Info([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1, TArgument3? arg2) { if (IsInfoEnabled) { Log(null, NLog.LogLevel.Info, message, new ReadOnlySpan(new object[3] { arg0, arg1, arg2 })); } } public static void Info(Exception? ex, [Localizable(false)] string message) { Write(ex, NLog.LogLevel.Info, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Info(Exception? ex, Func messageFunc) { if (IsInfoEnabled) { Write(ex, NLog.LogLevel.Info, messageFunc(), null); } } [StringFormatMethod("message")] public static void Warn([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsWarnEnabled) { Write(null, NLog.LogLevel.Warn, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Warn(Exception? ex, [Localizable(false)] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsWarnEnabled) { Write(ex, NLog.LogLevel.Warn, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Warn([Localizable(false)] string message, params object?[] args) { Write(null, NLog.LogLevel.Warn, message, args); } public static void Warn([Localizable(false)] string message) { Write(null, NLog.LogLevel.Warn, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Warn(Func messageFunc) { if (IsWarnEnabled) { Write(null, NLog.LogLevel.Warn, messageFunc(), null); } } [StringFormatMethod("message")] public static void Warn(Exception? ex, [Localizable(false)] string message, params object?[] args) { Write(ex, NLog.LogLevel.Warn, message, args); } [StringFormatMethod("message")] public static void Warn([Localizable(false)] string message, TArgument1? arg0) { if (IsWarnEnabled) { Log(null, NLog.LogLevel.Warn, message, new ReadOnlySpan(new object[1] { arg0 })); } } [StringFormatMethod("message")] public static void Warn([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1) { if (IsWarnEnabled) { Log(null, NLog.LogLevel.Warn, message, new ReadOnlySpan(new object[2] { arg0, arg1 })); } } [StringFormatMethod("message")] public static void Warn([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1, TArgument3? arg2) { if (IsWarnEnabled) { Log(null, NLog.LogLevel.Warn, message, new ReadOnlySpan(new object[3] { arg0, arg1, arg2 })); } } public static void Warn(Exception? ex, [Localizable(false)] string message) { Write(ex, NLog.LogLevel.Warn, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Warn(Exception? ex, Func messageFunc) { if (IsWarnEnabled) { Write(ex, NLog.LogLevel.Warn, messageFunc(), null); } } [StringFormatMethod("message")] public static void Error([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsErrorEnabled) { Write(null, NLog.LogLevel.Error, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Error(Exception? ex, [Localizable(false)] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsErrorEnabled) { Write(ex, NLog.LogLevel.Error, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Error([Localizable(false)] string message, params object?[] args) { Write(null, NLog.LogLevel.Error, message, args); } public static void Error([Localizable(false)] string message) { Write(null, NLog.LogLevel.Error, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Error(Func messageFunc) { if (IsErrorEnabled) { Write(null, NLog.LogLevel.Error, messageFunc(), null); } } [StringFormatMethod("message")] public static void Error(Exception? ex, [Localizable(false)] string message, params object?[] args) { Write(ex, NLog.LogLevel.Error, message, args); } [StringFormatMethod("message")] public static void Error([Localizable(false)] string message, TArgument1? arg0) { if (IsErrorEnabled) { Log(null, NLog.LogLevel.Error, message, new ReadOnlySpan(new object[1] { arg0 })); } } [StringFormatMethod("message")] public static void Error([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1) { if (IsErrorEnabled) { Log(null, NLog.LogLevel.Error, message, new ReadOnlySpan(new object[2] { arg0, arg1 })); } } [StringFormatMethod("message")] public static void Error([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1, TArgument3? arg2) { if (IsErrorEnabled) { Log(null, NLog.LogLevel.Error, message, new ReadOnlySpan(new object[3] { arg0, arg1, arg2 })); } } public static void Error(Exception? ex, [Localizable(false)] string message) { Write(ex, NLog.LogLevel.Error, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Error(Exception? ex, Func messageFunc) { if (IsErrorEnabled) { Write(ex, NLog.LogLevel.Error, messageFunc(), null); } } [StringFormatMethod("message")] public static void Fatal([Localizable(false)][StructuredMessageTemplate] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsFatalEnabled) { Write(null, NLog.LogLevel.Fatal, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Fatal(Exception? ex, [Localizable(false)] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsFatalEnabled) { Write(ex, NLog.LogLevel.Fatal, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Fatal([Localizable(false)] string message, params object?[] args) { Write(null, NLog.LogLevel.Fatal, message, args); } public static void Fatal([Localizable(false)] string message) { Write(null, NLog.LogLevel.Fatal, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Fatal(Func messageFunc) { if (IsFatalEnabled) { Write(null, NLog.LogLevel.Fatal, messageFunc(), null); } } [StringFormatMethod("message")] public static void Fatal(Exception? ex, [Localizable(false)] string message, params object?[] args) { Write(ex, NLog.LogLevel.Fatal, message, args); } [StringFormatMethod("message")] public static void Fatal([Localizable(false)] string message, TArgument1? arg0) { if (IsFatalEnabled) { Log(null, NLog.LogLevel.Fatal, message, new ReadOnlySpan(new object[1] { arg0 })); } } [StringFormatMethod("message")] public static void Fatal([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1) { if (IsFatalEnabled) { Log(null, NLog.LogLevel.Fatal, message, new ReadOnlySpan(new object[2] { arg0, arg1 })); } } [StringFormatMethod("message")] public static void Fatal([Localizable(false)] string message, TArgument1? arg0, TArgument2? arg1, TArgument3? arg2) { if (IsFatalEnabled) { Log(null, NLog.LogLevel.Fatal, message, new ReadOnlySpan(new object[3] { arg0, arg1, arg2 })); } } public static void Fatal(Exception? ex, [Localizable(false)] string message) { Write(ex, NLog.LogLevel.Fatal, message, null); } [Obsolete("Avoid delegate capture allocations. Marked obsolete with v5.3")] [EditorBrowsable(EditorBrowsableState.Never)] public static void Fatal(Exception? ex, Func messageFunc) { if (IsFatalEnabled) { Write(ex, NLog.LogLevel.Fatal, messageFunc(), null); } } public static void Reset() { ExceptionThrowWhenWriting = false; IncludeTimestamp = true; LogWriter = null; LogToConsole = false; LogToConsoleError = false; LogFile = null; InternalLogger.InternalEventOccurred = null; _logLevel = null; } [StringFormatMethod("message")] public static void Log(LogLevel level, [Localizable(false)] string message, params object?[] args) { Write(null, level, message, args); } [StringFormatMethod("message")] public static void Log(LogLevel level, [Localizable(false)] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsLogLevelEnabled(level)) { Write(null, level, message, args.IsEmpty ? null : args.ToArray()); } } [StringFormatMethod("message")] public static void Log(Exception? ex, LogLevel level, [Localizable(false)] string message, [ParamCollection] scoped ReadOnlySpan args) { if (IsLogLevelEnabled(level)) { Write(ex, level, message, args.IsEmpty ? null : args.ToArray()); } } public static void Log(LogLevel level, [Localizable(false)] string message) { Write(null, level, message, null); } public static void Log(LogLevel level, [Localizable(false)] Func messageFunc) { if (IsLogLevelEnabled(level)) { Write(null, level, messageFunc(), null); } } public static void Log(Exception? ex, LogLevel level, [Localizable(false)] Func messageFunc) { if (IsLogLevelEnabled(level)) { Write(ex, level, messageFunc(), null); } } [StringFormatMethod("message")] public static void Log(Exception? ex, LogLevel level, [Localizable(false)] string message, params object?[] args) { Write(ex, level, message, args); } public static void Log(Exception? ex, LogLevel level, [Localizable(false)] string message) { Write(ex, level, message, null); } private static void Write(Exception? ex, LogLevel level, string message, object?[]? args) { if (!IsLogLevelEnabled(level) || (InternalLogger.InternalEventOccurred == null && _logWriter == null) || IsSeriousException(ex)) { return; } string fullMessage = message; try { fullMessage = ((args != null && args.Length != 0) ? string.Format(CultureInfo.InvariantCulture, message, args) : message); } catch (Exception ex2) { if (ex == null) { ex = ex2; } if (NLog.LogLevel.Error > level) { level = NLog.LogLevel.Error; } } try { IInternalLoggerContext loggerContext = ((args != null && args.Length != 0) ? (args[0] as IInternalLoggerContext) : null); WriteToLog(level, ex, fullMessage, loggerContext); ex?.MarkAsLoggedToInternalLogger(); } catch (Exception exception) { ExceptionThrowWhenWriting = true; if (exception.MustBeRethrownImmediately()) { throw; } } } private static void WriteToLog(LogLevel level, Exception? ex, string fullMessage, IInternalLoggerContext? loggerContext) { if (_logWriter != null) { string value = CreateLogLine(ex, level, fullMessage); lock (LockObject) { _logWriter?.WriteLine(value); } } if (InternalLogger.InternalEventOccurred != null) { string senderName = ((loggerContext != null && !string.IsNullOrEmpty(loggerContext.Name)) ? loggerContext.Name : loggerContext?.ToString()); InternalLogger.InternalEventOccurred?.Invoke(null, new InternalLogEventArgs(fullMessage, level, ex, loggerContext?.GetType(), senderName)); } } private static string CreateLogLine(Exception? ex, LogLevel level, string fullMessage) { if (IncludeTimestamp) { return TimeSource.Current.Time.ToString("yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture) + " " + level.ToString() + " " + fullMessage + ((ex != null) ? " Exception: " : string.Empty) + (ex?.ToString() ?? ""); } return level.ToString() + " " + fullMessage + ((ex != null) ? " Exception: " : string.Empty) + (ex?.ToString() ?? string.Empty); } private static bool IsSeriousException(Exception? exception) { return exception?.MustBeRethrownImmediately() ?? false; } private static bool IsLogLevelEnabled(LogLevel logLevel) { if ((object)_logLevel != null && (object)logLevel != null) { return _logLevel.Ordinal <= logLevel.Ordinal; } return false; } private static void CreateDirectoriesIfNeeded(string filename) { try { if (!(LogLevel == NLog.LogLevel.Off)) { string directoryName = Path.GetDirectoryName(filename); if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(directoryName); } } } catch (Exception ex) { Error(ex, "Cannot create needed directories to '{0}'.", new ReadOnlySpan(new object[1] { filename })); if (ex.MustBeRethrownImmediately()) { throw; } } } private static string ExpandFilePathVariables(string internalLogFile) { try { if (ContainsSubStringIgnoreCase(internalLogFile, "${currentdir}", out string result)) { internalLogFile = internalLogFile.Replace(result, Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar); } if (ContainsSubStringIgnoreCase(internalLogFile, "${basedir}", out string result2)) { internalLogFile = internalLogFile.Replace(result2, LogManager.LogFactory.CurrentAppEnvironment.AppDomainBaseDirectory + Path.DirectorySeparatorChar); } if (ContainsSubStringIgnoreCase(internalLogFile, "${tempdir}", out string result3)) { internalLogFile = internalLogFile.Replace(result3, LogManager.LogFactory.CurrentAppEnvironment.UserTempFilePath + Path.DirectorySeparatorChar); } if (ContainsSubStringIgnoreCase(internalLogFile, "${processdir}", out string result4)) { internalLogFile = internalLogFile.Replace(result4, Path.GetDirectoryName(LogManager.LogFactory.CurrentAppEnvironment.CurrentProcessFilePath) + Path.DirectorySeparatorChar); } if (ContainsSubStringIgnoreCase(internalLogFile, "${commonApplicationDataDir}", out string result5)) { internalLogFile = internalLogFile.Replace(result5, SpecialFolderLayoutRenderer.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + Path.DirectorySeparatorChar); } if (ContainsSubStringIgnoreCase(internalLogFile, "${userApplicationDataDir}", out string result6)) { internalLogFile = internalLogFile.Replace(result6, SpecialFolderLayoutRenderer.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar); } if (ContainsSubStringIgnoreCase(internalLogFile, "${userLocalApplicationDataDir}", out string result7)) { internalLogFile = internalLogFile.Replace(result7, SpecialFolderLayoutRenderer.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar); } if (internalLogFile.IndexOf('%') >= 0) { internalLogFile = Environment.ExpandEnvironmentVariables(internalLogFile); } if (!string.IsNullOrEmpty(internalLogFile) && internalLogFile.IndexOf('.') >= 0) { internalLogFile = AppEnvironmentWrapper.FixFilePathWithLongUNC(internalLogFile); } return internalLogFile; } catch { return internalLogFile; } } private static bool ContainsSubStringIgnoreCase(string haystack, string needle, out string? result) { int num = haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase); result = ((num >= 0) ? haystack.Substring(num, needle.Length) : null); return result != null; } private static void LogToConsoleSubscription(object? sender, InternalLogEventArgs eventArgs) { string message = CreateLogLine(eventArgs.Exception, eventArgs.Level, eventArgs.Message); ConsoleTargetHelper.WriteLineThreadSafe(Console.Out, message); } private static void LogToConsoleErrorSubscription(object? sender, InternalLogEventArgs eventArgs) { string message = CreateLogLine(eventArgs.Exception, eventArgs.Level, eventArgs.Message); ConsoleTargetHelper.WriteLineThreadSafe(Console.Error, message); } private static void LogToFileSubscription(object? sender, InternalLogEventArgs eventArgs) { if (string.IsNullOrEmpty(_logFile)) { return; } string value = CreateLogLine(eventArgs.Exception, eventArgs.Level, eventArgs.Message); lock (LockObject) { try { using StreamWriter streamWriter = File.AppendText(_logFile); streamWriter.WriteLine(value); } catch (IOException) { } } } } [Obsolete("Use AsyncRequestQueue instead. Marked obsolete on NLog 5.0")] [EditorBrowsable(EditorBrowsableState.Never)] public class LogEventInfoBuffer { private readonly object _lockObject = new object(); private readonly bool _growAsNeeded; private readonly int _growLimit; private AsyncLogEventInfo[] _buffer; private int _getPointer; private int _putPointer; private int _count; public int Size => _buffer.Length; internal int Count { get { lock (_lockObject) { return _count; } } } public LogEventInfoBuffer(int size, bool growAsNeeded, int growLimit) { _growAsNeeded = growAsNeeded; _buffer = new AsyncLogEventInfo[size]; _growLimit = growLimit; _getPointer = 0; _putPointer = 0; } public int Append(AsyncLogEventInfo eventInfo) { lock (_lockObject) { if (_count >= _buffer.Length) { if (_growAsNeeded && _buffer.Length < _growLimit) { int num = _buffer.Length * 2; if (num >= _growLimit) { num = _growLimit; } InternalLogger.Trace("Enlarging LogEventInfoBuffer from {0} to {1}", _buffer.Length, num); AsyncLogEventInfo[] array = new AsyncLogEventInfo[num]; Array.Copy(_buffer, 0, array, 0, _buffer.Length); _buffer = array; } else { _getPointer++; } } _putPointer %= _buffer.Length; _buffer[_putPointer] = eventInfo; _putPointer++; _count++; if (_count >= _buffer.Length) { _count = _buffer.Length; } return _count; } } public AsyncLogEventInfo[] GetEventsAndClear() { lock (_lockObject) { int count = _count; if (count == 0) { return ArrayHelper.Empty(); } AsyncLogEventInfo[] array = new AsyncLogEventInfo[count]; for (int i = 0; i < count; i++) { int num = (_getPointer + i) % _buffer.Length; AsyncLogEventInfo asyncLogEventInfo = _buffer[num]; _buffer[num] = default(AsyncLogEventInfo); array[i] = asyncLogEventInfo; } _count = 0; _getPointer = 0; _putPointer = 0; return array; } } } } namespace JetBrains.Annotations { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.GenericParameter)] internal sealed class CanBeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.GenericParameter)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Delegate)] internal sealed class StringFormatMethodAttribute : Attribute { [NotNull] public string FormatParameterName { get; } public StringFormatMethodAttribute([NotNull] string formatParameterName) { FormatParameterName = formatParameterName; } } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class StructuredMessageTemplateAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] internal sealed class ContractAnnotationAttribute : Attribute { [NotNull] public string Contract { get; } public bool ForceFullStates { get; } public ContractAnnotationAttribute([NotNull] string contract) : this(contract, forceFullStates: false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } } [AttributeUsage(AttributeTargets.All)] internal sealed class UsedImplicitlyAttribute : Attribute { public ImplicitUseKindFlags UseKindFlags { get; } public ImplicitUseTargetFlags TargetFlags { get; } public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)] internal sealed class MeansImplicitUseAttribute : Attribute { [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; } public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [Flags] internal enum ImplicitUseKindFlags { Default = 7, Access = 1, Assign = 2, InstantiatedWithFixedConstructorSignature = 4, InstantiatedNoFixedConstructorSignature = 8 } [Flags] internal enum ImplicitUseTargetFlags { Default = 1, Itself = 1, Members = 2, WithInheritors = 4, WithMembers = 3 } }