I have implemented log4net
into .NET core 2.0
, to log into a text file. As log4net have a config file, which is having XML configuration
i
Maybe it is not the right way but, anyhow I managed to use my log4net.config
in appSettings.json
. I am putting my answer here so it can help someone if they don't want to use an extra config file for there project.
So what I have done is like by converting my XML into JSON and used the JSON as a string on my appSettings.json
after that I use the following code to read the string.
appSettings.json
{
"ConnectionStrings": {
"LoggerConfig": "Config string"
}
}
Json to XML Conversion using
Newtonsoft.Json
string xmlElement = _configuration["ConnectionStrings:LoggerConfig"];
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(xmlElement);
XmlConfigurator.Configure(logRepository, GenerateStreamFromString(doc.InnerXml));
This code is used to convert the JSON into XML but it will not provide the XML content as Element so, I used it as a stream. For converting the string into a stream I used the following code.
public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
and it works fine.
Here I used to convert first my
XML to JSON
and againJSON to XML
to use it as alog4net config
, but if anyone wants then use XML directly as a string, So it will reduce some code.