Skip to content

Commit

Permalink
Store any serilog config in app.config and web.config files
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasArdal committed Nov 20, 2024
1 parent c2b0c95 commit 8603700
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/Serilog.Sinks.ElmahIo/Sinks/ElmahIo/ElmahIOSink.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Elmah.Io.Client;
using Newtonsoft.Json.Linq;
using Serilog.Events;
Expand Down Expand Up @@ -419,6 +420,55 @@ internal void CreateInstallation()
}
}

var appConfigPath = Path.Combine(currentDirectory, "App.config");
var webConfigPath = Path.Combine(currentDirectory, "Web.config");

string configPath = null;

if (File.Exists(appConfigPath)) configPath = appConfigPath;
else if (File.Exists(webConfigPath)) configPath = webConfigPath;

if (configPath != null)
{
var configXml = XDocument.Load(configPath);

var outputXml = new XDocument(
new XElement("configuration",
new XElement("appSettings")
)
);

var appSettings = configXml.Descendants("appSettings").FirstOrDefault();
if (appSettings != null)
{
foreach (var setting in appSettings.Elements("add"))
{
var key = setting.Attribute("key")?.Value;
var value = setting.Attribute("value")?.Value;

if (!string.IsNullOrEmpty(key) && key.StartsWith("serilog:", StringComparison.OrdinalIgnoreCase))
{
outputXml.Root.Element("appSettings")?.Add(
new XElement("add",
new XAttribute("key", key),
new XAttribute("value", value ?? string.Empty)
)
);
}
}
}

if (outputXml.Root.Element("appSettings")?.HasElements == true)
{
logger.ConfigFiles.Add(new ConfigFile
{
Name = Path.GetFileName(configPath),
Content = outputXml.ToString(),
ContentType = "text/xml"
});
}
}

EnsureClient();

_client.Installations.Create(_options.LogId.ToString(), installation);
Expand Down

0 comments on commit 8603700

Please sign in to comment.