Search code examples
visual-c++utf-8nlogbyte-order-mark

How to configure NLog to save to a UTF8+BOM file?


This is how my logging is configured:

private static void SetupLogging(string logFile)
{
    var Config = new NLog.Config.LoggingConfiguration();
    var logfile = new NLog.Targets.FileTarget("logfile")
    {
        FileName = logFile,
        Layout = "${longdate}|${level:uppercase=true}|${logger}|${message:withException=true:exceptionSeparator=|}"
    };
    var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

    Config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
    Config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

    LogManager.Configuration = Config;
}

But, any error log file created is UTF8 encoded and not UTF8 + BOM. I realise that the need of the BOM is not necessary but I have some other classes that I use that rely on the BOM being present (CTextFileDocument) library.


Solution

  • The FileTarget has a WriteBom property for this purpose:

    Gets or sets a value indicating whether to write BOM (byte order mark) in created files. Defaults to true for UTF-16 and UTF-32

    private static void SetupLogging(string logFile)
    {
        var Config = new NLog.Config.LoggingConfiguration();
        var logfile = new NLog.Targets.FileTarget("logfile")
        {
            FileName = logFile,
            WriteBom = true,
            Layout = "${longdate}|${level:uppercase=true}|${logger}|${message:withException=true:exceptionSeparator=|}"
        };
        var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
    
        Config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
        Config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
    
        LogManager.Configuration = Config;
    }