|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using Microsoft.Extensions.Configuration; |
| 4 | +using NLog.Config; |
| 5 | +using NLog.Layouts; |
| 6 | +using NLog.LayoutRenderers; |
| 7 | +using System.Text; |
| 8 | + |
| 9 | +namespace NLog.Extensions.Configuration |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Layout renderer that can lookup values from Microsoft Extension Configuration Container (json, xml, ini) |
| 13 | + /// </summary> |
| 14 | + /// <remarks>Not to be confused with NLog.AppConfig that includes ${appsetting}</remarks> |
| 15 | + /// <example> |
| 16 | + /// Example: appsettings.json |
| 17 | + /// { |
| 18 | + /// "Mode":"Prod", |
| 19 | + /// "Options":{ |
| 20 | + /// "StorageConnectionString":"UseDevelopmentStorage=true", |
| 21 | + /// } |
| 22 | + /// } |
| 23 | + /// |
| 24 | + /// Config Setting Lookup: |
| 25 | + /// ${configsetting:name=Mode} = "Prod" |
| 26 | + /// ${configsetting:name=Options.StorageConnectionString} = "UseDevelopmentStorage=true" |
| 27 | + /// ${configsetting:name=Options.TableName:default=MyTable} = "MyTable" |
| 28 | + /// |
| 29 | + /// Config Setting Lookup Cached: |
| 30 | + /// ${configsetting:cached=True:name=Mode} |
| 31 | + /// </example> |
| 32 | + [LayoutRenderer("configsetting")] |
| 33 | + public class ConfigSettingLayoutRenderer : LayoutRenderer |
| 34 | + { |
| 35 | + internal IConfigurationRoot _configurationRoot; |
| 36 | + |
| 37 | + private static readonly Dictionary<string, WeakReference<IConfigurationRoot>> _cachedConfigFiles = new Dictionary<string, WeakReference<IConfigurationRoot>>(); |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// Global Configuration Container. Used if <see cref="FileName" /> has default value |
| 41 | + /// </summary> |
| 42 | + public static IConfiguration DefaultConfiguration { get; set; } |
| 43 | + |
| 44 | + ///<summary> |
| 45 | + /// Name of the setting |
| 46 | + ///</summary> |
| 47 | + [RequiredParameter] |
| 48 | + [DefaultParameter] |
| 49 | + public string Name { get => _name; set => _name = value?.Replace(".", ":"); } |
| 50 | + private string _name; |
| 51 | + |
| 52 | + ///<summary> |
| 53 | + /// The default value to render if the setting value is null. |
| 54 | + ///</summary> |
| 55 | + public string Default { get; set; } |
| 56 | + |
| 57 | + /// <summary> |
| 58 | + /// Configuration FileName (Multiple filenames can be split using '|' pipe-character) |
| 59 | + /// </summary> |
| 60 | + /// <remarks>Relative paths are automatically prefixed with ${basedir}</remarks> |
| 61 | + public Layout FileName { get; set; } = DefaultFileName; |
| 62 | + private const string DefaultFileName = "appsettings.json|appsettings.${environment:variable=ASPNETCORE_ENVIRONMENT}.json"; |
| 63 | + |
| 64 | + /// <inheritdoc/> |
| 65 | + protected override void InitializeLayoutRenderer() |
| 66 | + { |
| 67 | + _configurationRoot = null; |
| 68 | + base.InitializeLayoutRenderer(); |
| 69 | + } |
| 70 | + |
| 71 | + /// <inheritdoc/> |
| 72 | + protected override void CloseLayoutRenderer() |
| 73 | + { |
| 74 | + _configurationRoot = null; |
| 75 | + base.CloseLayoutRenderer(); |
| 76 | + } |
| 77 | + |
| 78 | + /// <inheritdoc/> |
| 79 | + protected override void Append(StringBuilder builder, LogEventInfo logEvent) |
| 80 | + { |
| 81 | + if (string.IsNullOrEmpty(_name)) |
| 82 | + return; |
| 83 | + |
| 84 | + string value = null; |
| 85 | + var configurationRoot = TryGetConfigurationRoot(); |
| 86 | + if (configurationRoot != null) |
| 87 | + { |
| 88 | + value = configurationRoot[_name]; |
| 89 | + } |
| 90 | + |
| 91 | + builder.Append(value ?? Default); |
| 92 | + } |
| 93 | + |
| 94 | + private IConfiguration TryGetConfigurationRoot() |
| 95 | + { |
| 96 | + if (DefaultConfiguration != null) |
| 97 | + { |
| 98 | + var simpleLayout = FileName as SimpleLayout; |
| 99 | + if (simpleLayout == null || string.IsNullOrEmpty(simpleLayout.Text) || ReferenceEquals(simpleLayout.Text, DefaultFileName)) |
| 100 | + { |
| 101 | + if (_configurationRoot != null) |
| 102 | + _configurationRoot = null; |
| 103 | + return DefaultConfiguration; |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + if (_configurationRoot != null) |
| 108 | + return _configurationRoot; |
| 109 | + |
| 110 | + var fileNames = FileName?.Render(LogEventInfo.CreateNullEvent()); |
| 111 | + if (!string.IsNullOrEmpty(fileNames)) |
| 112 | + { |
| 113 | + return _configurationRoot = LoadFileConfiguration(fileNames); |
| 114 | + } |
| 115 | + |
| 116 | + return null; |
| 117 | + } |
| 118 | + |
| 119 | + private IConfigurationRoot LoadFileConfiguration(string fileNames) |
| 120 | + { |
| 121 | + lock (_cachedConfigFiles) |
| 122 | + { |
| 123 | + if (_cachedConfigFiles.TryGetValue(fileNames, out var wearkConfigRoot) && wearkConfigRoot.TryGetTarget(out var configRoot)) |
| 124 | + { |
| 125 | + return configRoot; |
| 126 | + } |
| 127 | + else |
| 128 | + { |
| 129 | + configRoot = BuildConfigurationRoot(fileNames); |
| 130 | + _cachedConfigFiles[fileNames] = new WeakReference<IConfigurationRoot>(configRoot); |
| 131 | + return configRoot; |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + private static IConfigurationRoot BuildConfigurationRoot(string fileNames) |
| 137 | + { |
| 138 | + var configBuilder = new ConfigurationBuilder(); |
| 139 | + string baseDir = null; |
| 140 | + foreach (var fileName in fileNames.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)) |
| 141 | + { |
| 142 | + var fullPath = fileName; |
| 143 | + if (!System.IO.Path.IsPathRooted(fullPath)) |
| 144 | + { |
| 145 | + if (baseDir == null) |
| 146 | + baseDir = new BaseDirLayoutRenderer().Render(LogEventInfo.CreateNullEvent()) ?? string.Empty; |
| 147 | + fullPath = System.IO.Path.Combine(baseDir, fileName); |
| 148 | + } |
| 149 | + |
| 150 | + AddFileConfiguration(configBuilder, fullPath); |
| 151 | + } |
| 152 | + |
| 153 | + return configBuilder.Build(); |
| 154 | + } |
| 155 | + |
| 156 | + private static void AddFileConfiguration(ConfigurationBuilder configBuilder, string fullPath) |
| 157 | + { |
| 158 | + if (System.IO.File.Exists(fullPath)) |
| 159 | + { |
| 160 | + // NOTE! Decided not to monitor for changes, as it would require access to dipose this monitoring again |
| 161 | + if (string.Equals(System.IO.Path.GetExtension(fullPath), ".json", StringComparison.OrdinalIgnoreCase)) |
| 162 | + { |
| 163 | + configBuilder.AddJsonFile(fullPath); |
| 164 | + } |
| 165 | + else if (string.Equals(System.IO.Path.GetExtension(fullPath), ".xml", StringComparison.OrdinalIgnoreCase)) |
| 166 | + { |
| 167 | + configBuilder.AddXmlFile(fullPath); |
| 168 | + } |
| 169 | + else if (string.Equals(System.IO.Path.GetExtension(fullPath), ".ini", StringComparison.OrdinalIgnoreCase)) |
| 170 | + { |
| 171 | + configBuilder.AddIniFile(fullPath); |
| 172 | + } |
| 173 | + else |
| 174 | + { |
| 175 | + Common.InternalLogger.Info("configSetting - Skipping FileName with unknown file-extension: {0}", fullPath); |
| 176 | + } |
| 177 | + } |
| 178 | + else |
| 179 | + { |
| 180 | + Common.InternalLogger.Info("configSetting - Skipping FileName as file doesnt't exists: {0}", fullPath); |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | +} |
0 commit comments