I coded this:
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
public MyClass()
{
Console.Write("lol");
Logger.Debug("Debug test...");
Logger.Error("Debug test...");
Logger.Fatal("Debug test...");
Logger.Info("Debug test...");
Logger.Trace("Debug test...");
Logger.Warn("Debug test...");
}
And nothing displays.. so I was told to go and add <targets> to the config file, thing is.. where is the config file? Nothing on google, the documentation, or anything like that helps me...
From NLog Wiki:
The following locations will be searched when executing a stand-alone *.exe application:
standard application configuration file (usually applicationname.exe.config)
applicationname.exe.nlog in application’s directory
NLog.config in application’s directory
NLog.dll.nlog in a directory where NLog.dll is located (only if NLog isn't installed in the GAC)
So, the easiest would be to add a NLog.config file in the application’s directory
Sample Nlog.config File for your reference:
<?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"
throwConfigExceptions="true">
<targets>
<target name="logfile" xsi:type="File" fileName="file.txt" />
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logconsole" />
<logger name="*" minlevel="Debug" writeTo="logfile" />
</rules>
</nlog>
See also: https://github.com/NLog/NLog/wiki/Tutorial
Alternatively you can define the config programmatically in C# as explained in the blog docs here:
https://github.com/NLog/NLog/wiki/Configure-from-code
Related
NLog version - 4.4.3
Platform - .Net 4.5.2
Current NLog config -
<nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<variable name="layout" value="${longdate}|${level:uppercase=true}|${threadid}|${logger}|${message}" />
<variable name="logLocation" value="logs" />
<targets async="true">
<target name="debugger" xsi:type="Debugger" layout="${layout}" />
<target name="console" xsi:type="Console" layout="${layout}" />
<target name="logfile"
xsi:type="File"
fileName="${logLocation}\${processname}.log"
archiveFileName="${logLocation}\\${processname}.{###}.log"
archiveEvery="Day"
archiveAboveSize="2048000"
archiveNumbering="Rolling"
maxArchiveFiles="10"
concurrentWrites="false"
keepFileOpen="false"
layout="${layout}" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
<logger name="*" minlevel="Debug" writeTo="debugger" />
<logger name="*" minlevel="Info" writeTo="console" />
</rules>
</nlog>
Code to override location
LogManager.ReconfigExistingLoggers();
var target = (FileTarget)LogManager.Configuration.FindTargetByName<AsyncTargetWrapper>("logfile").WrappedTarget;
target.FileName = $#"..\..\..\..\logs\Foobar.log";
What is the current result?
When application/service starts it writes to overwritten location, but sometimes (not sure of scenario - maybe rollover) it start writing to config location.
What is the expected result?
Logs should always be written to overwritten location.
Did you checked the Internal log?
No
Please post full exception details (message, stacktrace, inner exceptions)
No Exception
Are there any workarounds? yes/no
Restart service/application.
Is there a version in which it did work?
No idea. This is the version we started with and sticking to.
Can you help us by writing an unit test?
Unit tests won't help as it is an intermittent scenario.
You have auto reload (<nlog autoReload="true”) enabled, so if it needs to reload (after sleep or change in config), you will lose the changes made in code.
The solution it so disable autoreload, or set the change after reload again. See code example:
static void Main(string[] args)
{
UpdateNLogConfig();
LogManager.ConfigurationReloaded += LogManager_ConfigurationReloaded;
log.Info("Entering Application.");
Console.WriteLine("Press any key to exit ...");
Console.Read();
}
private static void LogManager_ConfigurationReloaded(object sender, LoggingConfigurationReloadedEventArgs e)
{
UpdateNLogConfig();
}
private static void UpdateNLogConfig()
{
//note: don't set LogManager.Configuration because that will overwrite the nlog.config settings
var target = (FileTarget)LogManager.Configuration.FindTargetByName<AsyncTargetWrapper>("logfile").WrappedTarget;
target.FileName = $#"..\..\..\..\logs\Foobar.log";
LogManager.ReconfigExistingLoggers();
}
See also Combine XML config with C# config · NLog/NLog Wiki
Instead of doing target lookup, and modifying target properties directly. Then I suggest making use of the NLog Layout Logic.
<nlog autoReload="true" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets async="true">
<target name="logfile"
xsi:type="File"
fileName="${gdc:item=logFile:whenEmpty=log/${processname}.log}" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
And then just assign the logLocation:
NLog.GlobalDiagnosticsContext.Set("logFile", $#"..\..\..\..\logs\Foobar.log");
Using GDC will also works very well with autoReload=true and no need to call LogManager.ReconfigExistingLoggers().
Recently, we've updated some web and console application, to use a newer version of NLog, the latest 4.5.11.
Before, we've used a 4.4 version.
With this 4.4 version, we were able to set the NLog config inside the web.config or app.config file.
According to the documentation, this is still possible. However, with the newer version this does not work.
I only get some logging, if I copy/paste the same rules, into an nlog.config file.
Of course, I could do this for all my applications, but there is a chance we miss something.
What is the cause it isn't read from the web/app.config file anymore?
I also tried to set the throwExceptions="true" attribute, but it gave me no exceptions.
Also if I set the internal log file, on the attribute inside my web.config, it's still not working. The internal log, is also empty.
Tested with internalLogLevel="Info" and internalLogLevel="Trace"
If I set it in the Application_Start, I only have
2019-02-27 10:23:33.1899 Info Shutting down logging...
2019-02-27 10:23:33.1899 Info Logger has been shut down.
This is my Web.Config (partly)
<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"
internalLogFile="c:\temp\internal-nlog.txt" internalLogLevel="Info">
<targets>
<target name="logfile" xsi:type="File" fileName="${basedir}/Log/${shortdate}.log" layout="${date:format=dd-MM-yyyy HH\:mm\:ss.fff} [${level}] ${callsite} ${message}${onexception:${newline}EXCEPTION OCCURRED\:${exception:format=tostring}}" />
<target name="warnfile" xsi:type="File" fileName="${basedir}/Log/warn/${shortdate}.log" layout="${date:format=dd-MM-yyyy HH\:mm\:ss.fff} [${level}] ${callsite} ${message}${onexception:${newline}EXCEPTION OCCURRED\:${exception:format=tostring}}" />
</targets>
<rules>
<logger name="*" minlevel="Error" writeTo="logfile">
<filters>
<when condition="contains('${message}', 'ThreadAbortException')" action="Ignore" />
</filters>
</logger>
<logger name="*" level="Debug" writeTo="warnfile">
<filters>
<when condition="contains('${message}', 'ThreadAbortException')" action="Ignore" />
</filters>
</logger>
</rules>
</nlog>
I am trying to log exceptions in console application. I have done everything as always (and then it worked for me...):
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="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<targets>
<target name="LogFile" xsi:type="File"
fileName="${basedir}/Log/${date:format=yyyyMMdd} myLog.txt"
layout="${longdate}|${level:uppercase=true}|${message}|${exception}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="LogFile" />
</rules>
</nlog>
class Program
{
private static Logger _log = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
_log.Error("test");
}
}
For some mysterious reason file is never created nowhere on my computer. Any ideas why
Your config looks valid, so that shouldn't be the issue.
Some things to check:
Is you nlog.config in the correct directory? The best way to test is to copy the nlog.config to the directory with your .dll or .exe.
Enable exceptions to be sure that errors are not captured by Nlog: throwExceptions="true"
Check the internal log by setting internalLogLevel="Info" and check "c:\temp\nlog-internal.log"
A full tutorial to troubleshoot could be found on the NLog documentation.
In Visual Studio, check if your NLog.config file has this properties:
Build Action: Content.
Copy to Output Directory = Copy if newer
I am attaching a screen shot where you can see how it should appear. Sorry, it is in Spanish.
Edit your NLog config, change your log file path like this,use ${shortdate} instead {date:format=yyyyMMdd}. Set name in rules and call it like in this sample.
<?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 async="true">
<targets>
<target name="LogFile" xsi:type="File"
fileName="${basedir}/Log/${shortdate}myLog.txt"
layout="${longdate}|${level:uppercase=true}|${message}|${exception}" />
</targets>
<rules>
<logger name="ErrorLog" minlevel="Trace" writeTo="LogFile" />
</rules>
</nlog>
And your .cs
class Program
{
private Logger ErrorLogger = NLog.LogManager.GetLogger("ErrorLog");
static void Main(string[] args)
{
ErrorLogger.Error("test");
}
}
I’ve used NLog on a few console apps without any issue but this is the first time I’ve used it on an MVC web application. When I try to log to a file nothing happens. There are no errors nor are any log files created. When I step through the app locally I don’t get any errors either.
First thing I did was confirm that my NLog.config file’s property was set to “Copy always” in the “Copy to Output” property. I even uninstalled NLog through NuGet and then installed it again as well as closed VS and opened up the project again.
I’ve done some searching and the only real suggestions I found were to create the folder location first and then check the permissions on the app pool. I created the folder location but that didn’t seem to work either. I’m running this through Debug mode in Visual Studio 2015 which automatically fires up a local web server so I don’t know how to find out what service it’s using to write to the file location.
In the example below I can put a break point on my ActionResult inside my controller and see a value being passed in the “gate” parameter. I step though to my test of the logger and don’t get any errors. I look in my log location and no log file is created.
Anyone have any suggestions on what I can try?
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"
autoReload="true"
throwExceptions="true">
<variable name="LogDirBase" value="D:/logs/RampInfo"/>
<variable name="LogYear" value="${date:format=yyy}"/>
<variable name="LogMonth" value="${date:format=MM}"/>
<variable name="LogDay" value="${date:format=dd}"/>
<variable name="LogFileShortDate" value="${date:format=yyyy-MM-dd}"/>
<targets>
<target name="DefaultTarget"
xsi:type="File"
fileName="${LogDirBase}/${LogFileShortDate}.log"
encoding="utf-8"
layout="${longdate} | ${callsite} | ${message}"
maxArchiveFiles="14"
/>
</targets>
<rules>
<logger name="defaultLogger" minlevel="Debug" writeTo="DefaultTarget" />
</rules>
</nlog>
My Controller
public class RampController : Controller
{
private static Logger logger = LogManager.GetCurrentClassLogger();
// GET: GateInfo
public ActionResult Gate(string gate)
{
logger.Debug("Start action result. Gate: " + gate);
}
Logger names typically use something like this
<logger name="Name.Space.RampController" minlevel="Debug" writeTo="DefaultTarget" />
or, if you just want a single log file for your application:
<logger name="*" minlevel="Debug" writeTo="DefaultTarget" />
Internally, LogManager.GetCurrentClassLogger looks at the current Stack to determine the calling type: (silverlight conditionals removed):
public new T GetCurrentClassLogger()
{
StackFrame frame = new StackFrame(1, false);
return this.GetLogger(frame.GetMethod().DeclaringType.FullName);
}
I appreciate everyone's suggestions. I spent hours trying to figure out why the NLog wasn't working. I gave up for the day and came back to it this morning with a fresh mind. I basically started over with a whole new NLog.config and that worked. I copied out of different project a different NLog configuration. I don't really see the difference between the two but either way it's now working as expected.
Here is the new NLog.config I went with.
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwExceptions="true">
<variable name="LogDirectory" value="D:\integration\logs\RampInfo"/>
<targets>
<target name="LogTarget"
xsi:type="File"
fileName="${LogDirectory}/${shortdate}.log"
encoding="utf-8"
maxArchiveFiles="14"
layout="${longdate} ${callsite} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="LogTarget" />
</rules>
</nlog>
I have a unique problem with the NLog. I have a third-party assembly we use into our project. They have used the NLog into their project and referenced NLog configuration into their configuration which I don't have access to.
I initially had a problem even adding the NLog to a project since both version of dlls were different. I had to download the source code of NLog and change the assembly name since alias was not working for me (OR I didn't know how to use it.)
After giving my own assembly name, NLog started wotrking but.. It started logging third-party log information too with it. Looks like they were not careful enough when defining the logger and they just defined (*). Now my question is, how do I avoid their stuff from logging in to my file? I have also tried setting it to final = true.
Here is how my very simple configuration file looks like.
<?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">
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!-- add your targets here -->
<!--
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
<target name="errorLog" xsi:type="File"
fileName="${basedir}/logs/error/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}${onexception:${newline}EXCEPTION\: ${exception:format=ToString}}"
/>
<target name="generalLog" xsi:type="File"
fileName="C:/logs/${date:format=yyyy-MM-dd}.log"
layout="${longdate} ${uppercase:${level}} ${message}"/>
</targets>
<rules>
<!-- add your logging rules here -->
<logger name="Errors" writeTo="errorLog" minlevel="Warn"/>
<logger name="EBusiness.Model.*" writeTo="generalLog" levels="Trace,Debug,Info" final="true"/>
<!--
<logger name="*" minlevel="Trace" writeTo="f" />
-->
</rules>
</nlog>
If they are writing to the root logger, you should configure the root logger to not log to anywhere you care (maybe point it at a console logger) and your application can log to a specific logger which does write to your files.
Ugly, but should work.
For example:
Add this target:
<target name="console" xsi:type="Console" />
And Change the * rule to be:
<logger name="*" minlevel="Fatal " writeTo="console" />
Then, Add your own logger rule, say something like:
<logger name="MyNameSpace.*" minlevel="Trace" writeTo="logfile" final="true" />
Assuming you have a logfile target defined pointing at your file.