NLog not writing from referenced dll - c#

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

Related

Nlog not loggin to File

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

c#, Nlog and change target

i am running windows service,
and i want when i run in debugto to write to console
and when as service to event viewer.
in powershell i set
New-EventLog –LogName Application –Source "mySource"
I have this nlog.config:
<nlog>
<targets>
<target name="debugger" type="Debugger" layout="${logger}::${message}"/>
<target name="console" type="Console" layout="${logger}::${message}"/>
<target name="file" type="File" layout="${longdate} ${logger}::${message}" fileName="${basedir}/Logs/${shortdate}.log"/>
<target name="eventLog" type="eventlog" layout="${logger}::${message}" source="mySource"/>
</targets>
<rules>
<logger name="" minlevel="Trace" writeTo="debugger"/>
<logger name="" minlevel="Trace" writeTo="console"/>
<logger name="*" minlevel="Trace" writeTo="file"/>
<logger name="*" minlevel="Debug" writeTo="eventLog" />
</rules>
</nlog>
i do init when service start :
public static void InitLogger()
{
NLog.Targets.Target target = null;
target = LogManager.Configuration.FindTargetByName("eventlog");
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Info);
LogManager.Configuration.Reload();
}
to test this i change it in both cases to write to "eventlog"
even in debug mode. but it is not working correctly when using the event viewer (VS is running in admin mode)
i set in each class
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
what is missing?
This line will load the NLog.config and lookup a named target:
target = LogManager.Configuration.FindTargetByName("eventlog");
This line will discard the original NLog config (with all rules and targets) and create new one with a single target:
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Info);
This line will not do anything:
LogManager.Configuration.Reload();
I guess you are trying to add an extra target to the existing configuration. This can be done like this (Replacing all the above code):
LogManager.Configuration.AddRule("*", LogLevel.Info, target):
LogManager.ReconfigExistingLoggers();
Btw. if you don't configure the Source-property for the EventLog-target, then it will use AppDomain.FriendlyName

NLog 2.1 EventId for EventLog not working when not specified

I am using Nlog 2.1 and trying to write errors into Windows Event logger with different eventId. To better distinguish different errors.
If I specify eventId property it's working, but if don't I am not seeing any record in Windows Event Logger.
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="console" xsi:type="ColoredConsole"
layout="${date:format=HH\:mm\:ss}|${level:uppercase=true}|${message}" />
<target xsi:type="EventLog"
name="eventlog"
layout="{${newline}
"Logger": "${logger}",${newline}
"StackTrace": "${stacktrace}",${newline}
"Message": "${message}",${newline}
"Exception": "${exception:format=ToString,Data}"${newline}}"
machineName="."
source="CareFusion Analytics Agent Service"
eventId="${event-properties:EventID}"
log="Application" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="console" />
<logger name="*" minlevel="Error" writeTo="eventlog" />
</rules>
</nlog>
Usage:
private static void Main(string[] args)
{
Logger logger = LogManager.GetCurrentClassLogger();
logger.Error("Sample error message"); //This is not working
LogEventInfo logEvent = new LogEventInfo()
{
Level = LogLevel.Error,
Message = "Hello",
LoggerName = logger.Name
};
logEvent.Properties.Add("EventID", 400);
logger.Log(logEvent); //This is working
Console.WriteLine("Press any key....");
Console.ReadKey();
}
The call logger.Error("Sample error message"); goes wrong as the EventLogTarget tries to convert the ${event-properties:EventID} to a integer.
Because layout renders in NLog never return null (but string.Empty), this will give a exception - which will be caught by NLog. In the NLog's internal log you should see a FormatException.
So we need to specify a default value, you could do that with the whenEmpty:
<target xsi:type="EventLog"
...
eventId="${event-properties:EventID:whenEmpty=0}" />
PS: tested it with NLog 4.3.11

NLog in .NET 4.5 console app: not loading Configuration

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>

How to create a text file in my current directory with NLog?

I am using Nlog for the first time. My aim is to just write to a text file.
In main.c I have
class Program
{
private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
logger.Trace("Sample trace message");
logger.Debug("Sample debug message");
logger.Info("Sample informational message");
logger.Warn("Sample warning message");
logger.Error("Sample error message");
logger.Fatal("Sample fatal error message");
}
}
My Nlog.config file is as follows:
<?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" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
But I am not able to create a txt file in my current directory.
Try this...
<targets>
<target name="logfile" xsi:type="File" fileName="${basedir}/file.txt" />
</targets>
Take a look here too, introduction to NLog.
Did you set the NLog.config 'copy to output directory' to 'copy always'?
You should get it to work if you follow their tutorial.
This worked for me ${CurrentDir}
e.g.
<target xsi:type="File"
name="ownFile-web"
fileName="${CurrentDir}\Logs\nlog-web-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}| [${uppercase:${level}}]${newline}Logger: ${logger}${newline}url: ${aspnet-request-url}${newline}CallSite: ${callsite}${newline}Message: ${message}${onexception:${newline}EXCEPTION:${exception:format=tostring}}${newline}-------${newline}" />
https://github.com/NLog/NLog/wiki/CurrentDir-Layout-Renderer

Categories

Resources