NLog: Using NLog with
a windows service
Install Nlog through Nuget in the windows service project.
Install Nlog config through Nuget(it will be an empty file)
NLog library can be seen under References.
Nuget.config example:
<?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="Trace"
internalLogFile="C:\Users\njain\MailerLogs\log.txt"
throwExceptions="false">
<variable name="appName" value="YourAppName" />
<targets async="true">
<target xsi:type="File"
name="logFile"
layout="${longdate} - ${level:uppercase=true}:${logger} ${message}"
fileName="${basedir}\logs\mailer.txt"
keepFileOpen="false"
archiveFileName="${basedir}\logs\Mailer_${shortdate}.{##}.txt"
archiveNumbering="Sequence"
archiveEvery="Day"
maxArchiveFiles="10"
/>
</targets>
<rules>
<logger name="*" writeTo="logFile" minlevel="Trace" />
</rules>
</nlog>
Nlog.Config has two main sections- Target and Rules
Target has log location, name, and format settings and much
more.
Rules describe when to log, where to log and at what level
and much more.
To read more about NLog.config file - https://github.com/nlog/NLog/wiki/Configuration-file
Rebuild windows service project and Setup project, NLog.dll
will be seen in the setup project.
IMPORTANT: Go to
C;/Program Files(x86) and find the windowsServiceSetUp project and deploy the
NLog.config file there. (Without it the windows service will not be able to
write to the log file).
Other important settings to make sure logging works:
- NLog.config: ‘Copy to Output’ property needs to be set to ‘Copy Always’.
- ProjectInstaller: ‘Account’ property needs to be ‘LocalSystem’.
In the code the logger needs to be static so that it can be
accessed all over the class.
Call the GetCurrentClassLogger() method to attach the logger
to the current class.
partial class MailerService : ServiceBase
{
private static Logger
logger = LogManager.GetCurrentClassLogger();
public void Method()
{
logger.Info("Reading the table for mails");
// string
logName =logger.Name;
ReadOutbox
getData = new ReadOutbox();
System.Data.DataSet ds = getData.GetMailIds();
Email
email = new Email();
email.fromEmail = "from@from.com";
email.fromName = "Mailer ex";
email.smtpServer = "smtp.gmail.com";
email.smtpCredentials = new System.Net.NetworkCredential("someemail@gmail.com", "*************");
foreach
(System.Data.DataRow dr in ds.Tables[0].Rows)
{
email.fromEmail = dr["From"].ToString();
email.subject = dr["Subject"].ToString();
email.HtmlBody = dr["HtmlBody"].ToString();
email.mailBcc = dr["Bcc"].ToString();
email.mailcc = dr["Cc"].ToString();
email.replyTo = dr["ReplyTo"].ToString();
email.toEmail = dr["To"].ToString();
flag = true;
if
(email.fromEmail.Length == 0)
{
logger.Info("Message SENT failed to - " + dr["EmailTo"].ToString() + " @ " + DateTime.Now
+ ". The sender field cannot be empty");
flag = false;
return;
}
if
(email.toEmail.Length == 0)
{
logger.Info("Message SENT failed to - " + dr["EmailTo"].ToString() + " @ " + DateTime.Now
+ ". The recipient field cannot be empty");
flag = false;
return;
}
if
(!CheckRecipientEmail(email.toEmail))
{
logger.Info("Message SENT failed to - " + dr["EmailTo"].ToString() + " @ " + DateTime.Now
+ ". Invalid email provided.");
flag = false;
return;
}
if
(flag)
{
bool
result = email.sendEmail(dr["EmailTo"].ToString());
if
(result == true)
{
logger.Info("Message Sent SUCCESS to - " + dr["EmailTo"].ToString());
return;
}
else
{
logger.Info("Message Sent FAILED to - " + dr["EmailTo"].ToString());
}
}
}
if
(ds.Tables[0].Rows.Count == 0)
{
logger.Info("The mail queue is empty");
logger.Info("Log file closed at " + DateTime.Now);
logger.Info("=========================================");
}
}
}
This will log the info messages in the log file when the
windows service runs.
No comments:
Post a Comment