Why is my NLog configuration not working on my server machine? - c#

I am using ServiceStack framework and NLog to do my logging. I can do logging on my local machine just fine. However on the server, it doesn't. I have checked that the Nlog.config is in the bin directory and the whole directory, including the directory above the bin directory has write access.
Below is a snippet of the config file:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets async="true">
<target xsi:type="File" name="file" fileName="${basedir}\logs\${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" />
<target xsi:type="Debugger" name="debug"
header="===== ${date:format=ddd, dd MMM yyyy} ${time} ====="
layout="${level} | ${logger} | ${message} | ${onexception:${exception:format=tostring} | ${stacktrace}}"
footer="===== end of session ===== ${newline}"
/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file,debug" />
</rules>
</nlog>
What might be the problem?

Have you tried to change the path to something you know?
Instead of fileName="${basedir}\logs\${shortdate}.log" to something like fileName="c:\logs\${shortdate}.log"?
The basedir variable of NLog in web applications don't run inside the bin folder. I think you will find the log files inside
%SystemRoot%\Microsoft.NET\Framework\versionNumber\Temporary ASP.NET Files
If it's a ASP.NET app.

While I do not know specifically what is wrong with your server environment and config I have always found it helpful to check the following:
Make sure you know exactly what the directory for the logs is (as suggested by #PauloCorreia).
Make sure that directory actually exists.
Make sure that the IIS worker process has the correct privileges to be able to write to that directory.
FWIW, it is usually a permissions issue in my experience.

Related

having an issue saving NLog file to basefolder

I'm having a hard time understanding why ${basedir} does nothing to the current directory of the project and when I change it to the explicit path it does saves the log.
I tried to change the name of ${basedir} to ${currentdir} but it did nothing.
This one works
<target xsi:type="File" name="myAppLoggerTarget" fileName="C:\Users\Omer\Desktop\DBBalancers\Logs\${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
This one works
<target xsi:type="File" name="myAppLoggerTarget" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
Link to nlog docs suggests: "The current application domain's base directory."
I would try to print out the: "AppDomain.CurrentDomain.BaseDirectory" and see whats the value of that variable.
On the same nlog docs page you can also find about process dir:
processDir - Introduced in NLog 4.4.2. Render the base directory of the current process? Default false.

Make NLog log even when testing with UnitTests c#

As the title says, I want my Logger to not be ignored when running unit tests using XUnit. I want it still to log. If this is possible, how can it be done?
Here is my 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">
<targets>
<target name="log"
xsi:type="File"
fileName="${basedir}/logs/log.${longdate:cached=true}.log"
layout="${message}"
archiveFileName="${basedir}/logs/archives/log.${shortdate}.{#}.log"
archiveAboveSize="5242880"
archiveEvery="Day"
archiveNumbering = "Rolling"
maxArchiveFiles="20"
/>
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logconsole" />
<logger name="*" minlevel="trace" writeTo="log" />
</rules>
</nlog>
I just have a backend and no frontend, so when I run the tests I want to see that everything logs :)
You could use NLog in unit tests. Unfortunately it's difficult for NLog to find the path to the nlog.config as unit test frameworks move the binaries between folders - and not the nlog.config.
Also it's different in different environments/frameworks (NUnit, xUnit, MSTest, .NET full, .NET Core)
You could do:
Write the configuration in C#. See Docs
Or tell NLog the path to the config:
LogManager.Configuration = new XmlLoggingConfiguration("pathToNLogConfig/nlog.config");
Also recommend for logging in unit tests, write to the memory target instead of file/database etc. You could also retrieve in code the logged events. See memory target docs

How to use NLog in Xamarin Android

