how to use etw nlog for writing log to custom eventsource - c#

For my console application , I want to write all the logs to custom event source under Application and Services Logs under separate section MyEventSourceName.
I tried to use NLog.Etw, but seems nothing appears. How to do this?
<?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"
throwExceptions="false">
<extensions>
<add assembly="NLog.Etw" />
</extensions>
<targets async="true">
<target xsi:type="EtwEventSource"
name="eetw"
providerName="MyEventSourceName"
taskName="${level}"
layout="${message}">
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="eetw" />
</rules>
class Program
{
private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
logger.Info("New person created with name {0}");
}
}

You could use the eventlog target:
For example:
<target xsi:type="EventLog"
name="eventlog"
source="MyEventSourceName"
log="MyEventSourceLogName"
layout ="${message}${newline}${exception:format=ToString}"/>
See docs
The target supports .NET3.5+ and .NET Standard 2.0. For NetStandard 2.0 use the NLog.WindowsEventLog package.

Related

NLog with Postsharp not logging

I found out what the problem is. There is no problem with the code. The problem that I wrote column name incorrect in the query. I do not know how I missed such a thing, but thank you for all your help. You can use the codes for the NLog if you want.
( I trying to Logging with NLog into AOP. I working Winform and using Postsharp. NLog codes into ExceptionLoggingAttribute.cs . This codes studies in Form1.cs but does not working in Aspect. Please Help me! )
AOP inside
namespace LogLibrary
{
[PSerializable]
public class ExceptionLoggingAttribute : OnExceptionAspect
{
public FlowBehavior flowbehavior { get; set; }
public override void OnException(MethodExecutionArgs args)
{
NLog.Logger logger = LogManager.GetLogger("databaseLogger");
logger.Error(args.Exception.Message);
logger.Fatal(args.Exception.Message);
logger.Debug(args.Exception.Message);
logger.Trace(args.Exception.Message);
args.FlowBehavior = FlowBehavior.Continue;
}
}
Nlog.Config İnside
<?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">
<variable name="myvar" value="myvalue"/>
<targets>
<target name="database" xsi:type="Database"
connectionStringName="NLogConn"
commandText="exec dbo.dlog #username,#ErrorName,#MethodName,#StackName, #Date_Time">
<parameter name="#username" layout="${identity}"/>
<parameter name="#ErrorName" layout="${message}"/>
<parameter name="#MethodName" layout="${machinename}"/>
<parameter name="#StackName" layout="${stacktrace}"/>
<parameter name="#Date_Time" layout="${date}"/>
</target>
</targets>
<rules>
<logger name="databaseLogger" minlevel="Trace" writeTo="database" />
</rules>
</nlog>
App.Config İnside
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="NLogConn" connectionString="Data Source=DMGM0349997\MSSQLSERVER01; Initial Catalog=deneme; Integrated Security=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Form1 inside
using System.Windows.Forms;
using PostSharp.Aspects;
using NLog;
using LogLibrary;
namespace LogApp
{
[ExceptionLogging]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
throw new Exception("bla bla");
}
}
}
I hope this photo helps you for understand me
You have to enable first the internal log, set internalLogLevel on "info":
internalLogLevel="Info" internalLogFile="c:\temp\nlog-internal.log"
If there is still no internalLogFile, then NLog can't find you nlog.config. Check the location of nlog.config.
Alternative you read it config like this:
LogManager.Configuration = new XmlLoggingConfiguration("pathTo_Nlog.config")
Or set-up the config on C#
I hope this photo helps you for understand me
I had the same problem. When I executed my C# console app's main method that contained codes below, does not any log created:
private static readonly ILog Log = LogManager.GetLogger<Program>();
Log.Info("Application Started . . .");
My problem was the location of NLog.config file.
I right clicked and selected Properties NLog.config in Visual Studio. Then for "Copy to Output Directory" property, selected "Copy if newer" option.
The problem was that NLog.config file was not in executing directory of my app.
This page describes how to configure NLog via XML specification.
specially read the Log Location section.
My AppConfig :
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging"/>
</sectionGroup>
<common>
<logging>
<factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog444">
<arg key="configType" value="INLINE"/>
</factoryAdapter>
</logging>
</common>
and NLog.config files :
<?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"
internalLogLevel="Trace" internalLogFile="d:\NLog_Internallog.txt">
<variable name="logDirectory" value="logs" />
<targets>
<target xsi:type="File"
name="fileXmlName"
header="<nlog>"
footer="</nlog>"
fileName="${logDirectory}/${shortdate}.log.xml"
concurrentWrites="true"
createDirs="true"
autoFlush="true">
<layout xsi:type="Log4JXmlEventLayout">
</layout>
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="fileXmlName" />
</rules>
</nlog>

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 not creating file

As per tutorials, when some exception is thrown, it will write exceptions in a text file. But in my case, when some exception is thrown, I am not able to detect that file of exception in any of the folder.
I had install Nlog.config from nuget and used
var _logger = LogManager.GetCurrentClassLogger();
//In Controller
_logger.Error(ex, "StringErrorMessage");
and this is 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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<variable name="myvar" value="myvalue"/>
<variable name="logDirectory" value="${basedir}/logs/${shortdate}"/>
<targets>
<target name="logfile" xsi:type="File" fileName="${logDirectory}/file.txt" />
</targets>
<rules>
<!-- add your logging rules here -->
<logger name="*" minlevel="Error" writeTo="logfile" />
</rules>
</nlog>
Old question but someone still might look at it.
Does the file c:\temp\nlog-internal.log exist ?
If not, set Copy to Output Directory property of your nlog.config file to Copy always.

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