Web.config transform moving namespace declaration - c#

Using this online tester it is easy to see the following issue
I have a web.config that looks like:
<?xml version="1.0"?>
<configuration>
<nlog/>
</configuration>
And a transform that looks like:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<xdt:Import assembly="AppHarbor.TransformTester" namespace="AppHarbor.TransformTester.Transforms"/>
<nlog xdt:Transform="Replace"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets async="true">
<target name="LogMill" xsi:type="FallbackGroup" returnToFirstOnSuccess="true">
<target xsi:type="LogMillMessageBus"/>
<target xsi:type="File" fileName="..\LogMill-FailSafe.log" layout="${TextErrorLayout}"/>
</target>
</targets>
</nlog>
</configuration>
But the output is not what I expect, it moves the xsi namespace declaration down to the element that uses it, which causes nlog to fail to parse the configuration with the error Parameter p4 not supported on FallbackGroupTarget
<?xml version="1.0"?>
<configuration>
<nlog>
<targets async="true">
<target name="LogMill" p4:type="FallbackGroup" returnToFirstOnSuccess="true" xmlns:p4="http://www.w3.org/2001/XMLSchema-instance">
<target p4:type="LogMillMessageBus" /><target p4:type="File" fileName="..\LogMill-FailSafe.log" layout="${TextErrorLayout}" />
</target>
</targets>
</nlog>
</configuration>
Is there a transform option or syntax that I can apply to prevent it from moving the namespace declaration? I couldn't find anything in the documentation

Move your xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" declaration to the topmost element and it should be OK

In my case instead of
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
I had to use
xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"

Related

Format JSON object in Console or File targets of NLog

For a simple prototype program, I am using NLog with ColoredConsole and File targets, with simple layouts (see configuration file below).
And I am using # operator to destructure objects :
Logger.Debug("values : {#result}", aRandomObject);
where aRandomObject could be anything.
Unfortunately, for both the Console and File targets, by default the destructured object is rendered in json without any formatting. Pretty convienient for computers, but much harder to read for humans.
Instead, I would like to find a way to print my objects as formatted json (with indentations and line breaks) if it's possible with Nlog.
I don't want to render the whole target as a json (as a "JsonLayout" allows), but only the objects logged with #.
Here's the full NLog configuration :
<?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="true"
internalLogLevel="Off" internalLogFile="c:/temp/nlog-internal.log">
<variable name="baseLogDirectory" value="C:\Logs\Thing"/>
<targets>
<target xsi:type="File" name="file" fileName="${baseLogDirectory}\${cached:cached=true:inner=${date:format=yyyyMMdd_HHmmss}}_${processid}.log"
layout="${longdate} ${uppercase:${level}} ${callsite} ${message} ${exception:format=toString,Data}" />
<target name="console" xsi:type="ColoredConsole" layout="${longdate}|${pad:padding=5:inner=${level:uppercase=true}}|${message}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file, console" />
</rules>
</nlog>
Thank you

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 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.

ASP.NET MVC - NLog file target not found

