having an issue saving NLog file to basefolder - c#

I'm having a hard time understanding why ${basedir} does nothing to the current directory of the project and when I change it to the explicit path it does saves the log.
I tried to change the name of ${basedir} to ${currentdir} but it did nothing.
This one works
<target xsi:type="File" name="myAppLoggerTarget" fileName="C:\Users\Omer\Desktop\DBBalancers\Logs\${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
This one works
<target xsi:type="File" name="myAppLoggerTarget" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />

Link to nlog docs suggests: "The current application domain's base directory."
I would try to print out the: "AppDomain.CurrentDomain.BaseDirectory" and see whats the value of that variable.
On the same nlog docs page you can also find about process dir:
processDir - Introduced in NLog 4.4.2. Render the base directory of the current process? Default false.

Related

NLog - Can a FallbackGroup wrapper contain another FallbackGroup wrapper?

In NLog ... can a FallbackGroup wrapper contain another FallbackGroup wrapper? That is I want a cascade effect to handle if my 1st target (writing to a Database) fails, then my 2nd target will be to write to both a file and send an email.
And what config settings are needed to implement this structure (so that NLog handles encountered exceptions [ex. writing to the database failure] properly)?
Thanks for your time and any suggestions you offer.
If you want fallback to write to two targets then you can combine it with SplitGroup:
<target xsi:type="FallbackGroup"
name="db_fallback"
returnToFirstOnSuccess="true">
<target xsi:type="Database" name="db" />
<target xsi:type="SplitGroup" name="split_db_fallback">
<target xsi:type="file" name="file_db_fallback" />
<target xsi:type="mail" name="mail_db_fallback" />
</target>
</target>
See also https://github.com/nlog/nlog/wiki/SplitGroup-target

Set ApplicationData folder on app.config and get it on Nlog.config

I'd like to set the path of NLog log file on app.config.
I know how to set the applicationData folder on NLog.config. It's like that:
<target xsi:type="File"
name="logFileCsv"
fileName="${specialfolder:folder=ApplicationData}/something/something.log">
And if I use the NLog.Extended I know how to get key values from app.config and use them on NLog.config, like that:
<target xsi:type="File" name="logFileCsv" fileName="${appsetting:name=LogPath">
And on app.config should be like this
<add key="LogPath" value="${APPDATA}/something/something.log" />
But it's not working the way I want. NLog is creating the log file on c:\..\${APPDATA}/something/something.log"
So, I'd like to know how to set the ApplicationData folder on app.config to be understandable by NLog?
Unfortunately the ${appsetting} won't evaluate the value.
As work around you can do:
<target fileName="${APPDATA}/${appsetting:name=LogPath}" />
note: wrapping in a ${replace} also won't work
I tried the answer of Julian, but it wasn't utterly successful:
Error FileTarget(Name=logFileCsv): Failed write to file '\\something\something.log
However, with that help and workaround, I figure out how to do it:
So in App.config just add the final path:
<add key="LogPath" value="\something\something.log"/>
and in NLog.Config I did this:
<target xsi:type="File" name="logFileCsv" fileName="${specialfolder:folder=ApplicationData}/${appsetting:name=LogPath}">
And now the log is written on the right path: C:\Users\user\AppData\Roaming\something\something.log

How to use NLog in Xamarin Android

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)

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.

Categories