rebus log4net has wrong date - c#

When I throw an exception in a handler for a message type, then the exception is logged with UTCDate, however this should be the computer date.
The weird thing is that it logs it correctly and then logs in wrong, so multiple log messages are added to the file. This is not needed!
The correct time in the log below is 2014-02-18 14:... and the wrong time is 18-02-2014 13:....
I do not need the log with the wrong time
Log:
2014-02-18 14:08:43,616 WARN Rebus 1 worker 1 Rebus.Bus.RebusBus - User exception in Rebus 1 worker 1: System.IO.IOException: Error writing to file ---> System.UnauthorizedAccessException: Access to the path 'X' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at X.Y(X X, X X, X X) in X:line 538
--- End of inner exception stack trace ---
at X.Y(X X, X X, X X) in X:line 546
at Rebus.Bus.Dispatcher.DispatchToHandler[TMessage](TMessage message, IHandleMessages`1 handler)
18-02-2014 13:08:43:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.IOException: Error writing to file ---> System.UnauthorizedAccessException: Access to the path 'X' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at X.Y(X X, X X, X X) in X:line 538
--- End of inner exception stack trace ---
at X.Y(X X, X X, X X) in X:line 546
at Rebus.Bus.Dispatcher.DispatchToHandler[TMessage](TMessage message, IHandleMessages`1 handler)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at Rebus.Bus.Dispatcher.Dispatch[TMessage](TMessage message)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Rebus.Bus.Worker.DoTry()
at Rebus.Bus.Worker.TryProcessIncomingMessage()
at Rebus.Bus.Worker.MainLoop()
Log4NetConfiguration:
<log4net>
<logger name="NHibernate">
<level value="ERROR" />
</logger>
<logger name="NHibernate.SQL">
<level value="ERROR" />
</logger>
<!-- The DebugFileAppender writes all messages to a log file-->
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="X" />
<appendToFile value="true" />
<maximumFileSize value="10000KB" />
<maxSizeRollBackups value="10" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %thread %logger - %message%newline" />
</layout>
</appender>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<forecolor value="Red" />
</mapping>
<mapping>
<level value="DEBUG" />
<forecolor value="Yellow" />
</mapping>
<mapping>
<level value="INFO" />
<forecolor value="White" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionpattern value="%date [%thread] %logger %-5level - %message%newline" />
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<!--<param name="LogName" value="X" />-->
<param name="ApplicationName" value="X" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %newline %type %newline %method %newline %message %newline %exception" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="WARN" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<!-- add other appenders here and the log messages will be sent to every listed appender -->
<appender-ref ref="EventLogAppender" />
<appender-ref ref="RollingFile" />
<appender-ref ref="ColoredConsoleAppender" />
</root>
</log4net>
Rebus logging setup:
var rebusConfigurer = Configure.With(new WindsorContainerAdapter(container))
.Logging(l => l.Log4Net()).Transport(t => t.UseMsmqAndGetInputQueueNameFromAppConfig())
.MessageOwnership(o => o.FromRebusConfigurationSection())
.X(s => s.StoreInSqlServer(() => (SqlConnection)container.Resolve<ISession>().Connection, "X", "X"))
.SpecifyOrderOfHandlers(s => s.Use(new MyMessageHandlerInspector()));
Exception being caught by Rebus
throw new IOException("Error writing to file", exception);
How do I prevent or configure how rebus logs this? As you can see in the log, some of the rebus logging is ok, and other is not.

The thing is that Rebus keeps track of caught exceptions including their timestamps between retries, which is dnoe by keeping a list of Timed<Exception> instances around - and it used to initialize each with DateTime.UtcNow.
I've changed it in Rebus 0.57.0 though to use DateTime.Now, because I agree with you that it doesn't make sense - or at least it looks pretty weird alongside Log4Net's timestamps :)

Related

Exception in internal-nlog when returning a File(MemoryStream) from a controller action

