This is not so much as a question as it is a warning, and a bit of a rant.
I have the following NLog configuration 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"
throwExceptions="true">
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<target xsi:type="File" name="f" fileName="${basedir}/logs/NLog_${shortdate}.log"
layout="${date} ${uppercase:${level}} ${message}" />
<target xsi:type="File" name="eventFile" fileName="${basedir}/logs/EventFile_${shortdate}.log"
layout="${date} ${uppercase:${level}} The answer is ${event-context:item=Universe}" />
</targets>
<rules>
<logger name="MyLogger" minlevel="Trace" writeTo="f" />
<logger name="EventLogger" minlevel="Debug" writeTo="eventFile" />
</rules>
</nlog>
I am using the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using NLog.Config;
using NLog.Targets;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
Logger eventLogger = LogManager.GetLogger("EventLogger");
LogEventInfo eventInfo = new LogEventInfo(LogLevel.Debug, "EventLogger", "message");
eventInfo.Properties["Universe"] = 42;
eventLogger.Debug(eventInfo);
}
catch (Exception ex)
{
int a = 1;
}
int b = 1;
}
}
}
I used NuGet to download NLog for this application. It gave me NLog version 3.1.0.0. When I run this application, the exception handler is invoked, and the inner exception complains that a dictionary has been modified and therefore can no longer be enumerated.
Earlier, I had downloaded NLog 3.0.0.0 from another source. I replaced the 3.1.0.0 reference in my application with a reference to the 3.0.0.0 version, and the exception did not occur.
I am a brand new user of NLog, and this is the second serious bug I have found. The first one was that if a log is created with a log level of "Off", which is perfectly legal, an index out of range exception is thrown. This is because the integer value of an enumeration of log levels for "Off" is 6, and that number is used as an index into an array that only has six elements (thus, its highest index is 5).
I realize that NLog is an open-source project and thus does not have guarantees, but given its popularity, I would have expected that there would be much better test procedures in place than there seem to be.
RobR
Related
My current .net core nlog WebAPI config. I'm using:
<targets async="true">
Asynchronous target wrapper allows the logger code to execute more
quickly, by queueing messages and processing them in a separate
thread.
https://github.com/nlog/NLog/wiki/AsyncWrapper-target#async-attribute-and-asyncwrapper
<targets async="true">
<target name="jsonfile" xsi:type="File" fileName="/MyAPI${date:format=yyyy-MM-dd HH-mm-ss}.json" >
<layout xsi:type="JsonLayout">
<attribute name="Date" layout="${date:format=O}" />
</layout>
</target>
</targets>
This creates files every second:
MyAPI_2022-12-08 23-06-28.json
How how can I let nlog do something (f.ex. change the name or move it to another folder) when nlog is done writing to the file? I have a system (Splunk Universal Forwarder) that picks up the logs and I don't want it to pick up the file while it's being written to.
Thanks! :-)
hi I am trying to use Http target to send the log to an API.
nlog.config:
<targets>
<target name='HTTP'
type='HTTP'
URL='https://localhost:44331/api/logs'
Method='POST'
BatchSize='1'
MaxQueueSize='2147483647'
IgnoreSslErrors='true'
FlushBeforeShutdown='true'
ContentType='application/json'
Accept='application/json'
DefaultConnectionLimit='2'
Expect100Continue='false'
UseNagleAlgorithm='true'
ConnectTimeout='30000'
InMemoryCompression='true'>
<layout type='JsonLayout'>
<attribute name='sourcetype' layout='_json' />
<attribute name='host' layout='${machinename}' />
<attribute name='RequestBody' layout='${aspnet-request-posted-body}' />
<attribute name='event' encode='false'>
<layout type='JsonLayout'>
<attribute name='level' layout='${level:upperCase=true}' />
<attribute name='source' layout='${logger}' />
<attribute name='thread' layout='${threadid}' />
<attribute name='message' layout='${message}' />
<attribute name='utc' layout='${date:universalTime=true:format=yyyy-MM-dd HH\:mm\:ss.fff}' />
</layout>
</attribute>
</layout>
</target>
I got every attribute I added except for RequestBody.
Also logging to file and database is working fine as well as
http it is being called but without the request body data.
Any thing I am missing?
Probably you're missing the proper setup.
I will list the options:
ASP.NET (non-core)
You need to have the package NLog.Web installed
Then it should work out of the box, but I you have still issues, then force to include NLog.Web like this:
<nlog>
<extensions>
<add assembly="NLog.Web"/>
</extensions>
...
See docs
ASP.NET Core
For ASP.NET Core it depends on the version.
First of all you need the package NLog.Web.AspNetCore installed.
Also add to your config:
<extensions>
<!--enable NLog.Web for ASP.NET Core-->
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
And the Setup need to call NLog.Web.AspNetCore. I would recommend to check: Use NLog in ASP.NET Core application
Make sure you have called .AddNLogWeb(); / .UseNLog() (dependent on the ASP.NET Core version)
Still issues?
Still issues? There could be various other reasons and for now that's guessing. The target you used could choke on the length of the value etc.
I would recommend: Test it with a FileTarget or ConsoleTarget
and as check the internal log! - that will show a good error message if there is something wrong.
I faced the same and solution is in few github issues and thanks to Julian.
1.https://github.com/NLog/NLog.Web/issues/548
FilePath=C:\Users\user\myapp\bin\Debug\netcoreapp3.1\nlog.development.config
2020-07-21 11:05:29.1792 Warn Exception in layout renderer. Exception: System.InvalidOperationException: Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
at Microsoft.AspNetCore.Server.IIS.Core.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at Microsoft.AspNetCore.Server.IIS.Core.WrappingStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.Read(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
at NLog.Web.LayoutRenderers.AspNetRequestPostedBody.BodyToString(Stream body)
at NLog.Web.LayoutRenderers.AspNetRequestPostedBody.DoAppend(StringBuilder builder, LogEventInfo logEvent)
at NLog.LayoutRenderers.LayoutRenderer.RenderAppendBuilder(LogEventInfo logEvent, StringBuilder builder)
https://github.com/NLog/NLog.Web/pull/549
https://github.com/NLog/NLog.Web/issues/556
Adding below finally fixed the issue.
app.Use(async (context, next) => {
context.Request.EnableBuffering();
await next();
});
to here and Must be before app.UseEndpoints
public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
NLog.Web.AspNetCore v5.1 changes ${aspnet-request-posted-body} so it requires middleware to work:
app.UseMiddleware<NLog.Web.NLogRequestPostedBodyMiddleware>();
The middleware will ensure context.Request.EnableBuffering(); is called when necesary, so one doesn't have to call it explictly.
See also: https://github.com/NLog/NLog.Web/wiki/HTTP-Request-Logging
In an NLog.config file I had to add a new rule to log errors to the event log.
There was already a line specifying an error target:
<logger name="*" minlevel="Error" writeTo="AzureTableStorage" />
So I just added eventlog to the writeTo parameter.
<logger name="*" minlevel="Error" writeTo="AzureTableStorage,eventlog" />
And here is eventlog
<target xsi:type="EventLog"
name="eventlog"
source="MyApp"
layout="${message}${newline}${exception:format=ToString}"/>
However some of the other targets (AzureTableStorage, trace, loggly) all have a blue underline on them and the tooltip says
This is an invalid xsi:type http://www.nlog-project.org/schemas/NLog.trace
In another project the same targets do not have this error.
What do I need to do to remove this error?
This is a error from the XSD, which should be seen as warning. The XSD is generated with all the possible targets (in the NLog main package) and thus doesn't have the custom targets.
These kind of errors could be ignored and NLog won't stop working if the XML config contains these kind of "errors".
I am working on a C# console application.
I want to include some properties file which has name value sort pf pairs which i can use during runtime and can be editable like config.properties in java
Any suggestions?
Just add an App.config file to the project
Then setup your config file to hold the property values
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Property1" value="value1"/>
<add key="Property2" value="value2"/>
<add key="Property3" value="value3"/>
</appSettings> </configuration>
After that, you will need to add a reference to the .NET System.Configuration assembly (if you don't already have it referenced) in the Solution Explorer for your project.
Then you can do something like this
using System;
using System.Configuration;
namespace YourAppNamespace
{
class Program
{
static void Main(string[] args)
{
string property1 = ConfigurationManager.AppSettings["Property1"];
string property2 = ConfigurationManager.AppSettings["Property2"];
string property3 = ConfigurationManager.AppSettings["Property3"];
Console.WriteLine(property1);
Console.WriteLine(property2);
Console.WriteLine(property3);
}
}
}
I have nearly completed my first ETL process that uses Rhino ETL, and I've been able to figure out the way to use the API by referring to the tests.
Great. I have data moving through the pipeline and being written to the db.
However I can't seem to figure out how to enable logging.
the log4net assemblies are there, the log4net object is being created
the WithLoggingMixin class seems to be doing its thing (although I must admit I'm a bit fuzzy on exactly what that is)
in the log4net.config file I have a follingFileAppender set up, and it contains the following:
But no log file is created. When I make a call to Debug() in my code it doesn't do anything because log.IsDebugEnabled is false.
What am I missing?
In Rhino Etl 1.2.3, I was able to get logging to the console by adding the following to items the configuration section of the program's app.config file:
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter, Common.Logging">
<arg key="level" value="DEBUG" />
<arg key="showLogName" value="true" />
<arg key="showDataTime" value="true" />
<arg key="dateTimeFormat" value="yyyy/MM/dd HH:mm:ss:fff" />
</factoryAdapter>
</logging>
</common>
To log to destinations other than the console, the Common.Logging documentation has information on how to wire up log4net.
Okay. I dug through the [log4net documentation][1] and figured out a way to do it.
First of all I moved the log4net config into the App.config file (in a log4net section) and then executed
log4net.Config.XmlConfigurator.Configure();
during initialization. Now it works.
[1]: http://logging.apache.org/log4net/release/manual/configuration.html#.config Files "Apache log4net documentation"