I’m working on an ASP.NET Web API project and I have two related issues with logging using NLog that I’m hoping to get help with.
Log Specific Messages Only:
I want to configure NLog so that it only logs the specific messages that I write. Currently, it seems to log everything, including framework-level logs. How can I set up NLog to log only the messages that I explicitly write in my code?
Here is my current 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 xsi:type="File" name="logfile" fileName="file.txt" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
Logs Not Showing When Installed on IIS:
I have a BackgroundService that runs periodically based on a timer every 30 seconds. When I run the project in Visual Studio, it works correctly, and the logs are written as expected. However, when I install the Web API on IIS, the BackgroundService does not seem to start until the API is requested, and the logs are not generated. How can I ensure that the BackgroundService starts immediately and logs are written when the Web API is deployed on IIS?
What changes do I need to make to achieve these two goals?
When I run the project in Visual Studio, it works correctly, and the logs are written as expected. However, when I install the Web API on IIS, the BackgroundService does not seem to start until the API is requested, and the logs are not generated.
Omar Ababneh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
If using NLog v5 then you can use finalMinLevel
to suppress a noisy logger:
<?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 xsi:type="File" name="logfile" fileName="file.txt" />
</targets>
<rules>
<logger name="System.*" finalMinLevel="Warn" />
<logger name="Microsoft.*" finalMinLevel="Warn" />
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
See also: https://github.com/NLog/NLog/wiki/Logging-Rules-FinalMinLevel