After updating my app to .net core 3.1, I started noticing new logs in the internal-nlog files such as:
2020-07-23 23:49:07.0858 Warn Failed to get property value for object: System.IO.MemoryStream Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> System.InvalidOperationException: Timeouts are not supported on this stream.
at System.IO.Stream.get_ReadTimeout()
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at NLog.Internal.ObjectReflectionCache.ObjectPropertyList.Enumerator.get_Current()
The app itself is functional and working, it is just that this log pops up.
I managed to track it down to an nlog update from 4.5.6 to 4.7.2. After some playing around I came to the conclusion that the log entry does not appear on nlog 4.5.11, and it starts to appear on nlog 4.6.0
The log entry is written (twice) after exiting a particular controller action. It can be summed up as:
var stream = generateMemoryStream();
return this.File(stream,mediatype,somefilename);
The possibly relevant nlog config chunk is below
<target xsi:type="File" name="jsonFile" fileName="Logs\nlog-json-${shortdate}.log" >
<layout type="JsonLayout">
<attribute name="time" layout="${longdate}" />
<attribute name="level" layout="${level}"/>
<attribute name="message" layout="${message}"/>
<attribute name="templatedMessage" layout="${message:raw=true}" />
<attribute name="exception" encode="false">
<layout type='JsonLayout'>
<attribute name="message" layout="${exception:format=message}" />
<attribute name="type" layout="${exception:format=shortType}" />
<attribute name="stackTrace" layout="${exception:format=stackTrace}" />
<attribute name="data" layout="${exception:format=Data}" />
</layout>
</attribute>
<attribute name="eventProperties" encode="false">
<layout type='JsonLayout' includeAllProperties="true" maxRecursionLimit="2"/>
</attribute>
</layout>
</target>
Has anyone else noticed this behaviour? Or can point me in a certain direction?
Until NLog 4.7.3 is released then you can prevent reflection of Stream-objects with the following code:
NLog.LogManager.Setup().SetupSerialization(s =>
s.RegisterObjectTransformation<System.IO.Stream>(o => o.ToString()));
This will remove the noise coming from NLog trying to perform property-reflection of Stream-objects.

How to solve log4net:ERROR Could not create Appender [aiAppender] of type

I have .net core 3.1 console application which is referring to a .net class library project.
I am getting the below exception.
log4net:ERROR Could not create Appender [aiAppender] of type
[Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender,
Microsoft.ApplicationInsights.Log4NetAppender]. Reported error
follows. System.IO.FileNotFoundException: Could not load file or
assembly 'Microsoft.ApplicationInsights.Log4NetAppender,
Culture=neutral, PublicKeyToken=null'. The system cannot find the file
specified. File name: 'Microsoft.ApplicationInsights.Log4NetAppender,
Culture=neutral, PublicKeyToken=null' at
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean
throwOnError, Boolean ignoreCase, StackCrawlMarkHandle stackMark,
ObjectHandleOnStack assemblyLoadContext, Boolean
loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack
keepalive) at System.RuntimeTypeHandle.GetTypeByName(String name,
Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark,
AssemblyLoadContext assemblyLoadContext, Boolean
loadTypeFromPartialName) at System.RuntimeType.GetType(String
typeName, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark&
stackMark) at System.Type.GetType(String typeName, Boolean
throwOnError, Boolean ignoreCase) at
log4net.Util.SystemInfo.GetTypeFromString(Assembly relativeAssembly,
String typeName, Boolean throwOnError, Boolean ignoreCase) at
log4net.Util.SystemInfo.GetTypeFromString(String typeName, Boolean
throwOnError, Boolean ignoreCase) at
log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement
appenderElement)
log4net:ERROR Appender named [aiAppender] not found.
App.config:
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="aiAppender" />
</root>
<appender name="aiAppender" type="Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender, Microsoft.ApplicationInsights.Log4NetAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message%newline" />
</layout>
</appender>
</log4net>
to solve this issue I tried to add a package from NuGet package manager Microsoft.ApplicationInsights.Log4NetAppender, but I am getting the below error while adding this package.
Failed to fetch results from V2 feed at
'http://fxnugetserver.azurewebsites.net/nuget/FindPackagesById()?id='runtime.ubuntu.14.04-x64.runtime.native.System.Security.Cryptography.OpenSsl'&semVerLevel=2.0.0'
with following message : The specified path, file name, or both are
too long. The fully qualified file name must be less than 260
characters, and the directory name must be less than 248 characters.
The specified path, file name, or both are too long. The fully
qualified file name must be less than 260 characters, and the
directory name must be less than 248 characters.
But my project path is just J:\fx-core
Please help me to solve this issue
I just added log4net package to both the projects and error is gone now.
Try reinstalling log4net nuget package, if that doesn't help check in folder directory-bin-Debug if you are missing log4net and log4net.dll files.

C# windows event viewer

I want to log the errors from my C# app in Windows Event Viewer using log4net with the EventLogAppender (the errors must be logged under the Application log)
I have a log4net.config class with this code
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />
</configSections>
<log4net>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<applicationName value="MySource" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="{%level} {%date} – %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="EventLogAppender" />
</root>
</log4net>
</configuration>
In AssemblyInfo I added the following line
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch=true)]
Then in my Program class
class Program
{
static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
string name=null;
try
{
Console.WriteLine("Name : " + name.ToString());
}
catch (NullReferenceException nullException)
{
log.Error("Name is NULL", nullException);
}
}
}
I have to mention that I used power shell to create a new EventLog called "MySource"
The problem is that I receive the following error:
log4net:ERROR Could not create Appender [EventLogAppender] of type [log4net.Appender.EventLogAppender]. Reported error follows.
System.TypeLoadException: Could not load type 'log4net.Appender.EventLogAppender' from assembly 'log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a'.
at System.Reflection.RuntimeAssembly.GetType(QCallAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive, ObjectHandleOnStack assemblyLoadContext)
at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
at log4net.Util.SystemInfo.GetTypeFromString(Assembly relativeAssembly, String typeName, Boolean throwOnError, Boolean ignoreCase)
at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)
log4net:ERROR Appender named [EventLogAppender] not found.
Latest version of log4net (2.0.8 as of today) is implementing .net standard 1.3: https://logging.apache.org/log4net/release/release-notes.html.
In .net standard 1.3 EventLogAppender is not supported: https://logging.apache.org/log4net/release/framework-support.html#netstandard-1.3
If you want to use EventLogAppender, you will have to switch to .net framework.

