NLog does not create a log file
Asked Answered
P

15

55

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();
}
Photoneutron answered 11/5, 2012 at 11:50 Comment(5)
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.Ichthyoid
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.Photoneutron
Following the link you provided, i stumbled upon the solution. Thanks a lot.Photoneutron
I'm glad :) Then please post your solution as an answer for the later visitors.Ichthyoid
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-troubleshootingBoutonniere
P
23

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.

Photoneutron answered 11/5, 2012 at 12:18 Comment(4)
Hmm weird. This fixed it for me, but I have another application where this doesn't have to be specified (and the output still works)Chuffy
If you find out what was the reason, please do post it. I think it will be helpful to know what NLog log file placement can depend onPhotoneutron
That documentation is horrible. Can you put an example in your answer?Yelp
Look for another answer by Mauricio, who has graciously done that alreadyPhotoneutron
A
64

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)

Arise answered 14/4, 2017 at 21:42 Comment(2)
Thanks. The "Do Not Copy" setting was the problem.Objurgate
In my case, I am using Nlog in appsetings, Is it not able to create this copy? And I am with the same problem about "not creating .log file".Treasurer
P
23

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.

Photoneutron answered 11/5, 2012 at 12:18 Comment(4)
Hmm weird. This fixed it for me, but I have another application where this doesn't have to be specified (and the output still works)Chuffy
If you find out what was the reason, please do post it. I think it will be helpful to know what NLog log file placement can depend onPhotoneutron
That documentation is horrible. Can you put an example in your answer?Yelp
Look for another answer by Mauricio, who has graciously done that alreadyPhotoneutron
W
22

from nlog troubleshooting guide

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

enter image description here

Please view image link https://i.sstatic.net/AlUG5.png

Wisla answered 24/4, 2018 at 7:54 Comment(1)
thands,I forget to set nlog.config file copy always.I think nlog should throw exception if it can not find nlog.config file.Surveyor
P
17

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

Pellucid answered 10/5, 2013 at 15:36 Comment(0)
W
9

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://learn.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities

While answered 17/5, 2019 at 16:18 Comment(0)
M
6

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.

Meister answered 19/6, 2017 at 6:49 Comment(2)
the bolded text "the 'bin' directory" was key for me. I didn't realize it was in there. Must have missed the documentation. Thanks so much.Goggler
this was my problem also, I am doing ASP.NET and {$basedir} is <project_path>\bin\Debug\net5.0 (folder not shown in Rider Explorer view)Stomacher
H
4

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>
Heteroclite answered 22/12, 2017 at 11:18 Comment(1)
Late to the party but this answer was the solution for me.Naaman
U
1

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

Untune answered 7/7, 2021 at 17:27 Comment(0)
N
1

in my case, a WebAPI application, I solved the problem by giving modify permissions to IIS_IUSRS the modify permission for the website folder C:\inetpub\wwwroot\my_website

enter image description here

Noumenon answered 24/11, 2021 at 11:32 Comment(0)
M
1

My issue/solution was as embarrassing to finally figure out as it was vexing.

I tried all of the answers here, did a clean/rebuild and uninstalled/reinstalled NLog via NuGet. Nothing worked.

Turns out I had a perfectly valid NLog.config file, but had also somehow, accidentally, pasted an NLog config section info in my main App.Config file. Never thought to look there, but it was overriding anything else I did with NLog.

Monogenesis answered 5/4, 2023 at 1:11 Comment(0)
O
1

In my case I thought I had nlog.config in the root of my application, but it turns out it had been saved as nlog.config.txt and windows was hiding the extension.

On answered 2/7 at 13:16 Comment(0)
H
0

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.

Hotbox answered 16/8, 2018 at 8:11 Comment(0)
P
0

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.

Presentable answered 22/8, 2018 at 11:40 Comment(0)
U
0

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.

Ustulation answered 8/10, 2020 at 14:26 Comment(0)
B
0

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.

Blubberhead answered 13/9, 2021 at 11:37 Comment(2)
Can you create an issue at github.com/NLog/NLog/issues that demonstrates this issue (maybe by attaching an example project) ? NLog should automatically load NLog.configJessi
Make sure to check the properties of Nlog.config and ensure Copy to output directory is Copy if newer. See also github.com/NLog/NLog/wiki/Logging-troubleshootingJessi

© 2022 - 2024 — McMap. All rights reserved.