Skip to content

Commit 6358ae4

Browse files
authored
Support custom config file paths (#3)
* Support custom config file paths * AppVeyor build still failiing; trying working dir to locate config file... * Add missing config file :-)
1 parent c60a347 commit 6358ae4

File tree

6 files changed

+59
-48
lines changed

6 files changed

+59
-48
lines changed

src/Serilog.Settings.AppSettings/AppSettingsLoggerConfigurationExtensions.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,11 @@ public static class AppSettingsLoggerConfigurationExtensions
3535
/// <param name="settingPrefix">Prefix to use when reading keys in appSettings. If specified the value
3636
/// will be prepended to the setting keys and followed by :, for example "myapp" will use "myapp:serilog:minumum-level. If null
3737
/// no prefix is applied.</param>
38+
/// <param name="filePath">Specify the path to an alternative .config file location. If the file does not exist it will be ignored.
39+
/// By default, the current application's configuration file will be used.</param>
3840
/// <returns>An object allowing configuration to continue.</returns>
3941
public static LoggerConfiguration AppSettings(
40-
this LoggerSettingsConfiguration settingConfiguration, string settingPrefix = null)
42+
this LoggerSettingsConfiguration settingConfiguration, string settingPrefix = null, string filePath = null)
4143
{
4244
if (settingConfiguration == null) throw new ArgumentNullException(nameof(settingConfiguration));
4345
if (settingPrefix != null)
@@ -47,7 +49,7 @@ public static LoggerConfiguration AppSettings(
4749
if (string.IsNullOrWhiteSpace(settingPrefix)) throw new ArgumentException("To use the default setting prefix, do not supply the settingPrefix parameter, instead pass the default null.");
4850
}
4951

50-
return settingConfiguration.Settings(new AppSettingsSettings(settingPrefix));
52+
return settingConfiguration.Settings(new AppSettingsSettings(settingPrefix, filePath));
5153
}
5254
}
5355
}

src/Serilog.Settings.AppSettings/Settings/AppSettings/AppSettingsSettings.cs

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,31 +13,57 @@
1313
// limitations under the License.
1414

1515
using System;
16+
using System.Collections.Generic;
1617
using System.Configuration;
18+
using System.IO;
1719
using System.Linq;
1820
using Serilog.Configuration;
19-
using Serilog.Settings.KeyValuePairs;
21+
using Serilog.Debugging;
2022

2123
namespace Serilog.Settings.AppSettings
2224
{
2325
class AppSettingsSettings : ILoggerSettings
2426
{
27+
readonly string _filePath;
2528
readonly string _settingPrefix;
2629

27-
public AppSettingsSettings(string settingPrefix = null)
30+
public AppSettingsSettings(string settingPrefix = null, string filePath = null)
2831
{
32+
_filePath = filePath;
2933
_settingPrefix = settingPrefix == null ? "serilog:" : $"{settingPrefix}:serilog:";
3034
}
3135

3236
public void Configure(LoggerConfiguration loggerConfiguration)
3337
{
3438
if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));
3539

36-
var settings = ConfigurationManager.AppSettings;
40+
IEnumerable<KeyValuePair<string, string>> settings;
3741

38-
var pairs = settings.AllKeys
39-
.Where(k => k.StartsWith(_settingPrefix))
40-
.ToDictionary(k => k.Substring(_settingPrefix.Length), k => Environment.ExpandEnvironmentVariables(settings[k]));
42+
if (!string.IsNullOrWhiteSpace(_filePath))
43+
{
44+
if (!File.Exists(_filePath))
45+
{
46+
SelfLog.WriteLine("The specified configuration file `{0}` does not exist and will be ignored.", _filePath);
47+
return;
48+
}
49+
50+
var map = new ExeConfigurationFileMap {ExeConfigFilename = _filePath};
51+
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
52+
settings = config.AppSettings.Settings
53+
.Cast<KeyValueConfigurationElement>()
54+
.Select(k => new KeyValuePair<string, string>(k.Key, k.Value));
55+
}
56+
else
57+
{
58+
settings = ConfigurationManager.AppSettings.AllKeys
59+
.Select(k => new KeyValuePair<string, string>(k, ConfigurationManager.AppSettings[k]));
60+
}
61+
62+
var pairs = settings
63+
.Where(k => k.Key.StartsWith(_settingPrefix))
64+
.Select(k => new KeyValuePair<string, string>(
65+
k.Key.Substring(_settingPrefix.Length),
66+
Environment.ExpandEnvironmentVariables(k.Value)));
4167

4268
loggerConfiguration.ReadFrom.KeyValuePairs(pairs);
4369
}

