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.
Related
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.
I'm trying to use Log4Net's Rolling File Appender to create a log file whenever there is an issue with my data. Because I work with diacritics and non-Latin characters, I want the file encoding to be in UTF-8.
Normally, if the file doesn't have any diacritics/non-Latin characters, it's encoded as ASCII. If it does log diacritics/non-Latin characters, it'll automatically encode it to UTF-8. I want it to always be in UTF-8.
My first solution was to use <encoding value="utf-8"/>. This gives me UTF-8 with BOM, which is something I don't want. So this Stackoverflow solution told me to use <encoding type="System.Text.UTF8Encoding"/>. I tried it and I would get this error:
log4net:ERROR Failed to find type [System.Text.UTF8Encoding]
System.TypeLoadException: Could not load type 'System.Text.UTF8Encoding' 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.CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
log4net:ERROR Failed to create object to set param: encoding
I tried digging around on Apache's Jira and found this post which also told me to use <encoding type="System.Text.UTF8Encoding"/>, which was the same as the Stackoverflow solution.
I then assumed maybe it's because I'm using .NET Core 2.2 and I had to try a different type. I also tried <encoding type="System.Text.Encoding.UTF8"/>, <encoding type="UTF8Encoding"/>, <encoding type="Encoding.UTF8"/> but none of these worked as well.
Here is the appender part of my XML:
<appender name="file" type="log4net.Appender.RollingFileAppender">
<threshold value="WARN" />
<file type="log4net.Util.PatternString" value="%property{LogName}" />
<appendToFile value="true" />
<!--<encoding value="utf-8"/>-->
<encoding type="System.Text.UTF8Encoding"/>
<rollingStyle value="Size" />
<maximumFileSize value="1GB" />
<staticLogFileName value="false" />
</appender>
Is there a different setting I need to do?
You get this error because the System.Text.UTF8Encoding is trying to be loaded from the log4net assembly; from the error:
Could not load type 'System.Text.UTF8Encoding' from assembly 'log4net...
For .NET Core, System.Text.UTF8Encoding is declared as
UTF8Encoding Class
Namespace: System.Text
Assemblies: System.Text.Encoding.Extensions.dll, mscorlib.dll, netstandard.dll
The encoding type setting in your log4net configuration should include one of the assemblies mentioned, e.g.:
<encoding type="System.Text.UTF8Encoding, System.Text.Encoding.Extensions" />
Having this in place results in a file without a BOM:
Whereas when using <encoding value="utf-8" /> does include a BOM:
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.
I'm having serious trouble getting log4net to work with a Windows service (multi-project solution).
I first added reference to log4net.dll to the appropriate projects via NuGet. I then created a new Log4Net.config file in the root folder of the Windows service project. In the file's properties, I set Copy to Output Directory = Copy always. Below is the config file:
<?xml version="1.0"?>
<configuration>
<log4net>
<appender name="TestServiceLog" type="log4net.Appender.RollingFileAppender">
<file value="C:\Temp\Test.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="100" />
<maximumFileSize value="10MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<priority value="ALL" />
<appender-ref ref="TestServiceLog" />
</root>
</log4net>
</configuration>
In my Windows service project, in the AssemblyInfo.cs file, I added this line:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
In my main TestService.cs class, I referenced log4net and initialized the logger like so (omitted non-logging code):
public partial class TestService : ServiceBase
{
private ILog Log { get; set; }
protected override void OnStart(string[] args)
{
Log = LogManager.GetLogger(this.GetType());
Log.Info("Hear me log.");
}
}
I then installed and ran the service. I validated the service is running normally, but no log file is created/written to. No exceptions are being thrown. Everything appears in order when debugging. I turned on log4net's internal debugging and got this:
log4net: Creating repository for assembly [TestService, Version=3.6.5570.17497, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [TestService, Version=3.6.5570.17497, Culture=neutral, PublicKeyToken=null] Loaded From [C:\ProgramData\Company\Applications\TestService\TestService\TestService.exe]
log4net: Assembly [TestService, Version=3.6.5570.17497, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [TestService, Version=3.6.5570.17497, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: repository [log4net-default-repository] already exists, using repository type [log4net.Repository.Hierarchy.Hierarchy]
The output does not seem to hint at any issues. I've also tried adding the following line to my configuration, but it didn't do the trick:
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/>
I added a WinForms project to the solution with the exact same configuration and logging worked fine, so I'm confident it's not my setup. Any other ideas on steps I may have missed?
I was able to get it to work by making the Log variable static and instantiating it like this:
private static ILog Log = LogManager.GetLogger(typeof(TestService));
I'm not quite sure why this was necessary. Hopefully someone else knows the answer.
I would like to log in the Windows Event Viewer using log4net.
I created a Console Application (.NET Framework 4), I added the reference log4net.dll, I put the following code in my App.config:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="EventLogAppender"/>
</root>
</log4net>
<startup><supportedRuntime version="v2.0.50727"/></startup>
</configuration>
And I put the following code :
class Program
{
static void Main(string[] args)
{
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error("test error", new Exception("error's exception", new Exception("error's innerexception")));
Console.Read();
}
}
It doesn't log, nothing happens, why?
Thanks
You need to call configure.
Change:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", Watch = true)]
To
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
When you specify ConfigFile = "App.config" its going to look for App.config but your filename would be [FileName].Config.
You need to call XmlConfigurator.Configure from the log4net library to initialize it. (see below)
class Program
{
static void Main(string[] args)
{
// you need this
XmlConfigurator.Configure();
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error("test error", new Exception("error's exception", new Exception("error's innerexception")));
Console.Read();
}
}
Call XmlConfigurator.Configure() at the begining of your App.
You also need to grant the user running the application rights to put data in the eventlog.
A good way to do this is with powershell, admin mode
New-EventLog EventLogName -source ApplicationName
Also, add this two parameters into the appender
<param name="LogName" value="EventLogName " />
<param name="ApplicationName" value="ApplicationName" />
Regards,