Why won't my windows service write to my log file? - c#

I have a windows service and use nlog for logging. Everything works fine when I run from the visual studio ide. The log file updates with no issues. When I install the service, the service runs fine but the log file never updates. I am running under LOCAL SERVICE if that helps. Yes, I have created the logs directory under my application folder.
<?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="file" xsi:type="File" fileName="${basedir}/logs/${shortdate}_info.txt"
layout="${date} ${logger} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Info" maxlevel="Info" writeTo="file" />
</rules>
</nlog>

I've had this issue too. As mentioned by genki you are probably logging into the \Windows\System32 directory. Maybe check for the log file you are expecting there first. When writing services I've often put a line like this in the beginning to get the current directory to behave like a normal application
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

If you are using x64 version of Windows than the log file is saved in C:\Windows\SysWOW64 folder
This is the default case if you build your project using the AnyCPU configuration and deploy to a 64 bit operating system.

Your local service account doesn't have access to write to the file location specified. You set it to use a system account in the "Log On" tab of the service properties dialog, or you can set up the user account as part of the setup process.

You can use Process Monitor to look at the file operations being performed, and why they are failing.
I would suspect (along with other answerers) that this is a permission problem, with the service's account not having sufficient access to the file.

Just out of curiousity, have you checked whether anything is being written in the system32 directory of your windows installation? Iirc, that's the default application runtime base directory for services...

I have just had the same problem with Enterprise framework logging.
To conclude this question of which the Answers together tell the correct story.
In your example when using the Visual Studio IDE the log file is being written using the application's user permissions and the log file is being written.
The Windows Service does not have these same permissions so the log file will not get written. Windows Service does have permission (I have tested this) to write to the
AppDomain.CurrentDomain.BaseDirectory
using System.IO namespace.
So direct the log file to this base directory and you will be safe.

I found this post very helpful when I had the same problem:
http://nlog-forum.1685105.n2.nabble.com/Nlog-not-working-with-Windows-service-tp6711077p6825698.html
Basically, you'll want to include ${basedir} as part of your file location in your config. This will make NLog start at where your executable is running from.

Have you tried install/run your service as a different named user.
If that works, then you can be pretty sure you've a permissions issue where your Local system account doesn't have permission to write to the directory/file.

It's maybe your service is running under an other user context and also because of Windows restrictions. I had the same issue and solved it logging into the following folder:
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
Maybe this will help you.

After creating an installation project for my service, and installing it multiple times, I finally realized that I had not included the NLog.config file as one of the files to install. Now that it is included alongside the executable, it's working perfectly.
For what it's worth, the NLog.config file can be manually added after the fact, but the service may need to be stopped and restarted.

I had a very closely related problem. My NLOG looked like this:
<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="c:\temp\nlog-internal.log">
<targets>
<!-- Write events to a file with the date in the filename -->
<target xsi:type="File"
name="File"
fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<!-- Exception levels: Fatal, Error, Warn, Info, Debug, Trace -->
<logger name="*"
minlevel="Debug"
writeTo="File" />
</rules>
It was all permission related. Firstly, where I installed the service, I had to make sure the LOCAL SERVICE account had permission to read/write to the Logs folder.
Secondly, the internalLogFile although not written to, Nlog appears to try and access regardless - which is why I solved my issue by again ensuring LOCAL SERVICE has permission to read/write in **c:\temp**

hi this is what i did and it's work nicely u have to create class library and in this class add the following methode ^^
public static void WriteErrorLog(Exception ex)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ":" + ex.Source.ToString().Trim() + ":" + ex.Message.ToString().Trim());
sw.Flush();
sw.Close();
}
catch
{
}
}
public static void WriteErrorLog(String Message)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ":"+Message);
sw.Flush();
sw.Close();
}
catch
{
}
}
and in your service u have to make in OnStart method :
Library.WriteErrorLog(" Service Started ");
//and in your OnStop method
Library.WriteErrorLog(" Service Stoped ");
hope this will be helpfull .

Related

NLog no log output from a referenced project