SmtpAppender missing in log4net 2.0.8 nuget?

I created a console app for .NET Core 2.0 and installed a log4net 2.0.8 nuget
I want to use the SmtpAppender but it does not exist in the library
This is my log4net configuration
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="test#test.com" />
<from value="test#test.com" />
<subject type="log4net.Util.PatternString" value="Message logged" />
<smtpHost value="localhost" />
<authentication value="None" />
<port value="25" />
<bufferSize value="1" />
<lossy value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%utcdate [%level] - %message%newline%exception" />
</layout>
</appender>
<root>
<level value="All" />
<appender-ref ref="SmtpAppender" />
</root>
</log4net>
And this is Program.cs
namespace Log4NetTest
{
public class Program
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead("log4net.config"));
var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
typeof(log4net.Repository.Hierarchy.Hierarchy));
log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
log.Info("TEST INFO LOG");
}
}
}
When I run the application, I expect an email to be sent to localhost with the message "TEST INFO LOG" but instead log4net outputs this to the console:
log4net:ERROR Could not create Appender [SmtpAppender] of type [log4net.Appender.SmtpAppender]. Reported error follows.
System.TypeLoadException: Could not load type 'log4net.Appender.SmtpAppender' from assembly 'log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a'.
at System.Reflection.RuntimeAssembly.GetType(RuntimeAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive)
at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)
log4net:ERROR Appender named [SmtpAppender] not found.
Press any key to continue . . .
SmtpAppender type does not even appear in the object browser. There's SmtpPickupDirAppender but that's not what I want to use.
Do I miss something? After some search I did not find anyone ever had this problem, log4net 2.0.8 is 7 months old and downloaded milion times.
Since the built in SmtpAppender is not supported for .Net Core, you can quite easily create your own custom SMTP appender for Log4Net. Take a look at
https://github.com/HatfieldConsultants/Log4Net.Core.CustomAppenders
as an example of how a very basic SMTP appender can be built.

NLog exception when writing to a database

I have NLog 4.2.3 configured to write to a database and a text file using the following 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" internalLogLevel="Error" internalLogFile="C:/tmp/NLog.txt">
<targets>
<target name="database" xsi:type="Database" dbProvider="Npgsql.NpgsqlFactory,Npgsql,Version=2.0.12.00,Culture=neutral,PublicKeyToken=5d8b90d52f46fda7" connectionString="Server=xxx.xxx.xxx.xxx;Port=5432;User Id=userid;Password=password;Database=testdb;">
<commandText>INSERT INTO invoice_log (message, level, logger) VALUES (#msg, #level, #logger)</commandText>
<parameter name="#msg" layout="${message}" />
<parameter name="#level" layout="${level}" />
<parameter name="#logger" layout="${logger}" />
</target>
<target name="log" xsi:type="File" layout="${longdate} | ${logger} | ${level:uppercase=true}: ${message}" fileName="${basedir}/Logs.txt" keepFileOpen="false" encoding="iso-8859-2" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="database" />
<logger name="*" minlevel="Trace" writeTo="log" />
</rules>
</nlog>
I'm trying to log a simple Info message. It logs correctly to the text file, but it fails for the database and I get the following error in the NLog internal log file:
Error Error when writing to database System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Activator.CreateInstance(Type type)
at NLog.Targets.DatabaseTarget.OpenConnection(String connectionString)
at NLog.Targets.DatabaseTarget.EnsureConnectionOpen(String connectionString)
at NLog.Targets.DatabaseTarget.WriteEventToDatabase(LogEventInfo logEvent)
at NLog.Targets.DatabaseTarget.Write(LogEventInfo logEvent)
I have looked at configs from other similar questions (NLog is not writing to database table, NLog to PostgreSQL connection), but I can't see what is missing from mine?
According to the nlog docs, dbProvider is an invariant name for a factory registered in a config file OR the fully qualified name of a type that implements IDbConnection. Npgsql.NpgsqlConnection implements the required interface and has a parameterless contructor. NpgsqlFactory does not and it does not have a parameterless constructor (the cause of the error).

Categories

Resources