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?
CodePudding user response:
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();
}
See also: https://github.com/NLog/NLog/wiki/How-to-log-exceptions