Log4net works when specifying logger name but not by reflection? Is this an issue? - vb.net

I am attempting to overhaul one application's (a console app written in VB.NET) logging system using log4net.
I configured log4net according to this CodeProject tutorial. After configuring, I have discovered that the following log initialization creates empty logs (the resulting folder structure is correct and it creates the correct, dated text file, but the file is empty):
Private ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(Reflection.MethodBase.GetCurrentMethod().DeclaringType)
However, if I use the following line, it logs correctly.
Private ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger("VSED")
In my main module, I'm logging an error like so:
log.Error("Test error!")
And I'm loading the assembly like so:
<Assembly: log4net.Config.XmlConfigurator(Watch:=True)>
Below is my app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="logs\" />
<datePattern value="dd.MM.yyyy'.log'" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100KB" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
</layout>
</appender>
<logger name="VSED">
<level value="DEBUG"/>
<appender-ref ref="RollingFileAppender"/>
</logger>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO"/>
<levelMax value="FATAL"/>
</filter>
</log4net>
<system.diagnostics>
<sources>
<!-- This section defines the logging configuration for My.Application.Log -->
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
<!-- Uncomment the below section to write to the Application Event Log -->
<!--<add name="EventLog"/>-->
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog"
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
initializeData="FileLogWriter"/>
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
</sharedListeners>
</system.diagnostics>
</configuration>
Is this even an issue? Will it present problems if I use this logger (explicitly stating its name) in multiple classes as opposed to the reflection?
Essentially, I'd just like to know why it's not working via the preferred method. Is my app.config incorrect? Am I doing something else incorrectly?
Thank you all!

You are only logging messages from VSED, your Reflection.MethodBase.GetCurrentMethod().DeclaringType is probably not VSED, but something.VSED. That is why your logger is not giving any output. See what the Reflection.MethodBase.GetCurrentMethod().DeclaringType is and make a logger with that name.
This will give the output from all your loggers:
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>

Related

Is there any similar kind of configure to rolingStyle="once" of log4net is available for NLog?

I am using log4net currently and on every hour log file archive is being performed.
Now I am changing log4net to NLog
Is there similar setting available in NLog Like rolingStyle="once"? which was configure setting available in log4net.
For example earlier while using log4net the files created were used to be like:
LogFile.log
LogFile.log.1 <-last archive file
Following is configuration I used in log4net and I want to use the exact configure settings so that archived file naming should remains as it was in log4net:
<appender name="Work" type="RMM.Common.Logger.LogFileRollingAppender, Common">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<dateTimeStrategy type="log4net.Appender.RollingFileAppender+UniversalDateTime" />
<file type="log4net.Util.PatternString" value="%property{EdgeAPILogPath}\WebAPI_Work.log" />
<param name="AppendToFile" value="true"/>
<rollingStyle value="Once" />
<rollingStyle value="Composite" />
<datePattern value=".yyyyMMdd-HH" />
<maxSizeRollBackups value="300" />
<maximumFileSize value="20MB" />
<Encoding value="UTF-8" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%utcdate{yyyy/MM/dd HH:mm:ss,fff} [%-5p] [%3t] %m%n" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="DEBUG" />
<levelMax value="FATAL" />
</filter>
</appender>
You can:
Use fileName="${basedir}/logs/${cached:${date:format=yyyy-MM-dd HH_mm_ss}}.log" as a way to ensure one log file per application instance.
Use archiveFileName="${archiveLogDirectory}/LogFile.log.{####}" to append numbers at the end (feel free to add or remove # as required, depending on your maxArchiveFiles).
Use archiveNumbering="Sequence" to achieve the order you want (higher numbers = newer logs).
Source: this piece of documentation and some personal experience.
Hopefully this basic example will help you getting closer to your final target:
<?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="./internal-nlog.txt"
throwExceptions="true">
<variable name="logDirectory" value="./logs"/>
<variable name="archiveLogDirectory" value="./logs/archive"/>
<targets>
<target name="errors"
xsi:type="File"
fileName="${logDirectory}/${cached:${date:format=yyyy-MM-dd HH_mm_ss}}.log"
archiveFileName="${archiveLogDirectory}/LogFile.log.{#}"
maxArchiveFiles="9"
archiveEvery="Hour"
archiveNumbering="Sequence"
/>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="errors"/>
</rules>
</nlog>
Not an expert on log4net, but it sounds like that rolingStyle="once" is the same as NLog FileTarget ArchiveOldFileOnStartup. So maybe something like this:
<nlog>
<variable name="EdgeAPILogPath" layout="${basedir}" />
<targets>
<target xsi:type="file" name="work"
fileName="${EdgeAPILogPath}/WebAPI_Work.log"
encoding="utf-8"
archiveNumbering="DateAndSequence"
archiveFileName="${EdgeAPILogPath}/WebAPI_Work.{#}.log"
archiveDateFormat="yyyyMMdd-HH"
archiveEvery="Hour"
archiveAboveSize="20000000"
archiveOldFileOnStartup="true"
maxArchiveFiles="300" />
</targets>
<rules>
<logger name="*" minLevel="Debug" writeTo="work" />
</rules>
</nlog>
See also: https://github.com/NLog/NLog/wiki/FileTarget-Archive-Examples

mvc 4 log4net not working

i am tring to use log4net for log but it is not working
My log file is created empty, without data.
There is no NHibernate data and There is no USER data.
Does anybody know why?
I am tring to do like this:
web.config
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="log4net.Config" value="log4net.config"/>
<add key="log4net.Config.Watch" value="True"/>
</appSettings>
<log4net debug="true">
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender, log4net">
<file type="log4net.Util.PatternString" value="Logs/"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<staticLogFileName value="false"/>
<datePattern value="'MyLog_'yyyyMMdd'.log'"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss.fff} %-5level: %message%newline"/>
</layout>
</appender>
<logger name="LogEmArquivo">
<level value="DEBUG"/>
<appender-ref ref="FileAppender"/>
</logger>
<logger name="NHibernate">
<level value="WARN" />
</logger>
<logger name="NHibernate.SQL">
<level value="DEBUG" />
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="LogEmArquivo" />
</root>
</log4net>
On AssemblyInfo
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
On my Helper
log4net.Config.XmlConfigurator.Configure();
log = LogManager.GetLogger("LogEmArquivo");
What is wrong? i already tried many diferent way and the only things that is happining is create the file MyLog_20170303.log with no data.
I keep my log4net config in a seaprate file
Here's my complete file that works.
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="logs/error.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level %thread %logger - %message%newline" />
</layout>
</appender>
<logger name="NHibernate">
<level value="WARN" />
</logger>
<logger name="NHibernate.SQL">
<level value="DEBUG" />
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFile" />
</root>
Have you tried a simpler log configuration with a static log file name to see if it is your log4net configuration.
You can also turn on internal debugging for log4net to verify your configuration is valid. See this answer here How to track down log4net problems
Maybe are you encountering the LOG4NET-506 issue: latest versions of log4net issue an exclusive mutex named according to file configuration property.
It does not cause issues if the file configuration actually target a file.
But in your case, it is a directory. If you have many processes trying to log to that directory, only one of them will be able of logging.
As a workaround, I have instructed log4net in my cases to log in a Logs\ sub-directory dedicated to each application. Like: file="Logs\App1\".