I am using NLog 4.5.11 in one Visual Studio 2017 solution. It has the nlog.config in the start up project, but the actual logging required is from another project, where NLog is referenced (but no nlog.config exists). Running this solution works fine, the NLog logs are being produced where I expect.
The second VS solution uses (references) both the start up project and the one with the logging. One note on this project is that it is an Excel Add-on. When I run (debug from VS) this second solution, I do NOT get the NLog logging that should have been triggered via the referenced projects' code and NLog logging. I do not get any errors, exceptions, or error files etc.
I have tried also installing the NuGet packages for NLog to the second solution. I also tried adding a copy of the nlog.config to it. I have looked in the build directory and the NLog dlls and config file are being copied there. I have also tried enabling the throwExceptions="true" and internalLogLevel="Trace".
I have been looking on SO and elsewhere, but I cannot find a solution or even how to debug it. All that ever happens is simply no output, which is really frustrating.
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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="true"
internalLogLevel="Trace" internalLogFile="c:\temp\nlog-internal.log">
<variable name="appName" value="FSIS" />
<variable name="logDir" value="c:\temp\Rbnz.Fsis.Logging" />
<variable name="logDirArchive" value="c:\temp\Archive\Rbnz.Fsis.Logging" />
<targets async="true">
<target xsi:type="File"
name="default"
layout="${longdate} - ${level:uppercase=true}: ${message}${onexception:${newline}EXCEPTION\: ${exception:format=ToString}}"
fileName="${logDir}\${shortdate}.log"
keepFileOpen="false"
archiveFileName="${logDirArchive}\${shortdate}.{##}.log"
archiveNumbering="Sequence"
archiveEvery="Day"
maxArchiveFiles="30"
/>
</targets>
<rules>
<logger name="*" writeTo="default" minlevel="Debug" />
</rules>
</nlog>
Usage inside the code of the referenced project:
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
and later on, inside a method:
logger.Info("Start: CompileSeries()");
logger.Info("Done: CompileSeries()");
I expected that if NLog logging works for a project, then including that project as a reference in another project (in another solution), would trigger the same logging. Obviously I'm incorrect in this assumption.
Based on what you wrote, you have a First Solution that has two projects--a startup project that configures a logger object. That solution has a second project that references the startup project's logger object. Fine.
Now you have a Second Solution. In this solution, you simply reference the First Solution's startup project assembly and the First Solution's second project. Your Second Solution has its own project that's trying to access the logger exposed by the First Solution's referenced projects.
This issue is that your First Solution actually executes its startup project. Your Second Solution does not execute it--it simply references it. Therefore, your logger object isn't getting properly initialized by NLog.
The solution (generically) is to ensure that your logger object is initialized in your Second Solution just as it's initialized in your First Solution. If you want more specific guidance, show specifics as to how your First Solution's startup project initializes the logger object and I should be able to help you replicate that logic in the Second Solution.
Your conclusion that you cannot log from another solution is incorrect. It's all about proper object initialization.
I hope this helps.

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.

Why is my NLog configuration not working on my server machine?

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.

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

NLog not working in release mode

I am using NLog to log the exceptions in my asp.net mvc (C#) application.
NLog is not working in release mode. The same is working when running in debug mode.
What may be the problem? Is there any fix for this?
I was having the same problem as you:
ASP.NET MVC 3
.NET 4
IIS 7
Release Mode
I tried changing directories, and changing permissions to no avail. I even tried enabling the internal logging but even that didn't work! No failures, no exceptions, nothing!
After doing some more investigating, I found the solution. For some reason, NLog wasn't loading the config file AT ALL. I realized this after I programmatically enabled the internal logging. The internal logging reported this:
2012-02-13 11:34:40.3181 Debug Targets for MyMvcController by level:
2012-02-13 11:34:40.3181 Debug Trace =>
2012-02-13 11:34:40.3181 Debug Debug =>
2012-02-13 11:34:40.3181 Debug Info =>
2012-02-13 11:34:40.3181 Debug Warn =>
2012-02-13 11:34:40.3181 Debug Error =>
2012-02-13 11:34:40.3181 Debug Fatal =>
This was basically saying that there were no targets defined for any of the log levels! Definitely not correct!
My NLog configuration file was as simple as it could be (and it was set to Copy to Output Directory):
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<!-- Other XML Sections -->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File" fileName="${basedir}/MyApplication.log" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
</nlog>
</configuration>
I'm still not sure exactly why this was happening, but moving the NLog configuration into the web.config directly resolved the problem.
See also: https://github.com/nlog/NLog/wiki/Configuration-file#configuration-file-format
set up environment variables:NLOG_INTERNAL_LOG_LEVEL and NLOG_INTERNAL_LOG_FILE, rerun your release build then check the log file see what's wrong
For anyone, who is not sure about 'why nlog is not working in prod environment':
Go to Nlog.config file
SET throwExceptions="true" in nlog tag
and start debugging with proper errors.
Good luck.
I think you should provide to your publish directory IIS_IUSRS to Write Permission.
Transfer nlog config to config file of your application (web.config for example), and try again.
Make sure your target file saves within a "/logs/" folder. See below
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
I tried to log into "root/log.log" and was not working, then tried "root/logs/log.log" and worked
Below full 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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log" >
<!-- optional, add some variabeles
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<!--
Writing events to the a file with the date in the filename. -->
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<!-- 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>
</nlog>
You can activate the NLog InternalLogger from code, so you can rule out the issue with correct deployment of NLog.config:
// enable internal logging to the console
NLog.Common.InternalLogger.LogToConsole = true;
// enable internal logging to a file
NLog.Common.InternalLogger.LogFile = "c:\\nlog-internal.txt"; // On Linux one can use "/home/nlog-internal.txt"
// set internal log level
NLog.Common.InternalLogger.LogLevel = LogLevel.Debug;
// Perform test output, ensure first NLog Logger is created after InternalLogger is enabled.
NLog.LogManager.GetLogger("Test").Info("Hello World");
See also: https://github.com/NLog/NLog/wiki/Internal-Logging
See also: https://github.com/NLog/NLog/wiki/Logging-troubleshooting
Another thing worth checking is the write permission of your log directory and/or files.
Permission error, or any other error, will show up in the internal log if enabled. This is how I set up my 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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
<!-- setting to True will break your application so be careful -->
throwExceptions="false"
<!-- change level to your preference -->
internalLogLevel="Error" internalLogFile="c:\your-path\nlog-internal.log">
<!-- your NLog settings -->
<!-- ... -->
</nlog>
Assuming you've configured NLog in the right way, like the other answers suggest, Try one of these
Write Permission for your Server
If you are using IIS, give WRITE permission for user IIS_IUSRS for your log folder.
Constructor
public LoggerService() {
_logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
}
The path for nlog.config could be different for you. Mine was on the same folder

Categories