NLog for ASP.NET website doesn't log - c#

I created simple ASP.NET web-site, added NLog, but it doesn't create any log file, neither throws any exceptions. I tried troubleshoot, but it doesn't help https://github.com/NLog/NLog/wiki/Logging-troubleshooting
my web.config
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<nlog
xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwExceptions="true"
internalLogLevel="Off"
internalLogFile="c:\temp\nlog-internal.log">
<targets>
<target name="file" type="File" fileName="C:\log.txt" />
</targets>
<rules>
<logger name="File" minlevel="Trace" writeTo="file" />
<logger name="FileNotFound" minlevel="Trace" writeTo="file-404" />
</rules>
</nlog>
Then I run page below, and nothing happens...
public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LogManager.ThrowExceptions = true;
Logger logger = LogManager.GetLogger("foo");
Logger log = LogManager.GetCurrentClassLogger();
log.Error("some test");
logger.Error("some test 2");
}
}
What is my fault? Thank you!

The name attriute of the <logger> is a filter (on name)
So you filter now on the loggers with the name "File" and "FileNotFound"
This will write all to the file
<logger name="*" minlevel="Trace" writeTo="file" />
Another option is to use named loggers in C#, so instead of
Logger log = LogManager.GetCurrentClassLogger();
use
Logger log = LogManager.GetLogger("FileNotFound");
Then you could use <logger name="FileNotFound" ..> in your config

Likely that your output directory can't be written to by the IIS user. Try using an output directory relative to the website, like "logs".

Related

NLog logger doesn't log to the configured logfile in release build

I have the configuration file set up
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog autoReload="true">
<targets>
<target name="file" type="File" fileName="${basedir}/log/${shortdate}.log" layout="${date:format=HH\:mm\:ss.fff}|${message}"/>
<target name="file_webs" type="File" fileName="${basedir}/log/${shortdate}_webs.log" layout="${date:format=HH\:mm\:ss.fff}|${message}"/>
</targets>
<rules>
<logger name="WebSocket.*" minlevel="Debug" writeTo="file_webs" final="true"/>
<logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</nlog>
</configuration>
The logger is loaded in each class like this:
private static Logger logger = LogManager.GetCurrentClassLogger();
The logging is directed to the correct file as long as I don't run the build version. Then all logging is done in the default log file.
What could be the cause?
Check the following:
Is the correct config file placed in the output directory of the release. Maybe there is a different version of your config file there or it is missing.
Are there other things running after your build? Like a tool to obfuscate the source code? If so, this might mess up the class name in your build, the config the can not redirect to the right output. In that case, explicitly load the logger for your class this way:
private static Logger logger = LogManager.GetLogger("WebSocket.*");

NLog for asp.net core is not filtering Microsoft logs

I have the following nlog.config file in ASP.NET Core 2.1 project. However, it's logging messages from every logger (including Microsoft logger) to console.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Error"
internalLogFile="${specialfolder:folder=UserProfile}\nlog\internal-nlog.txt">
<variable name="fullLayout" value="${shortdate} [${uppercase:${level}}] ${logger}: ${message} ${exception:format=tostring} url: ${aspnet-request-url}" />
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write to console -->
<target name="console" xsi:type="ColoredConsole" layout="${fullLayout}" />
<!-- write to file -->
<target xsi:type="File"
name="allfile"
fileName="${defaultDirectory}/test-api-all.log"
archiveEvery="Day"
archiveFileName="${defaultDirectory}/test-api-all-${#}.log"
archiveNumbering="Date"
archiveDateFormat="yyyy-MM-dd"
maxArchiveFiles="5"
layout="${fullLayout}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File"
name="ownFile-web"
fileName="${defaultDirectory}/test-api-app.log"
archiveEvery="Day"
archiveFileName="${defaultDirectory}/test-api-app-${#}.log"
archiveNumbering="Date"
archiveDateFormat="yyyy-MM-dd"
maxArchiveFiles="5"
layout="${fullLayout}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="console" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxLevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
I do not have any logging settings in appsettings.json files. All logger configuration in in nlog.config. In the Program.cs, I'm registering NLog like:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging => logging.ClearProviders())
.UseNLog()
.Build();
How can I filter out Microsoft logs?
EDIT:
Above configuration started working without a problem the next day without me making any changes :O
Maybe this will work:
<!-- rules to map from logger name to target -->
<rules>
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxLevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="console" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
The order of the logging rules are important, as the rules are matched from the top. See also https://github.com/NLog/NLog/wiki/Configuration-file#rules
The order of your logging rules seems to be correct. I suggest trying to double check if your updated nlog.config file is being copied to the build directory (e.g. \bin\Debug\netcoreapp2.1\nlog.config)
I kind of encountered the same issue, but found out that debugging using Visual Studio, it sometimes doesn't really copy the nlog.config file to your build directory. So the solution is to Clean the project first, then Build, and finally Debug.

How to set debugEnabled/InfoEnabled in nlog.config

