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
Related
I've got this nlog.config file in my .Net Core console application:
<?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="c:\temp\IBTest\internal-nlog.txt">
<targets>
<target xsi:type="File" name="allfile" fileName="c:\temp\IBTest\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="File" name="ownFile-web" fileName="c:\temp\IBTest\nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
<target xsi:type="Null" name="blackhole" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="allfile" />
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
When I start my application on windows it works fine and creates all log files that should be created.
However, when I deploy my app on Linux it doesn't work.
This is how my nlog.config file looks on Linux:
<?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="/home/ib_tests_internal-nlog.log">
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="/home/ib_tests-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="/home/ib_tests_nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}| ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
<!-- write to the void aka just remove -->
<target xsi:type="Null" name="blackhole" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
I really don't get what's wrong. I checked the paths million of times, all files (at least the ones I think) have all rights to read/write.
I've tried dotnet publish and then dotnet app.dll in windows and it worked. When I start the application the same way on Linux it doesn't. And I'm really out of ideas. Seems that all I've been doing was copy-paste from samples I had. Does anyone have ideas what could be wrong? Or what else to check? or some manual way to create that log file and see if it runs? seriously been sitting half of the day to the point I thought I'm going to be fired
My guess would be the filename casing of your NLog.config is incorrect. Unless you have configured the code to use something other than the default, then nlog.config will not work, and it must be NLog.config (notice the capital N and L).
I just had a similar issue. Nlog worked fine on Windows and Mac development machines, but failed to log when deployed to Linux. The issue for me was permissions (I found this out by trial-and-error, not from any errors or messages). Try adjusting permissions on the directory that is being logged to.
You are logging directly to the /home directory, I would suggest updating you nlog.config to use a /home/logs subdirectory.
<target xsi:type="File" name="ownFile-web" fileName="/home/logs/ib_tests_nlog-own-${shortdate}.log" ...
Then set permissions with:
sudo chmod -R 777 /home/logs
I'm trying to use NLog with an Azure Web App. Everything works on my local PC, but when I deploy to Azure it doesn't work at all.
I've tried with different targets like file and Azure table storage. Both work perfectly on my PC but not in Azure.
I'm using asp.net core.
Here is my NLog config for the table storage.
Note: this configuration works when I execute the program from my local PC. I can see the entries in the Azure table storage.
<?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"
>
<extensions>
<add assembly="NLog.Extensions.AzureTableStorage"/>
</extensions>
<targets>
<target xsi:type="AzureTableStorage" name="allfile"
PartitionKey="nlog-all-${date}.${logger}"
RowKey="${ticks}.${guid}"
ConnectionString="**REMOVED**"
tableName="**REMOVED**"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="AzureTableStorage" name="ownFile"
PartitionKey="nlog-own-${date}.${logger}"
RowKey="${ticks}.${guid}"
ConnectionString="**REMOVED**"
tableName="**REMOVED**"
layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />
<target xsi:type="Null" name="blackhole" />
</targets>
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile" />
</rules>
</nlog>
I noticed that the configuration file NLog.config was not getting updated (or is being overwritten) in Azure.
Renaming the configuration file to something different solved my problem.
However, I consider this a workaround only.
The NLog.config in Azure seems to be the one coming as example, and contains no targets at all.
I have one server and many client applications, NLog is used everywhere. The purpose is to nearly completely remove logs from client and to send logs from a client directly to the server. It's successfully done through WCF, ILogReceiverServer and LogReceiverService target (as written there).
But the connection between server and client apps could be lost, so it's necessary to write Error messages to the file on the client side. And it should be written only when the connection is lost. I've studied NLog docs (should've studied better), but haven't found anything. Is it possible to check if logs were sent successfully or not? Or, may be, to enable/disable logger based on the result of logs sending?
Client config:
<nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File" ... />
<target name="console" xsi:type="Console" ... />
<target xsi:type="LogReceiverService"
name="RemoteWcfLogger"
endpointConfigurationName="NetTcpBinding_ILogReceiverServer"
endpointAddress="net.tcp://address:port/LogReceiverServer"
useBinaryEncoding="True"
clientId=""
includeEventProperties="True">
</target>
</targets>
<rules>
<logger name="*" minLevel="Trace" writeTo="RemoteWcfLogger"/>
<logger name="*" minLevel="Error" writeTo="file" />
<logger name="*" minLevel="Trace" writeTo="console" />
</rules>
</nlog>
Maybe the Nlog FallbackGroup-target could be a solution:
https://github.com/nlog/NLog/wiki/FallbackGroup-target
So when the primary-target fails, then it will fallback to a secondary target.
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)
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