src/Serilog.Settings.AppSettings/project.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"version": "2.0.1-*",
2+
"version": "2.1.0-*",
33
"description": "XML configuration (System.Configuration <appSettings>) support for Serilog.",
44
"authors": [ "Serilog Contributors" ],
55
"packOptions": {

test/Serilog.Settings.AppSettings.Tests/Settings/AppSettingsTests.cs

Lines changed: 21 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using System;
2-
using System.Configuration;
32
using System.IO;
43
using Xunit;
54
using Serilog.Events;
@@ -10,25 +9,28 @@ namespace Serilog.Tests.AppSettings.Tests
109
{
1110
public class AppSettingsTests
1211
{
13-
static AppSettingsTests()
12+
static string GetConfigPath()
1413
{
14+
const string testsConfig = "tests.config";
15+
if (File.Exists(testsConfig))
16+
return Path.GetFullPath(testsConfig);
1517
var basePath = AppDomain.CurrentDomain.BaseDirectory;
16-
var config = Path.GetFullPath(Path.Combine(basePath, "app.config"));
17-
if (!File.Exists(config))
18-
throw new InvalidOperationException($"Can't find app.config in {basePath}");
18+
return Path.GetFullPath(Path.Combine(basePath, testsConfig));
19+
}
1920

20-
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", config);
21+
[Fact]
22+
public void TheTestConfigFileExists()
23+
{
24+
var config= GetConfigPath();
25+
Assert.True(File.Exists(config), "Can't find the test configuration file");
2126
}
2227

2328
[Fact]
2429
public void EnvironmentVariableExpansionIsApplied()
2530
{
26-
// Make sure we have the expected key in the App.config
27-
Assert.Equal("%PATH%", ConfigurationManager.AppSettings["serilog:enrich:with-property:Path"]);
28-
2931
LogEvent evt = null;
3032
var log = new LoggerConfiguration()
31-
.ReadFrom.AppSettings()
33+
.ReadFrom.AppSettings(filePath: GetConfigPath())
3234
.WriteTo.Sink(new DelegatingSink(e => evt = e))
3335
.CreateLogger();
3436

@@ -45,18 +47,14 @@ public void CanUseCustomPrefixToConfigureSettings()
4547
const string prefix1 = "custom1";
4648
const string prefix2 = "custom2";
4749

48-
// Make sure we have the expected keys in the App.config
49-
Assert.Equal("Warning", ConfigurationManager.AppSettings[prefix1 + ":serilog:minimum-level"]);
50-
Assert.Equal("Error", ConfigurationManager.AppSettings[prefix2 + ":serilog:minimum-level"]);
51-
5250
var log1 = new LoggerConfiguration()
5351
.WriteTo.Observers(o => { })
54-
.ReadFrom.AppSettings(prefix1)
52+
.ReadFrom.AppSettings(prefix1, filePath: GetConfigPath())
5553
.CreateLogger();
5654

5755
var log2 = new LoggerConfiguration()
5856
.WriteTo.Observers(o => { })
59-
.ReadFrom.AppSettings(prefix2)
57+
.ReadFrom.AppSettings(prefix2, filePath: GetConfigPath())
6058
.CreateLogger();
6159

6260
Assert.False(log1.IsEnabled(LogEventLevel.Information));
@@ -70,25 +68,22 @@ public void CanUseCustomPrefixToConfigureSettings()
7068
public void CustomPrefixCannotContainColon()
7169
{
7270
Assert.Throws<ArgumentException>(() =>
73-
new LoggerConfiguration().ReadFrom.AppSettings("custom1:custom2"));
71+
new LoggerConfiguration().ReadFrom.AppSettings("custom1:custom2", filePath: GetConfigPath()));
7472
}
7573

7674
[Fact]
7775
public void CustomPrefixCannotBeSerilog()
7876
{
7977
Assert.Throws<ArgumentException>(() =>
80-
new LoggerConfiguration().ReadFrom.AppSettings("serilog"));
78+
new LoggerConfiguration().ReadFrom.AppSettings("serilog", filePath: GetConfigPath()));
8179
}
8280

8381
[Fact]
8482
public void ThreadIdEnricherIsApplied()
8583
{
86-
// Make sure we have the expected key in the App.config
87-
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:WithThreadId"]);
88-
8984
LogEvent evt = null;
9085
var log = new LoggerConfiguration()
91-
.ReadFrom.AppSettings()
86+
.ReadFrom.AppSettings(filePath: GetConfigPath())
9287
.WriteTo.Sink(new DelegatingSink(e => evt = e))
9388
.CreateLogger();
9489

@@ -102,12 +97,9 @@ public void ThreadIdEnricherIsApplied()
10297
[Fact]
10398
public void MachineNameEnricherIsApplied()
10499
{
105-
// Make sure we have the expected key in the App.config
106-
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:WithMachineName"]);
107-
108100
LogEvent evt = null;
109101
var log = new LoggerConfiguration()
110-
.ReadFrom.AppSettings()
102+
.ReadFrom.AppSettings(filePath: GetConfigPath())
111103
.WriteTo.Sink(new DelegatingSink(e => evt = e))
112104
.CreateLogger();
113105

@@ -121,12 +113,9 @@ public void MachineNameEnricherIsApplied()
121113
[Fact]
122114
public void EnrivonmentUserNameEnricherIsApplied()
123115
{
124-
// Make sure we have the expected key in the App.config
125-
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:WithEnvironmentUserName"]);
126-
127116
LogEvent evt = null;
128117
var log = new LoggerConfiguration()
129-
.ReadFrom.AppSettings()
118+
.ReadFrom.AppSettings(filePath: GetConfigPath())
130119
.WriteTo.Sink(new DelegatingSink(e => evt = e))
131120
.CreateLogger();
132121

@@ -140,12 +129,9 @@ public void EnrivonmentUserNameEnricherIsApplied()
140129
[Fact]
141130
public void ProcessIdEnricherIsApplied()
142131
{
143-
// Make sure we have the expected key in the App.config
144-
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:WithProcessId"]);
145-
146132
LogEvent evt = null;
147133
var log = new LoggerConfiguration()
148-
.ReadFrom.AppSettings()
134+
.ReadFrom.AppSettings(filePath: GetConfigPath())
149135
.WriteTo.Sink(new DelegatingSink(e => evt = e))
150136
.CreateLogger();
151137

@@ -159,12 +145,9 @@ public void ProcessIdEnricherIsApplied()
159145
[Fact]
160146
public void LogContextEnricherIsApplied()
161147
{
162-
// Make sure we have the expected key in the App.config
163-
Assert.NotNull(ConfigurationManager.AppSettings["serilog:enrich:FromLogContext"]);
164-
165148
LogEvent evt = null;
166149
var log = new LoggerConfiguration()
167-
.ReadFrom.AppSettings()
150+
.ReadFrom.AppSettings(filePath: GetConfigPath())
168151
.WriteTo.Sink(new DelegatingSink(e => evt = e))
169152
.CreateLogger();
170153

test/Serilog.Settings.AppSettings.Tests/project.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"buildOptions": {
99
"keyFile": "../../assets/Serilog.snk",
1010
"preserveCompilationContext": true,
11-
"copyToOutput": [ "app.config" ]
11+
"copyToOutput": [ "tests.config" ]
1212
},
1313
"frameworks": {
1414
"net4.5.2": {

0 commit comments

Comments
 (0)