Getting an error during initialization of the Google Stack Driver appender - log4net

Have a google stack driver appender in my log4net configuration but during initialization I get an error about not being able to cast as an IAppender. Here's the reference for the appender.
<appender name="CloudLogger" type="Google.Cloud.Logging.Log4Net.GoogleStackdriverAppender,Google.Cloud.Logging.Log4Net">
<layout type="log4net.Layout.SerializedLayout, log4net.Ext.Json">
<decorator type="log4net.Layout.Decorators.StandardTypesDecorator, log4net.Ext.Json" />
<member value="date:date" />
<member value="level:level" />
<member value="logger:logger" />
<member value="message:messageObject" />
<member value="exception:exception" />
</layout>
<projectId value="playground" />
<logId value="test-api" />
</appender>
Error output.
log4net: Loading Appender [CloudLogger] type: [Google.Cloud.Logging.Log4Net.GoogleStackdriverAppender,Google.Cloud.Logging.Log4Net]
log4net:ERROR Could not create Appender [CloudLogger] of type [Google.Cloud.Logging.Log4Net.GoogleStackdriverAppender,Google.Cloud.Logging.Log4Net]. Reported error follows.
System.InvalidCastException: Unable to cast object of type 'Google.Cloud.Logging.Log4Net.GoogleStackdriverAppender' to type 'log4net.Appender.IAppender'.
at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)
log4net:ERROR Appender named [CloudLogger] not found.

It is working now. Appeared to be a version mismatch between log4net versions in different projects between the solution.

Related

No EventLogAppender in Log4Net 2.0.14

I'm trying to configure an EventLogAppender in a .Net 6.0 console app, I'm using Log4Net 2.0.14 and I getting the following Exception...
log4net:ERROR Could not create Appender [EventLogAppender] of type [log4net.Appender.EventLogAppender]. Reported error follows.
System.TypeLoadException: Could not load type [log4net.Appender.EventLogAppender]. Tried assembly [log4net, Version=2.0.14.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a] and all loaded assemblies
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.
This is my appender:
<log4net>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<applicationName value="Application" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="ERROR"/>
<appender-ref ref="EventLogAppender"/>
</root>
</log4net>
See the official EventLogAppender doc:
Please note that this appender is not natively available in log4net for dotnet standard, as it would bring in windows dependencies for non-windows consumers. Please see https://www.nuget.org/packages/log4net.appenders.netcore for an alternative if you still require EventLog logging for netstandard targets
So use the Nuget package "Log4Net.Appenders.NetCore".
The appender declaration is slightly different:
<appender name="EventLogAppender" type="Log4Net.Appenders.NetCore.EventLogAppender,Log4Net.Appenders.NetCore">

log4net getting ? instead of method name randomly

I have .net 4.5.2 applications where i am using log4net 1.2.15.0 version (even in 2.0.8)
I have random behavior that in method name i am getting ? in my text file
I have tried both %M or %method and this behavior reoccur randomly
My Appender setting is
<appender name="MyApp" type="log4net.Appender.RollingFileAppender" >
<file value="..\\Logs\\MyApp.txt" />
<appendToFile value="true" />
<datePattern value="yyyyMMdd" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<filter type="log4net.Filter.LevelRangeFilter">
<acceptOnMatch value="true" />
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{yyyy-MM-dd HH:mm:ss.fff} %10p [%2t] %5c{1}.%method - %m%n" />
<!-- <conversionPattern value="%d{yyyy-MM-dd HH:mm:ss.fff} %10p [%2t] %5c{1}.%M - %m%n" /> -->
</layout>
</appender>
Sample output text in log file is
2017-08-22 07:13:08.668 INFO [ 4] ServicesManager.? - Socket connectivity Reply from aaa, is True at socket connectivity attempt 1
Please help me in finding what's the problem
This is documented behaviour:
The following patterns %type %file %line %method %location %class %C %F %L %l %M all generate caller location information. Location information uses the System.Diagnostics.StackTrace class to generate a call stack. The caller's information is then extracted from this stack.
StackTrace information will be most informative with Debug build configurations. By default, Debug builds include debug symbols, while Release builds do not. The debug symbols contain most of the file, method name, line number, and column information used in constructing StackFrame and StackTrace objects. StackTrace might not report as many method calls as expected, due to code transformations that occur during optimization.
This means that in a Release build the caller information may be incomplete or may not exist at all! Therefore caller location information cannot be relied upon in a Release build.
The documentation also says:
Generating caller location information is extremely slow. Its use should be avoided unless execution speed is not an issue.

