I have a C# .NET 6.0 Winform Desktop Application that uses NLog to log to both a text file and to a RichTextBox, and it's working perfectly.
I am also able to create a single file executable of said desktop application with one exception. The NLog.config file is not embedded in the executable file, it ends up being placed in the Publish Target Location, along with the executable file. I'm at a loss as to why this is happening as I do not what the end users to be able to end the config file for NLog because they will, Murphy's Law, corrupt it, delete it, or change it and logging will end up broken. I've searched Stackoverflow and googled my fingers off and can not find anything definitive on how to specifically set it so that the config file is embedded.
Using C# in Visual Studio 2022, Latest Build NLog 5.0.4
Make sure that the Build Action of your NLog.config
file ìs set to Embedded Resource
.
You'll notice below entry in your .csproj
file.
<ItemGroup>
<EmbeddedResource Include="NLog.config" />
</ItemGroup>
You'll have to configure the LogManager
manually.
Read the content of that embedded file; make sure that the namespace and casing of the resource/file name matches exactly.
Load that xml into an XmlLoggingConfiguration
and assign it to the Configuration
property of the LogManager
.
Below code makes use of the NLog.config
file from GitHub.
static void Main()
{
var stream = typeof(Program).Assembly.GetManifestResourceStream("YourNamespace.NLog.config");
string xml;
using (var reader = new StreamReader(stream))
{
xml = reader.ReadToEnd();
}
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(xml);
var logger = LogManager.GetCurrentClassLogger();
logger.Info("Hello world!");
}