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");
}
}
Related
ASP.NET CORE Using NLog
I have some trouble , it doesn't delete old logs file.
"MaxArchiveFiles" and "maxArchiveDays" did not execute the action of deleting logs properly.
What I do wrong?
Thanks!
<?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"
internalLogLevel="info"
internalLogFile="C:\Logs\testProject\nlog-internal.txt">
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="ALL"
fileName="C:\Logs\testProject\testProject.${cached:${date:format=yyyy-MM-dd}}.log"
layout="${longdate}|${uppercase:${level}}|${threadid}|${logger}|${message} ${exception:format=ToString}"
maxArchiveFiles="20"
archiveFileName="C:\Logs\testProject\testProject{#}.log"
archiveDateFormat="yyyy-MM-dd"
archiveAboveSize="104857600"
archiveNumbering="DateAndSequence"
maxArchiveDays="3"
archiveEvery="Day"
/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="ALL" />
</rules>
</nlog>
Current files (files from today) are not part of archive when using MaxArchiveDays. So maxArchiveDays="1" will only clean files older than yesterday.
You could consider removing archiveFileName and archiveDateFormat and archiveNumbering, so it becomes this:
<target xsi:type="File" name="ALL"
fileName="C:\Logs\testProject\testProject.${cached:${date:format=yyyy-MM-dd}}.log"
layout="${longdate}|${uppercase:${level}}|${threadid}|${logger}|${message} ${exception:format=ToString}"
maxArchiveFiles="100"
archiveAboveSize="10485760"
maxArchiveDays="1"
/>
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().
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
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>
We are using Nlog as our logging framework and I cannot find a way to archive files the way I want. I would like to have the date of when the logging took place in the logging file name.
Ex All logging that happend from 2009-10-01 00:00 -> 2009-10-01:23:59 should be placed in Log.2009-10-01.log. But all the logs for this day should be placed in Log.log for tailing and such.
The current NLog.config that I use looks like this.
<?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" >
<extensions>
<add assembly="My.Awesome.LoggingExentions"/>
</extensions>
<targets>
<target name="file1" xsi:type="File"
fileName="${basedir}/Logs/Log.log"
layout="${longdate} ${level:uppercase=true:padding=5} ${session} ${storeid} ${msisdn} - ${logger:shortName=true} - ${message} ${exception:format=tostring}"
archiveEvery="Day"
archiveFileName="${basedir}/Logs/Log${shortdate}-{#}.log"
archiveNumbering="Sequence"
maxArchiveFiles="99999"
keepFileOpen="true"
/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file1" />
</rules>
</nlog>
This however sets the date in the logfile to the date when the new logfile is created. Which cause frustration when you want to read logs later.
It also seems like I have to have atleast one # in the archiveFileName, which I rather not. So if you got a solution for that also I would be twice as thankful =)
Probably too late to help you, but I believe all you need to do is include the date in the file name using the date layout renderer with the proper date format. By including the date, you don't need to specify the archive features. When the date changes, a new file will be automatically created.
<?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" >
<extensions>
<add assembly="My.Awesome.LoggingExentions"/>
</extensions>
<targets>
<target name="file1" xsi:type="File"
fileName="${basedir}/Logs/${date:format=yyyy-MM-dd}.log"
layout="${longdate} ${level:uppercase=true:padding=5} ${session} ${storeid} ${msisdn} - ${logger:shortName=true} - ${message} ${exception:format=tostring}"
keepFileOpen="true"
/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file1" />
</rules>
</nlog>
Just in case if somebody still needs a solution -- requested feature has been added to NLog recently: https://github.com/NLog/NLog/pull/241, but it is still not available by Nuget
Maybe this is what you need,
Daily folder with the file Log.log in it
<target xsi:type="File" name="file1" fileName="${basedir}/logs/Log.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>