log4net RavenDB Appender not writing logs

I've found the following project (https://github.com/antonsamarsky/log4net.Raven) that enabled a log4net appender to RavenDb.
I've imported the nuget package and configured my App.config file like this:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<connectionStrings>
<add name="RavenLogs" connectionString="Url = http://localhost:8080; DefaultDatabase=MyLog"/>
</connectionStrings>
<log4net>
<appender name="RavenAppender" type="log4net.Raven.RavenAppender, log4net.Raven">
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
<connectionString value="RavenLogs"/>
<maxNumberOfRequestsPerSession value="100"/>
<bufferSize value="50" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ERROR" />
</evaluator>
</appender>
</log4net>
<root>
<level value="INFO" />
<appender-ref ref="RavenAppender" />
</root>
there wasn't any documentation other than importing the nuget and the configuration on GitGub. When I run my program I don't get any errors, but I don't see anything on RavenDb server either.
I've even tried creating MyLog database myself on RavenDb, in case the appender doesn't automatically creates it - still nothing.
Anyone knows how to use this appender?
You have a LevelEvaluator in your configuration, which will only trigger if the log event has a level equal to or over the configured level. Does an error even occur in the program?
When setting up log4net, set up a simple FileAppender alongside your working configuration, this way you can easily see what data you should/want to be seeing in your true logs. For all you know you forgot to configure the log4net framework and the FileAppender will act as an easy way to see if there is a problem. Remove filters and evaluators from your RavenDB appender, and add them back after checking if everything works
Jeroen's comment about setting up the internal debugger is another way to do it but may not be necessary for configuration problems.

log4j: Unrecognized element rollingPolicy

