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>
Related
I have the configuration file set up
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog autoReload="true">
<targets>
<target name="file" type="File" fileName="${basedir}/log/${shortdate}.log" layout="${date:format=HH\:mm\:ss.fff}|${message}"/>
<target name="file_webs" type="File" fileName="${basedir}/log/${shortdate}_webs.log" layout="${date:format=HH\:mm\:ss.fff}|${message}"/>
</targets>
<rules>
<logger name="WebSocket.*" minlevel="Debug" writeTo="file_webs" final="true"/>
<logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</nlog>
</configuration>
The logger is loaded in each class like this:
private static Logger logger = LogManager.GetCurrentClassLogger();
The logging is directed to the correct file as long as I don't run the build version. Then all logging is done in the default log file.
What could be the cause?
Check the following:
Is the correct config file placed in the output directory of the release. Maybe there is a different version of your config file there or it is missing.
Are there other things running after your build? Like a tool to obfuscate the source code? If so, this might mess up the class name in your build, the config the can not redirect to the right output. In that case, explicitly load the logger for your class this way:
private static Logger logger = LogManager.GetLogger("WebSocket.*");
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.
I created simple ASP.NET web-site, added NLog, but it doesn't create any log file, neither throws any exceptions. I tried troubleshoot, but it doesn't help https://github.com/NLog/NLog/wiki/Logging-troubleshooting
my web.config
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<nlog
xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwExceptions="true"
internalLogLevel="Off"
internalLogFile="c:\temp\nlog-internal.log">
<targets>
<target name="file" type="File" fileName="C:\log.txt" />
</targets>
<rules>
<logger name="File" minlevel="Trace" writeTo="file" />
<logger name="FileNotFound" minlevel="Trace" writeTo="file-404" />
</rules>
</nlog>
Then I run page below, and nothing happens...
public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LogManager.ThrowExceptions = true;
Logger logger = LogManager.GetLogger("foo");
Logger log = LogManager.GetCurrentClassLogger();
log.Error("some test");
logger.Error("some test 2");
}
}
What is my fault? Thank you!
The name attriute of the <logger> is a filter (on name)
So you filter now on the loggers with the name "File" and "FileNotFound"
This will write all to the file
<logger name="*" minlevel="Trace" writeTo="file" />
Another option is to use named loggers in C#, so instead of
Logger log = LogManager.GetCurrentClassLogger();
use
Logger log = LogManager.GetLogger("FileNotFound");
Then you could use <logger name="FileNotFound" ..> in your config
Likely that your output directory can't be written to by the IIS user. Try using an output directory relative to the website, like "logs".
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.
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>