NServiceBus 5 with RabbitMQ transport throwing exception while enabling UnicastBus

I'm attempting to use NServiceBus with RabbitMQ in a self-hosted scenario. I've obtained the source for the NServiceBus and NServiceBus.RabbitMQ repos on github to track down the issues I've had so far, so the version I'm using is the source on their repos as of yesterday.
Here is my configuration:
var busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("RMAQueue");
busConfiguration.AssembliesToScan(typeof(RMACommand).Assembly);
busConfiguration.Conventions()
.DefiningCommandsAs(type => type.Namespace != null && type.Namespace.StartsWith("RMAInterfaces.Commands.", StringComparison.Ordinal));
busConfiguration.Conventions()
.DefiningEventsAs(type => type.Namespace != null && type.Namespace.StartsWith("RMAInterfaces.Events.", StringComparison.Ordinal));
busConfiguration.Conventions()
.DefiningMessagesAs(type => type.Namespace != null && type.Namespace.StartsWith("RMAInterfaces.Messages.", StringComparison.Ordinal));
busConfiguration.UseTransport<RabbitMQTransport>();
busConfiguration.Transactions().Disable();
busConfiguration.PurgeOnStartup(true);
busConfiguration.UseSerialization<NServiceBus.JsonSerializer>();
busConfiguration.DisableFeature<SecondLevelRetries>();
busConfiguration.DisableFeature<StorageDrivenPublishing>();
busConfiguration.DisableFeature<TimeoutManager>();
busConfiguration.UsePersistence<InMemoryPersistence>();
busConfiguration.EnableInstallers();
var bus = Bus.Create(busConfiguration);
I am getting an exception on the Bus.Create() line:
{"The given key (NServiceBus.LocalAddress) was not present in the dictionary."}
Following the stack from it leads me to see that it's failing while enabling the Feature UnicastBus.
Here is my app config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="MessageForwardingInCaseOfFaultConfig" type="NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core" />
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
<section name="AuditConfig" type="NServiceBus.Config.AuditConfig, NServiceBus.Core" />
</configSections>
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error" />
<UnicastBusConfig>
<MessageEndpointMappings>
<add Messages="RMAInterfaces" Endpoint="RMAQueue#localhost" />
</MessageEndpointMappings>
</UnicastBusConfig>
<connectionStrings>
<add name="NServiceBus/Transport" connectionString="host=localhost" />
<add name="NServiceBus/Persistence" connectionString="host=localhost"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<!--<AuditConfig
QueueName="The address to which messages received will be forwarded."
OverrideTimeToBeReceived="The time to be received set on forwarded messages, specified as a timespan see http://msdn.microsoft.com/en-us/library/vstudio/se73z7b9.aspx" />-->
<AuditConfig QueueName="audit" />
</configuration>
What am I missing to be able to self-host NServiceBus using a RabbitMQ transport?
I have just had this exact problem, and the fix is as Andreas suggested. I added the following to my configuration code...
configuration.AssembliesToScan(typeof(NServiceBus.Transports.RabbitMQ.IManageRabbitMqConnections).Assembly);
With that in place the error message regarding NServiceBus.LocalAddress no longer shows up. My complete setup is as follows (code, then config file)
[TestMethod]
public void TestMethod1()
{
LogManager.Use<Log4NetFactory>();
var configuration = new BusConfiguration();
configuration.AssembliesToScan(typeof(NServiceBus.Transports.RabbitMQ.IManageRabbitMqConnections).Assembly);
configuration.UseSerialization<JsonSerializer>();
configuration.UseTransport<NServiceBus.RabbitMQTransport>();
configuration.UsePersistence<InMemoryPersistence>();
var bus = global::NServiceBus.Bus.Create(configuration);
bus.Start();
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="MessageForwardingInCaseOfFaultConfig" type="NServiceBus.Config.MessageForwardingInCaseOfFaultConfig, NServiceBus.Core" />
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, Log4net" />
</configSections>
<MessageForwardingInCaseOfFaultConfig ErrorQueue="error" />
<connectionStrings>
<add name="NServiceBus/Transport" connectionString="host=localhost" />
</connectionStrings>
<UnicastBusConfig>
<MessageEndpointMappings>
<add Assembly="TestNSBCreation" Endpoint="TestNSBCreation" />
</MessageEndpointMappings>
</UnicastBusConfig>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="ContactAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="C:\logs\TestNSBCreation.log" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
The Morgan Skinner's answer helped figure out the actual root cause of my issue. I've added the suggested code configuration.AssembliesToScan(typeof(NServiceBus.Transports.RabbitMQ.IManageRabbitMqConnections).Assembly);
After that the exception was more descriptive. NServiceBus.RabbitMQ package automatically downloads RabbitMQ.Client package. The later package was updated to the latest available on nuget and this created version conflict between what expected by NserviceBus.RabbitMQ and what was actually installed. I've removed both packages completely and reinstalled NserviceBus.RabbitMQ package and the error went away. The ..assembliesToScan... line was no longer needed either.

log4net not inserting into database but working fine for file

I am using this code in WCF application in VS 2012, SQL Express is 2008 R2.
I have included the fileAppendor and Database Appendor, File Appender works fine but its not inserting data into the database.
I have verified the same connection string its working fine and inserting records in to the table.
Also I have set the buffer value to 1, still no luck
<bufferSize value="1" />
This is my config file
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="server=(local)\\SQLEXPRESS;database=Log_DB;Integrated Security=SSPI;Connection Timeout=360;" />
<connectionString value="data source=[(local)\\SQLEXPRESS];initial catalog=[Log_DB];integrated security=SSPI" />
<commandText value="INSERT INTO [Error_Log] ([Date_time] ) VALUES (#Date_time)" />
<parameter>
<parameterName value="#Date_time" />
<dbType value="DateTime" />
<!--<layout type="log4net.Layout.RawTimeStampLayout" />-->
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</parameter>
</appender>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="log-file.txt"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] ID=%property{EventID} - %message%newline" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
...
</configuration>
Do I am missing any other stuff?
Also I am not getting any information by setting Internal.Debug to true.
How to get internal debug details of log4net?
Finaly I got the answer for this, I am sharing here since it may help others.
Need to use the System/Machine Name instead of (local) in the Connection string. Even with the dotnet application (local) works but for log4net need to use the System name.

The server committed a protocol violation. Section=ResponseStatusLine MVC4

I have a peculiar problem.
I make a HttpWebRequest against a Url and my tests from my test library works as they should.
Then I head over to my mvc4 web application and try to call the same piece of code that I call from my test. And it fails.
Now, I know there is are some things that can go wrong here. But really, not that many things should. I know for a fact it has something to do with the web.config because whenever I change the web.config in my mvc4 application to app.config, with the exact same values, it works.
The target framework is .NET 4.5.
Here is my web.config file
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true"/>
</settings>
</system.net>
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5"/>
</system.web>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<datePattern value="dd.MM.yyyy'.log'" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="..\..\logs\" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="false" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
</configuration>
Okay, it had nothing to do with my config...DoH!
It has everything to do with the way I call the piece of code I knew was working. Since it's an async method I am calling, I need to call it from an async method, so the thread is not hanging somewhere else. Task.Run(()=> MyMethod()) did the trick.