I have an app running on Tomcat 7.0.2 and using log4j for logging.
Shortly after tomcat start the following messages appear in catalina.out:
INFO: Initializing log4j from [file:///export0/home/tomcat/appconf/log4j.xml]
log4j:WARN Unrecognized element rollingPolicy
log4j:WARN Please set a rolling policy for the RollingFileAppender named 'PERFFILE'
log4j:WARN Unrecognized element rollingPolicy
log4j:WARN Please set a rolling policy for the RollingFileAppender named 'FILE'
and when my actual log messages should print, I see the following:
log4j:ERROR No output stream or file set for the appender named [FILE].
log4j:ERROR No output stream or file set for the appender named [PERFFILE].
These two appenders are defined like this:
<appender name="FILE" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="Append" value="true" />
<param name="File" value="${catalina.base}/logs/server.log" />
<rollingPolicy class="com.myapp.logging.AgingTimeBasedRollingFilePolicy">
<param name="fileNamePattern" value="${catalina.base}/logs/archive/server.%d{yyyy-MM-dd}.log.gz" />
<param name="keepFilesForDays" value="30" />
</rollingPolicy>
<layout class="com.myapp.logging.jboss.WebappAwarePattern">
<param name="ConversionPattern" value="%d{ISO8601}{${server.localTimezone}} %p [%X{webapp}:%c{2}] %m%n" />
</layout>
</appender>
<appender name="PERFFILE" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="Append" value="true" />
<param name="File" value="${catalina.base}/logs/performance.log" />
<rollingPolicy class="com.myapp.logging.AgingTimeBasedRollingFilePolicy">
<param name="fileNamePattern" value="${catalina.base}/logs/archive/performance.%d{yyyy-MM-dd}.log.gz" />
<param name="keepFilesForDays" value="30" />
</rollingPolicy>
<layout class="com.myapp.logging.jboss.WebappAwarePattern">
<param name="ConversionPattern" value="%d{ISO8601}{${server.localTimezone}} %p [%X{webapp}:%c{2}] %throwable{0} %m%n" />
</layout>
</appender>
I've been having a hard time trying to fugure out why this errors occur but got no result (probably my log4j.xml can not be parsed correctly)
So any ideas why this happens would be highly appreciated.
Thanks in advance!
Taken from the Appenders documentation page:
Parameter Name Type Description
policy TriggeringPolicy The policy to use to determine
if a rollover should occur.
I think you should replace rollingPolicy with policy. This probably depends on whether you are using 2.0 or 1.2; I dont see policy in the 1.2 version.
I think you set the wrong class or your custom class for the rollingPolicy class on your two appenders that maybe not exist or not recognize by log4j
<rollingPolicy class="com.myapp.logging.AgingTimeBasedRollingFilePolicy">
So change both appenders class with:
<rollingPolicy class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
that have been provided by apache-log4j-extras jar

log4net not logging from Autocad Plugin on deployment

I am developing an AutoCAD 2012 plugin using .net API"s of autocad. The Autocad plugin's are dll which are loaded into the Autocad runtime when the Autocad is started. I have been able to successfully log from log4net using Visual Studio developement environment. However, when I run the plugin outside of Visual Studio, that is when I deploy my plugin, the log4net does not log any messages or even create a log file. Here is the logging related code and the configuration file.
log4net_autocad.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/>
</configSections>
<log4net>
<appender name="AutocadRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="${NIRVANA_SOFTWARE_INSTALL_PATH}Relay_Manager_Autocad.log"/>
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="0" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p [%C.%M] %m%n"/>
</layout>
</appender>
<logger name="AutocadFile">
<level value="All"/>
<appender-ref ref="AutocadRollingFileAppender"/>
</logger>
</log4net>
</configuration>
myPlugin.cs: Code to congifure logging
public class MyPlugin : IExtensionApplication {
private static log4net.ILog log;
void IExtensionApplication.Initialize() {
...
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo("log4net_autocad.config"));
log = log4net.LogManager.GetLogger("AutocadFile");
}
void IExtensionApplication.Initialize() will execute when the Autocad is started. Couple of things that I have checked:
Checked that the Autocad Plugin is properly loaded in Autocad, which
means that log4net initialization code has run.
Checked that log4net config file (log4net_autocad.config) is copied
in the bin directory of the deployed application
The strange thing is that when I load the plugin in developement environment(VS 2010), the plugin logs properly. So why is the log4net not logging (or even creating a log file) in deployment.
EDIT:
I checked some additional stuff
In the plugin just before I log, I checked following through alert dialogs.
The log.Logger.Name properly returns the name of the logger that I am using.
log.Logger.IsEnabledFor(log4net.Core.Level.All) returns false, even though I have configured Level Value=All in the config file.
EDIT-2
I tried to define config file as explained in the referring url of the answer. I am quoting the approach as outlined in the document.
2.] Application Configuration File: [AppName].exe.config, [AppName].dll.config
The application-level configuration, [AppName].exe.config or [AppName].dll.config, is where
most of this document will spend its time. This configuration file will contain all applicationlevel settings and can even be used to define the use of and default values for settings
associated with the Roaming-User and Local-User configuration files. These files are
typically stored in the same directory as the application executable, but can be placed
elsewhere if necessary. There will be much more discussion on this to come.
The above approach suits my application, but I still can't get the logger to log anything at all.I defined a log4net config file with name RelayAnalysis_Autocad.dll.config and supplied it to the log4net for configuration. I think there is something else to it that I am not able to understand. I have started doubting whether we can log using log4net from autocad plugin?
I also removed the environment path and hardcoded it so as to eliminate any issues regarding the reading of environment variable. Still no luck.
On deploy, you should store the plugin configuration in one of the default config files:
User.config
acad.exe.config
machine.config
Probably, the User.config is the best file to carefully change during setup. Moreover you should design and code the changes so that they can be reverted on uninstall.
Doublecheck that you have properly replaced the ${NIRVANA_SOFTWARE_INSTALL_PATH} during setup and that the folder has proper permissions.
Furthermore, I would try to either add to the AssemblyInfo.cs the following line
[assembly: log4net.Config.XmlConfigurator(ConfigFile="AbsolutePathToTheConfig")]
(in which case you shouldn't call XmlConfigurator.Configure) or use an absolute path in the call to
log4net.Config.XmlConfigurator.Configure(new FileInfo("AbsolutePathToTheConfig"));
Finally, note that the log4net documentation about XmlConfigurator.Configure states that the configuration file used can be a XML not matching the .NET config rules.
The configuration file must be valid XML. It must contain at least one element called log4net that holds the log4net configuration data.
Thus, in the log4net_autocad.config file you can skip the <configuration> element:
<log4net>
<appender name="AutocadRollingFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Absolute\Path\To\Relay_Manager_Autocad.log"/>
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="0" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p [%C.%M] %m%n"/>
</layout>
</appender>
<logger name="AutocadFile">
<level value="All"/>
<appender-ref ref="AutocadRollingFileAppender"/>
</logger>
</log4net>

Resources