I have Logger of NLog package,
I want to define trace enable=true in my config logger file.
How can I do it?
My NLog.config file:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" maxlevel="Trace" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
You do this by setting the minLevel attribute in your rules section of the NLog.config like so;
<rules>
<logger name="*" minlevel="Debug" writeTo="CSVFile" />
</rules>
Debug will write out Debug, Info, Warn, Error and Fatal-level log messages. Only Trace is skipped.
EDIT
Conversely, if you wanted to only log Trace, then set the maxLevel like so;
<rules>
<logger name="*" maxlevel="Trace" writeTo="CSVFile" />
</rules>
To just log a specific intermediate level, use minLevel and maxLevel together like;
<rules>
<logger name="*" minlevel="Debug" maxlevel="Debug" writeTo="CSVFile" />
</rules>
EDIT2
I tweaked your config file such that the output logs to the console rather than the file;
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" maxlevel="Trace" writeTo="logconsole" />
</rules>
</nlog>
And when run in a test application where I'm writing out multiple logging levels like so;
_logger.Trace("trace text");
_logger.Debug("debug text");
_logger.Info("info text");
_logger.Warn("warn text");
_logger.Error("error text");
_logger.Fatal("fatal text");
And only the Trace text displays in the console window. One thing of note however, is that the XML in the config file must be correctly formatted. The sample above is working as described in my test application here.
You can create multiple levels of logging by creating multiple logger instaances such as
<rules>
<!-- add your logging rules here -->
<!-- different logger instances for different environments, no levels are mentioned explicitly, can be done if exclusion of some levels is required -->
<logger name="Log.Dev" minlevel="Debug" writeTo="database" enabled="true" />
<logger name="Log.Staging" minlevel="Info" writeTo="database" enabled="true" />
<logger name="Log.Production" minlevel="Error" writeTo="database" enabled="true" />
</rules>
After that while initializing give the name of the logger which you want to initialize
/// <summary>
/// The log.
/// Getting Logger instance from key name defined in Web.config of main web file. Key name is LoggerInstanceName
/// On the basis of name , logger instance and defined rules can be switched from one to another.
/// </summary>
private static readonly NLog.Logger Log = LogManager.GetLogger(Convert.ToString(ConfigurationManager.AppSettings.Get("LoggerInstance")));
Also do not forget to add key in your app settings
<appSettings>
<!--logger instance name-->
<add key="LoggerInstanceName" value="Log.Dev" />
</appSettings>

NLog 2.1 EventId for EventLog not working when not specified

I am using Nlog 2.1 and trying to write errors into Windows Event logger with different eventId. To better distinguish different errors.
If I specify eventId property it's working, but if don't I am not seeing any record in Windows Event Logger.
NLog.config file:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="console" xsi:type="ColoredConsole"
layout="${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message}" />
<target xsi:type="EventLog"
name="eventlog"
layout="{${newline}
"Logger": "${logger}",${newline}
"StackTrace": "${stacktrace}",${newline}
"Message": "${message}",${newline}
"Exception": "${exception:format=ToString,Data}"${newline}}"
machineName="."
source="CareFusion Analytics Agent Service"
eventId="${event-properties:EventID}"
log="Application" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="console" />
<logger name="*" minlevel="Error" writeTo="eventlog" />
</rules>
</nlog>
Usage:
private static void Main(string[] args)
{
Logger logger = LogManager.GetCurrentClassLogger();
logger.Error("Sample error message"); //This is not working
LogEventInfo logEvent = new LogEventInfo()
{
Level = LogLevel.Error,
Message = "Hello",
LoggerName = logger.Name
};
logEvent.Properties.Add("EventID", 400);
logger.Log(logEvent); //This is working
Console.WriteLine("Press any key....");
Console.ReadKey();
}
The call logger.Error("Sample error message"); goes wrong as the EventLogTarget tries to convert the ${event-properties:EventID} to a integer.
Because layout renders in NLog never return null (but string.Empty), this will give a exception - which will be caught by NLog. In the NLog's internal log you should see a FormatException.
So we need to specify a default value, you could do that with the whenEmpty:
<target xsi:type="EventLog"
...
eventId="${event-properties:EventID:whenEmpty=0}" />
PS: tested it with NLog 4.3.11

NLog in .NET 4.5 console app: not loading Configuration

I have some console apps I've written at work. I'd like to get NLog into them but I am having trouble.
When I inspect the 'logger' object, I see in it's 'Factory' property, that the configuration had targets=0, loggingrules=0, everything blank or unset.
So, it doesn't do ANYTHING.. doesn't drop an internal log file either... I have tried nLog.config NLog.config and nlog.config... to no avail. Tried ver 3 and 4 of NLog too...
Why would it not pick up the config?
I have:
NLog.config in the root with 'Content' for build action and 'Copy Always' set
Confirmed the NLog.config IS being copied to the bin
Here's the NLog.config:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwConfigExceptions="true"
throwExceptions="true"
internalLogLevel="Trace"
internalLogFile="c:\temp\NlogInternal.log"
internalLogToConsole="true"
internalLogToConsoleError="true"
internalLogToTrace="true">
<targets>
<target xsi:type="Console" name="debugConsole" layout="${message} "/>
<target xsi:type="File" name="debugFile" createDirs="true" fileName="c:\temp\testlog.log" layout="${longdate} ${uppercase:${level}} ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugConsole"/>
<logger name="*" minlevel="Trace" writeTo="debugFile"/>
</rules>
</nlog>
and finally (this doesn't error, but nothing is output since the config is blank):
private static Logger logger = LogManager.GetCurrentClassLogger();
logger.Info("ConsoleApp test log...");
Do your app.config have a NLog configSection?
Something like this:
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog>
</nlog>
</configuration>
If even the internalLogger isn't working, you could debug the issue by setting
the InternalLogger.LogWriter
e.g.
// enable internal logging to a custom TextWriter
InternalLogger.LogWriter = new StringWriter(); //e.g. TextWriter writer = File.CreateText("C:\\perl.txt")
I got the same issue on my end. When you make change your fileName Path "c:\temp\testlog.log" to
"c:/temp/testlog.log" then it will work. Hope the below snipet help you to resolve the issue.
<targets>
<target xsi:type="Console" name="debugConsole" layout="${message} "/>
<target xsi:type="File" name="debugFile" createDirs="true"
fileName="c:/temp/testlog.log" layout="${longdate} ${uppercase:${level}}
${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugConsole"/>
<logger name="*" minlevel="Trace" writeTo="debugFile"/>
</rules>

Categories

Resources