I want to use NLog in my Xamarin.Droid project. I installed NLog.Config and dependencies and move NLog.config and NLog.xsd manually to Assets folder and change NLog.config build action to AndroidAsset.
As you can see in Load automatically NLog.config from Assets folder I guess there is no problem to put NLog.config into Assets folder.
After that I change NLog.config like below
<targets>
<target name="console" xsi:type="Console" layout="${longdate} ${callsite} ${level} ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="console" />
</rules>
After that I write some code like below for write some log in Console
ILogger logger = LogManager.GetCurrentClassLogger();
for (int c = 0; c < 1000; ++c)
logger.Debug("Hi there");
But after that I could not see any my messages in Android Device Logging or Output tab when "Show output from" set to Debug.
Do I look to the right places?
Your config says minlevel info:
<logger name="*" minlevel="Info" writeTo="console" />
but your are writing debug level. Which is below info.
logger.Debug("Hi there");
So change your logger rule to: (level name & attribute names are case insensitive)
<logger name="*" minlevel="debug" writeTo="console" />
NLog v5 no longer automatically scans for NLog.config in the Androids Assets-folder.
Either perform explicit loading of the NLog.config from the Assets-folder, or consider embedding the NLog.config as Assembly-Ressource:
NLog.LogManager.Setup().LoadConfigurationFromAssemblyResource(typeof(App).GetTypeInfo().Assembly);
See also: https://github.com/NLog/NLog/wiki/Explicit-NLog-configuration-loading
Notice NLog.Targets.MauiLog can also be used for platform specific output:
Android - Android.Util.Log / LogCat
Apple iOS / MacOS - Unified Logging OSLog (replacement of print and NSLog)

XAML access user directory [duplicate]

My NLog targets is like this:
<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>
But this causes problems if the user isn't an admin on their machine, because they will not have write access to "Program Files". How can I get something like %AppData% to NLog instead of BaseDir?
You're looking for the NLog special folders.
Example:
...fileName="${specialfolder:folder=ApplicationData}/Program/file.txt"...
Oren's answer should be the right answer. However, for the life of me I couldn't get it to work with my .NET 4.0 website using nLog 2.0.0.0. I ended up using simply
fileName="${basedir}app_data\logs\${shortdate}.log"
${specialfolder:ApplicationData} also works
The previous answers helped solve the problem I was having, but a couple of years later and the solution is now somewhat different under v4.3. The directory and filename are combined with the path.
#theGecko's link is still current for the syntax, but the page is deficient of an example:
https://github.com/nlog/NLog/wiki/Special-Folder-Layout-Renderer
The following example would write the file myLog.log to the current users application data roaming directory C:\USers\current.user\AppData\Roaming\My\Path\Somewhere:
fileName="${specialfolder:dir=My/Path/Somewhere/:file=myFile.log:folder=ApplicationData}"
For logging to the project directory:
While the previous answers work for the original question, searching for how to log to the project APP_DATA directory leads to this question. And while bkaid's answer works for ASP.NET and for using the APP_DATA folder specifically, for .NET Core and .NET 5 the solution is a bit different, because that motif has been abandoned in favor of defining a wwwroot folder for only those things which should be served, and the remainder being private. The answer for .NET Core/5, then, is to write to the solution root directory:
First, ensure the NLog.Web.AspNetCore assembly is added to nlog.config:
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
Then use one of the layout renderers provided by that extension, in this case ${aspnet-appbasepath} which references the solution root directory:
<targets>
<target name="file"
type="File"
xsi:type="File"
fileName="${aspnet-appbasepath}/log/${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}"/>
</targets>
This will write the file to <solution folder>/log/2021-07-01.log, which will never be served by the public-facing website. Other layout renderers provided by this assembly are listed on the NLog website.

NLog does not create a log file

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();
}
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)
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.
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
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
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:
Right click on your folder in windows explorer and select properties
Choose the security tab
Click edit
Click add
In the textbox type 'IIS AppPool\YourAppPoolName' replace YourAppPoolName with the actual name of the application pool your site runs under
Click Check names
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
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.
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>
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
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.
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.
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.
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.
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.
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

Categories