I have a problem with NLog.
I have configured the NLog in the file Nlog.config as following:
<?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="true"
internalLogLevel="Trace"
internalLogFile="d:\temp\nlog-internal.log">
<target xsi:type="File" name="log" fileName="${basedir}\logs\${date:format=dd}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
<rules>
<logger name="*" minlevel="Debug" writeTo="log" />
</rules>
</nlog>
And I get an error that target log is not found. I really don't know what I can do, maybe someone had similar problem.
I'm using .NET 4.5.
The Nlog.config is in the main directory of the project.
I set up the permissions to full access in the directories.
I tried to move the configuration into the web.config file, but the error still appear.
2016-07-26 09:17:25.6353 Warn Skipping unknown node: target
2016-07-26 09:17:25.6353 Trace ParseRulesElement
2016-07-26 09:17:25.6623 Error Error in Parsing Configuration File. Exception: NLog.NLogConfigurationException: Exception occurred when loading configuration from D:\Project\NLog.config ---> NLog.NLogConfigurationException: Target log not found.
w NLog.Config.XmlLoggingConfiguration.ParseLoggerElement(NLogXmlElement loggerElement, IList`1 rulesCollection)
w NLog.Config.XmlLoggingConfiguration.ParseRulesElement(NLogXmlElement rulesElement, IList`1 rulesCollection)
w NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String filePath, Boolean autoReloadDefault)
w NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
w NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
Structure of the project:
Update (after Michel A. answer): I have also properties in NLog.config file
Build Action = Content
Copy to Output Directory = Copy always
Update2: I found the solution. The problem was that I have the backslashes instead of forward slashes
Wrong syntax:
fileName="${basedir}\logs\${date:format=dd}.log"
Correct syntax:
fileName="${basedir}/logs/${date:format=dd}.log"
Update2: I found the solution. The problem was that I have the backslashes instead of forward slashes
I'm pretty sure that wasn't the problem. The paths aren't evaluated on registering the target. Also on Windows the kind of slashes don't matter.
The problem is here that the XML is lacking the <targets>:
<?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="true"
internalLogLevel="Trace"
internalLogFile="d:\temp\nlog-internal.log">
<target xsi:type="File" name="log" fileName="${basedir}\logs\${date:format=dd}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
<rules>
<logger name="*" minlevel="Debug" writeTo="log" />
</rules>
</nlog>
It should be:
<?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="true"
internalLogLevel="Trace"
internalLogFile="d:\temp\nlog-internal.log">
<targets>
<target xsi:type="File" name="log" fileName="${basedir}\logs\${date:format=dd}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="log" />
</rules>
</nlog>
Hint: You get auto completion and error checking if you install the NLog.Schema package
Is your NLog config file being copied into your bin folder ?
(check property file in Visual Studio)

Why does NLog miss some messages when logging a large number of messages?

I try to test NLog performance (latest version) with settings:
<?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">
<variable name="basePath" value="c:\logs\" />
<variable name="msgFormat" value="${message}" />
<targets async="true">
<target name="file"
xsi:type="File"
fileName="${basePath}/${logger}/${date:format=yyyy}/${date:format=MMMM}/log-${date:format=yyMMdd}-${level}.log"
layout="${msgFormat}"
concurrentWrites="true" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file"/>
</rules>
</nlog>
and run this code:
var msg = "this is example string for logging test. it's not very long, but not very short";
var count = 20000;
Parallel.For(0, count, x => nlog.Info(msg));
NLog writes to file, but when file size reaches 1MB it stops writing. I try to use simple for loop, but it doesn't helped me.
And i try to use internal logging, but there is no errors, by the way i see there this strings:
2013-04-01 11:36:18.2458 Trace Opening
c:\logs/NLogTest/2013/April/log-130401-Info.log with
concurrentWrite=False
It's very strange, because concurrentWrites default value is true, furthermore I've set this value in config.
The problem lies in the default value of the AsyncWrappers QueueLimit, which is 10000.
The value determines how big the queue of messages to write are allowed to be, the problem arises because all 20000 messages are queued before anything is written to the file, which causes NLog to discard the last 10000 messages.
Unfortunately this cannot be changed when using the async attribute, you have to define the AsyncWrapper manually to be able to control the QueueLimit, which is done like 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">
<variable name="basePath" value="c:\logs\" />
<variable name="msgFormat" value="${message}" />
<targets async>
<target name="asyncWrapper" xsi:Type="AsyncWrapper" queueLimit="20000">
<target name="file"
xsi:type="File"
fileName="${basePath}/${logger}/${date:format=yyyy}/${date:format=MMMM}/log-${date:format=yyMMdd}-${level}.log"
layout="${msgFormat}"
concurrentWrites="true" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file"/>
</rules>
</nlog>
Where QueueLimit is set to 20000.
You could also changed the OverflowAction if you need to do something other the discard messages not put in the queue, see AsyncWrapper documentation for more information. The options are Block, Discard or Grow.

Categories

Resources