44
votes

I am trying to add logging to an application running on mobile device with Windows Mobile 6.1. � .NET Compact framework 3.5. using NLog.

I have the appropriate version of the NLog distribution installed.

However no log files are being created.

Here is 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=".\Neolant.ASRM.Terminal.log" layout="${longdate}|${level}|${message}|${exception}" autoFlush="true"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Info" writeTo="logfile" />
  </rules>
</nlog>

And here is the test code I was using:

public static void Main()
{
    try
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
        var logger = NLog.LogManager.GetLogger("UpperLevel");
        logger.Info("test test test.");
        try
        {
            throw new Exception("Unexpected!");
        }
        catch (Exception e)
        {
            var logger = NLog.LogManager.GetLogger("UpperLevel");
            logger.WarnException("An exception occured.", e);
        }
        throw new Exception("Suddenly!");           
    }
    finally
    {
        NLog.LogManager.Flush();
    }
}

private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
    var logger = NLog.LogManager.GetLogger("UpperLevel");
    logger.FatalException("Application closed due to exception.", unhandledExceptionEventArgs.ExceptionObject as Exception);
    NLog.LogManager.Flush();
}
12
Have you experimented with different file name/paths? E.g fileName="Neolant.ASRM.Terminal.log" without `.\` ? The Nlog.Config is in the app directory? Additionally you can turn on the Nlog's internal logging to get additional info about your problem. - nemesv
I hace tried filename with and without '.\' with similar (that is to say, without) results. NLog.config is deployed into the application directory. Will try internal logging now. - Srv19
Following the link you provided, i stumbled upon the solution. Thanks a lot. - Srv19
I'm glad :) Then please post your solution as an answer for the later visitors. - nemesv
Here's the updated link to troubleshooting NLog issues, for those of us who have come here via a Google search... github.com/NLog/NLog/wiki/Logging-troubleshooting - SWalters

12 Answers

50
votes

I had this problem turned out that my log file was not being copied to my build directory. The NLog github page had the answer. (I've reformatted the paragraph a little for better readability.) https://github.com/NLog/NLog/wiki/Logging-troubleshooting

NLog cannot find the configuration file. This can happen when the NLog.config file is configured with Build Action = None or Copy to Output Directory = Do not copy in Visual Studio.

Set Build Action = Content and "Copy to Output Directory = Copy if newer to fix this)

23
votes

The log file was being created - but not in the application directory.

Using ${basedir} layout renderer as part of the file name proved to be a solution.

16
votes

In case the response marked as answer is not all that clear you can check the example

<targets>
  <target xsi:type="Console" name="console" 
    layout="${longdate}|${level}|${message}" />
  <target xsi:type="File" name="ErrorLog" fileName="${basedir}/error.txt"
          layout="${longdate}
          Trace: ${stacktrace} 
          ${message}" />
  <target xsi:type="File" name="AccessLog" fileName="${basedir}/access.txt"
          layout="${shortdate} | ${message}" />
</targets>

Taken from here using AppData location in NLog

14
votes

from nlog troubleshooting guide

Please check Nlog.config file properties: Copy to output directory should be Copy always

Please view image link https://i.stack.imgur.com/AlUG5.png

5
votes

From the nlog troubleshooting guide:

https://github.com/NLog/NLog/wiki/Logging-troubleshooting

If you know that your config file is definitely being found, temporarily replace the section of your NLog.config file with the following and try it.

This rule will match any logger you've created, and if it works, it will put a log.txt file in the 'base directory' - which is the 'bin' directory for your test instance e.g. if you're running in debug mode, you'll see log.txt in your bin > debug folder. (This isn't explained very clearly in the troubleshooting guide).

If this works then you know that the problem is with your rules:

<nlog throwExceptions="true">
  <targets>
    <target name="file" type="File" fileName="${basedir}/log.txt" />
  </targets>
  <rules>
    <logger name="*" minLevel="Trace" writeTo="file" />
  </rules>
</nlog>

I found that only name="file" worked for the target - other values didn't

Adding the throwExceptions="true" as above will also ensure that you get useful error messages when you're debugging.

4
votes

My issue was permission related, the log file needs to allow the process to write to it, without write permissions you'll get no file.

Here's how to fix it for websites in IIS:

  1. Right click on your folder in windows explorer and select properties
  2. Choose the security tab
  3. Click edit
  4. Click add
  5. In the textbox type 'IIS AppPool\YourAppPoolName' replace YourAppPoolName with the actual name of the application pool your site runs under
  6. Click Check names
  7. Click OK

Security footnote: From a security aspect the best practice is to use ApplicationPoolIdentity as it is a dynamically created, unprivileged account. more reading here: https://docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities

3
votes

In my case, I've missed the rules after defining the rules works like a charm

 <rules>
    <logger name="*" minlevel="Trace" writeTo="logfile" />
    <!-- add your logging rules here -->

    <!--
    Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace)  to "f"
    <logger name="*" minlevel="Debug" writeTo="f" />
    -->
  </rules>
1
votes

Spent a lot of time on this issue. This was my problem. I was using a Setup project to install a Windows Service with an MSI. I had to manually add NLog.config to the output of the installer to make sure it got copied to the install directory of the service

0
votes

I also faced the same issue, finally i have solved it. I had a web application, where i want to implement NLog. Please find the following steps to implement NLog.

Step 1:- Go to NuGet packages manager and install following packages. enter image description here

Step 2:- Open Web.config and add those following line

<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"
  xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
  autoReload="true"
  throwExceptions="false"
  internalLogLevel="Off" internalLogFile="D:\projects\NlogWeb\nlog-internal.log">
<targets>
  <target name="console" xsi:type="ColoredConsole" layout="${message}" />
  <!--Write logs to File-->
  <target name="file" xsi:type="File" fileName="D:\projects\NlogWeb\ErrorLogFile.log" layout="--------------------- ${level}(${longdate})${machinename}-------------------- ${newline}
Exception Type:${exception:format=Type}${newline} 
Exception Message:${exception:format=Message}${newline}  
Stack Trace:${exception:format=Stack Trace}${newline}  
Additional Info:${message}${newline}" >
</target>  
</targets>   
<rules>

  <logger name="*" minlevel="trace" writeTo="file" />
</rules>
</nlog>

Step 3:- Now the last configuration to call in your .cs file.

using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NlogWeb
{
public partial class Home : System.Web.UI.Page
{
    private static Logger logger = LogManager.GetCurrentClassLogger();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            throw new Exception("Divide By Zero Exception", new DivideByZeroException());
        }
        catch (Exception ex)
        {                 
            logger.Error(ex.Message);
        }
    }
  }
}

We have done. Now execute your code and enjoy logging.

0
votes

To fix this, I had to run my application in administrator mode. I suspect windows had an update that suddenly prevented exe's from creating a (log) file, since the exe could always prevously log without admin rights.

0
votes

In my case I had to load the NLog.config file manually in the code since it wasn't found automatically. Loading the configuration must be done before logs are generated.

LogManager.LoadConfiguration(@"D:\doe\ConsoleApp2\ConsoleApp2\NLog.config");

After that I got log files and console output.

-1
votes

for simple troubleshooting purposes, launch VisualStudio to run as administrator. This will help to sort out permissions to create log files while debugging.

Also use createDirs=true in each of the target section to automatically create missing folders in the file path provided in target section.