my nlog not creating files. I Use the same configuration in another project and everythink is Ok, but in new project nlog not create new files.
Nlog config :
<?xml version="1.0" encoding="utf-8" ?>
autoReload= "true"
internalLogLevel =" Trace"
internalLogFile ="c:\temp\internal-nlog.txt">
<targets>
<target name="file" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="C:\beka\logs\logfile.txt"
/>
<target name="exceptions" xsi:type="File"
layout="${longdate} ${logger} ${message}${exception:format=ToString}"
fileName="C:\beka\logs\logfileExceptions.txt"
/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="file" />
<logger name="*" minlevel="Error" writeTo="exceptions" />
</rules>
On the console I can see that the log has been called but its not sent to a file.
I think the problem can be in c:\temp\internal-nlog.txt becouse this file has references to another project. And when i start another project internal-nlog.txt is update but when i start this project internal-nlog-txt doesnt update
Nlog action = content,
Copy to outputDirectory = copy if newer
Related
I have the following nlog.config file in ASP.NET Core 2.1 project. However, it's logging messages from every logger (including Microsoft logger) to console.
<?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="Error"
internalLogFile="${specialfolder:folder=UserProfile}\nlog\internal-nlog.txt">
<variable name="fullLayout" value="${shortdate} [${uppercase:${level}}] ${logger}: ${message} ${exception:format=tostring} url: ${aspnet-request-url}" />
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write to console -->
<target name="console" xsi:type="ColoredConsole" layout="${fullLayout}" />
<!-- write to file -->
<target xsi:type="File"
name="allfile"
fileName="${defaultDirectory}/test-api-all.log"
archiveEvery="Day"
archiveFileName="${defaultDirectory}/test-api-all-${#}.log"
archiveNumbering="Date"
archiveDateFormat="yyyy-MM-dd"
maxArchiveFiles="5"
layout="${fullLayout}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File"
name="ownFile-web"
fileName="${defaultDirectory}/test-api-app.log"
archiveEvery="Day"
archiveFileName="${defaultDirectory}/test-api-app-${#}.log"
archiveNumbering="Date"
archiveDateFormat="yyyy-MM-dd"
maxArchiveFiles="5"
layout="${fullLayout}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="console" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxLevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
I do not have any logging settings in appsettings.json files. All logger configuration in in nlog.config. In the Program.cs, I'm registering NLog like:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging(logging => logging.ClearProviders())
.UseNLog()
.Build();
How can I filter out Microsoft logs?
EDIT:
Above configuration started working without a problem the next day without me making any changes :O
Maybe this will work:
<!-- rules to map from logger name to target -->
<rules>
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxLevel="Info" final="true" />
<logger name="*" minlevel="Trace" writeTo="console" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
The order of the logging rules are important, as the rules are matched from the top. See also https://github.com/NLog/NLog/wiki/Configuration-file#rules
The order of your logging rules seems to be correct. I suggest trying to double check if your updated nlog.config file is being copied to the build directory (e.g. \bin\Debug\netcoreapp2.1\nlog.config)
I kind of encountered the same issue, but found out that debugging using Visual Studio, it sometimes doesn't really copy the nlog.config file to your build directory. So the solution is to Clean the project first, then Build, and finally Debug.
I have Logger of NLog package,
I want to define trace enable=true in my config logger file.
How can I do it?
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="file.txt" />
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" maxlevel="Trace" minlevel="Trace" writeTo="logfile" />
</rules>
</nlog>
You do this by setting the minLevel attribute in your rules section of the NLog.config like so;
<rules>
<logger name="*" minlevel="Debug" writeTo="CSVFile" />
</rules>
Debug will write out Debug, Info, Warn, Error and Fatal-level log messages. Only Trace is skipped.
EDIT
Conversely, if you wanted to only log Trace, then set the maxLevel like so;
<rules>
<logger name="*" maxlevel="Trace" writeTo="CSVFile" />
</rules>
To just log a specific intermediate level, use minLevel and maxLevel together like;
<rules>
<logger name="*" minlevel="Debug" maxlevel="Debug" writeTo="CSVFile" />
</rules>
EDIT2
I tweaked your config file such that the output logs to the console rather than the 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="file.txt" />
<target name="logconsole" xsi:type="Console" />
</targets>
<rules>
<logger name="*" maxlevel="Trace" writeTo="logconsole" />
</rules>
</nlog>
And when run in a test application where I'm writing out multiple logging levels like so;
_logger.Trace("trace text");
_logger.Debug("debug text");
_logger.Info("info text");
_logger.Warn("warn text");
_logger.Error("error text");
_logger.Fatal("fatal text");
And only the Trace text displays in the console window. One thing of note however, is that the XML in the config file must be correctly formatted. The sample above is working as described in my test application here.
You can create multiple levels of logging by creating multiple logger instaances such as
<rules>
<!-- add your logging rules here -->
<!-- different logger instances for different environments, no levels are mentioned explicitly, can be done if exclusion of some levels is required -->
<logger name="Log.Dev" minlevel="Debug" writeTo="database" enabled="true" />
<logger name="Log.Staging" minlevel="Info" writeTo="database" enabled="true" />
<logger name="Log.Production" minlevel="Error" writeTo="database" enabled="true" />
</rules>
After that while initializing give the name of the logger which you want to initialize
/// <summary>
/// The log.
/// Getting Logger instance from key name defined in Web.config of main web file. Key name is LoggerInstanceName
/// On the basis of name , logger instance and defined rules can be switched from one to another.
/// </summary>
private static readonly NLog.Logger Log = LogManager.GetLogger(Convert.ToString(ConfigurationManager.AppSettings.Get("LoggerInstance")));
Also do not forget to add key in your app settings
<appSettings>
<!--logger instance name-->
<add key="LoggerInstanceName" value="Log.Dev" />
</appSettings>
I use NLog for debugging/tracing in my app. What's happening is that I am seeing some extra stuff in the output. This is C#/VisualStudio on the Mac, targeting iOS.
Here is an example...
I'm using a target of type "Debugger", and my layout line is:
<layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
The call to the logger is:
log.Debug("Added New Key. Code = {0}", code);
And the output is:
AppleLibrary.PasswordMgr: 16:04:36.4064 Debug
AppleLibrary.PasswordMgr.SavePassword:55 Added New Key. Code = -34018
Every debug line starts with <logger name>:
Its even worse when I use a target type of "Console" with exactly the same layout. A call like this:
log.Debug("Started Application");
ends up with this:
2017-06-14 16:04:23.673 MyApp.iOS[11942:6245589] 16:04:23.6374 Debug MyApp.iOS.Application.Main:14 Started Application
in this case every line starts with: 2017-06-14 16:04:23.673 MyApp.iOS[11942:6245589], which looks like the long date, logger name and thread/tick information.
Note that this does not happen with my file target, even though it uses exactly the same layout! The above call shows this in the logfile.txt:
16:04:23.6374 Debug MyApp.iOS.Application.Main:14 Started Application
Which is exactly what I want.
Here is 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" throwExceptions="true">
<targets>
<target name="logfile"
xsi:type="File"
header="############STARTING RUN ${date} ${time}"
archiveOldFileOnStartup="true"
maxArchiveFiles="5"
fileName="/Users/Paul/Dev/MyApp/MyApp.iOS/logfile.txt"
layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
<target name="console" xsi:type="Console"
layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
<target name="debugger"
xsi:type="Debugger"
layout="${time} ${level} ${callsite}:${callsite-linenumber} ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="logfile" />
<logger name="CoreLibrary.*" minlevel="Trace" writeTo="debugger" enabled="false" />
<logger name="AppleLibrary.*" minlevel="Debug" writeTo="debugger" />
<logger name="MyApp.iOS.*" minlevel="Debug" writeTo="console" />
</rules>
</nlog>
I'd appreciate any pointers as to what I'm misunderstanding here.
Thanks.
Paul.
I have some console apps I've written at work. I'd like to get NLog into them but I am having trouble.
When I inspect the 'logger' object, I see in it's 'Factory' property, that the configuration had targets=0, loggingrules=0, everything blank or unset.
So, it doesn't do ANYTHING.. doesn't drop an internal log file either... I have tried nLog.config NLog.config and nlog.config... to no avail. Tried ver 3 and 4 of NLog too...
Why would it not pick up the config?
I have:
NLog.config in the root with 'Content' for build action and 'Copy Always' set
Confirmed the NLog.config IS being copied to the bin
Here's the 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"
autoReload="true"
throwConfigExceptions="true"
throwExceptions="true"
internalLogLevel="Trace"
internalLogFile="c:\temp\NlogInternal.log"
internalLogToConsole="true"
internalLogToConsoleError="true"
internalLogToTrace="true">
<targets>
<target xsi:type="Console" name="debugConsole" layout="${message} "/>
<target xsi:type="File" name="debugFile" createDirs="true" fileName="c:\temp\testlog.log" layout="${longdate} ${uppercase:${level}} ${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugConsole"/>
<logger name="*" minlevel="Trace" writeTo="debugFile"/>
</rules>
</nlog>
and finally (this doesn't error, but nothing is output since the config is blank):
private static Logger logger = LogManager.GetCurrentClassLogger();
logger.Info("ConsoleApp test log...");
Do your app.config have a NLog configSection?
Something like this:
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog>
</nlog>
</configuration>
If even the internalLogger isn't working, you could debug the issue by setting
the InternalLogger.LogWriter
e.g.
// enable internal logging to a custom TextWriter
InternalLogger.LogWriter = new StringWriter(); //e.g. TextWriter writer = File.CreateText("C:\\perl.txt")
I got the same issue on my end. When you make change your fileName Path "c:\temp\testlog.log" to
"c:/temp/testlog.log" then it will work. Hope the below snipet help you to resolve the issue.
<targets>
<target xsi:type="Console" name="debugConsole" layout="${message} "/>
<target xsi:type="File" name="debugFile" createDirs="true"
fileName="c:/temp/testlog.log" layout="${longdate} ${uppercase:${level}}
${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugConsole"/>
<logger name="*" minlevel="Trace" writeTo="debugFile"/>
</rules>
I have a dll that I created for sending email. I have NLog included in that project that logs to c:\logs{logfilename.log} <--This is either an error or event log.
When working with the project locally it works just fine and writes out to the file during testing.
When I reference the emailing dll from another project that also has NLog it is not outputting to the log files. The config from the email dll is in the bin directory of the new project that is referencing it. I can create logs from the new project using a trace but it didn't print the email dll entries. Is there something special I need to do in my new project to get the email dll to write the logs? I've searched for an answer to this but the keywords do not produce the results I would need. I'm new to NLog, please be gentle.
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">
<targets>
<target xsi:type="File"
name="default"
layout="${longdate} - ${level:uppercase=true}: ${message}${onexception:${newline}EXCEPTION\: ${exception:format=ToString}}"
fileName="C:\logs\default.log"
keepFileOpen="false"
archiveFileName="C:\logs\NTC_Utility\default.{##}.log"
archiveNumbering="Sequence"
archiveEvery="Day"
maxArchiveFiles="30"
/>
<target xsi:type="File"
name="error"
layout="${longdate} - ${level:uppercase=true}: ${message}${onexception:${newline}EXCEPTION\: ${exception:format=ToString}}"
fileName="C:\logs\error.log"
keepFileOpen="false"
archiveFileName="C:\logs\NTC_Utility\error.{##}.log"
archiveNumbering="Sequence"
archiveEvery="Day"
maxArchiveFiles="90"
/>
<target xsi:type="File"
name="emailLog"
layout="-------------------- ${message} (${longdate}) --------------------${newline}
From: ${event-context:item=From}${newline}
To: ${event-context:item=To}${newline}
BCC: ${event-context:item=Bcc}${newline}
CC: ${event-context:item=CC}${newline}
Subject: ${event-context:item=Subject}${newline}
Body: ${event-context:item=Body}${newline}
Attachments: ${event- context:item=Attachments}${newline}--------------------------------------------------------------------${newline}"
fileName="C:\logs\EmailLog.log"
keepFileOpen="false"
archiveFileName="C:\logs\NTC_Utility\EmailLog_.{##}.log"
archiveNumbering="Sequence"
archiveEvery="Day"
maxArchiveFiles="90"
/>
</targets>
<rules>
<logger name="*" writeTo="error" level="Error" final="true" />
<logger name="*" writeTo="emailLog" level="Info" final="true" />
<logger name="*" writeTo="default" minLevel="Debug" />
</rules>
</nlog>
This is my Log.cs from the compiled utility dll
using NLog;
namespace NTC.Utility
{
internal static class Log
{
public static Logger Instance { get; private set;}
static Log()
{
LogManager.ReconfigExistingLoggers();
Instance = LogManager.GetCurrentClassLogger();
}
}
}
This line calls my Logging Method after the email is sent.
LogEmailSent(imperEmail);
Which calls this method...
private void LogEmailSent(EmailMessage email)
{
Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo thisEvent = new LogEventInfo(LogLevel.Info, "default","Email Sent");
thisEvent.Properties["From"] = email.From;
thisEvent.Properties["To"] = EmailCollectionToCsv(email.ToRecipients);
thisEvent.Properties["Bcc"] = EmailCollectionToCsv(email.BccRecipients);
thisEvent.Properties["CC"] = EmailCollectionToCsv(email.CcRecipients);
thisEvent.Properties["Subject"] = email.Subject;
thisEvent.Properties["Body"] = email.Body;
thisEvent.Properties["Attachments"] = AttachmentCollectionToCsv(email.Attachments);
logger.Log(thisEvent);
}
Ok, so I finally figured out what was going on after logging the trace... I noticed that it was only showing the error rule as loaded.... so I moved the "emaillog" rule above the "error" rule and all worked perfectly.
check your nlog.config
if not. are there any posibilities some configurations are injected within the code..
http://www.codeproject.com/Articles/10631/Introduction-to-NLog