Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NLog 5.0.4 does not log exceptions

I have the following console application:

using NLog;

namespace ConsoleTest
{
    class Program
    {
        static Logger logger = null;
        static void Main()
        {
            string targetName = "logconsole";
            logger = LogManager.GetLogger(targetName);
            var _logLayout = "${message} | ${exception:format=tostring} #";
            var _config = new NLog.Config.LoggingConfiguration();
            var _logConsole = new NLog.Targets.ConsoleTarget(targetName) { Layout = _logLayout };
            _config.AddRule(LogLevel.Info, LogLevel.Fatal, _logConsole);

            NLog.LogManager.Configuration = _config;
            CauseException();
        }

        private static void CauseException()
        {
            try
            {
                string s = null;
                bool b = s.Contains('a');
            }
            catch (Exception exc)
            {
                //Console output: "123 | #"
                logger.Error("123", exc);
                Console.ReadLine();
            }            
        }
    }
}

I have included NLog 5.0.4 via NuGet. The logger output does not include any exception details at all, only the message "123" I passed directly to the logger. What I want is the exception details like message, stack trace etc. What am I doing wrong here?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You use the method Logger.Error<T>(string message, T argument). The exception is passed as a argument of the message format (like with String.Format).

To display a exception you need to use Logger.Error(Exception exception, string message) like :

catch (Exception exc)
{
    logger.Error(exc, "123");
    Console.ReadLine();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading