Log4Net - Log to Azure Blob Storage doesn't create logs - c#

I'm trying to log information to Azure Blob Storage using this Nuget libraries:
log4net (2.0.3)
log4net.Appender.Azure (1.3.0.19665)
My app.config file contains:
<configuration>
<configSections>
<section type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" name="log4net" />
</configSections>
<connectionStrings>
<add name="StorageConnectionString" connectionString="!##$%^&*()" />
</connectionStrings>
...
<log4net>
<appender name="AzureBlobAppender" type="log4net.Appender.AzureBlobAppender, log4net.Appender.Azure">
<param name="ContainerName" value="Logs"/>
<param name="DirectoryName" value="logs"/>
<param name="ConnectionStringName" value="StorageConnectionString" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="AzureBlobAppender" />
</root>
Appender creates storage container but it's always empty. What am I doing wrong?

If you are currently doing development on development PC, better use the cloud emulator by inserting this line as your connection string
<param name="ConnectionString" value="UseDevelopmentStorage=true" />
If you are currently testing directly into the cloud, you can put the connection string which you can get in your azure portal.

Related

log4net not appending to azure blob

I want to append logs to azure blob storage. So i added nuget package called log4net.appender.azure.
Wrote following in app.config
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="AzureBlobAppender" />
</root>
<appender name="AzureBlobAppender" type="log4net.Appender.AzureBlobAppender, log4net.Appender.Azure">
<param name="ContainerName" value="myConatiner"/>
<param name="DirectoryName" value="myFolder/logs.txt"/>
<param name="ConnectionString" value="DefaultEndpointsProtocol=https;AccountName=XXXX;AccountKey=Ngqa/KvLxL4zpxdPDv8Opm29JCOXTJuJsF8FrzFQZpWCOcoFm1EI+mvFu+7AJvaWEU3jDffYrf4rGOKPJu/ObA==;EndpointSuffix=core.windows.net" />
<param name="AsText" value="true" />
</appender>
this is how i defined connection string
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
then i wrote below in class file
log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Info("I am being tested");
but when i run program i dont see anything logged in azure blob. What am i missing?
Looks to me like your configuration is wrong. According to the examples in the README...
<appender name="AzureBlobAppender" type="log4net.Appender.AzureBlobAppender, log4net.Appender.Azure">
<param name="ContainerName" value="testloggingblob"/>
<param name="DirectoryName" value="logs"/>
<!-- You can either specify a connection string or use the ConnectionStringName property instead -->
<param name="ConnectionString" value="UseDevelopmentStorage=true"/>
<!--<param name="ConnectionStringName" value="GlobalConfigurationString" />-->
<param name="AsText" value="true" />
</appender>
myContainer should be ContainerName
MyFolder should be DirectoryName
AzureBlobConnectionString should be ConnectionStringName
Try following steps and proceed to next only if previous one is fine.
You need to check if the Logger property in debugger mode and examine the ConfigurationMessages property to see if any errors are reported.
First try adding a file appender to see if log4net is working fine or not.
<appender name="fileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log-file.txt" />
<appendToFile value="true" />
<maximumFileSize value="1000KB" />
<maxSizeRollBackups value="10" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger - %message%newline" />
</layout>
</appender>
With this, you can go to Kudo in Azure portal's webapp and see the physical file being written atleast.
Second, see if you are initializing the config properly with
log4net.Config.XmlConfigurator.Configure();
Third, check if the region of the storage account is the same as the web app or not.

How to read log4Net from web.config

I am using log4net to perform daily logging.
I realize that log4net doesn't support deleting old files in this fashion.
I am trying to write my own method to accomplish this task, however I am no sure how to read the log4net settings from the web.config file.
I've tried:
var log4NetData = ConfigurationManager.GetSection("log4net");
However I get this as my results:
The type 'System.Configuration.ConfigXmlElement' exists in both 'System.Configuration.dll' and 'System.dll'
How can I read the log4net node from my web.config?
Actually Log4Net can update the same file always (this way, there is no need to delete it and create another one).
I'm using log4Net to log always the same file n times in a hour. My configurations:
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
app.config:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="MyFileAppender" />
</root>
<appender name="MyFileAppender" type="log4net.Appender.FileAppender">
<file value="application.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%newline" />
</layout>
</appender>
</log4net>

Log4Net not working in Selenium Framework when Running SpecFlow Tests

I'm struggling with Log4Net for a good while now. I have followed this post
as an example. The difference is, in my case, I have two separate projects, one with all objects that interacts with WebDriver and web elements (FrameworkProject), second is actual test project(TestProject). I have read a lot and I'm almost sure I have set it correctly...
FrameworkProject assembly file includes [assembly: log4net.Config.XmlConfigurator(Watch = true)]
My Log4Net.config file is as follow:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="MyAppender" />
<appender-ref ref="MyFileAppender" />
</root>
<appender name="MyAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
<appender name="MyFileAppender" type="log4net.Appender.FileAppender">
<file value="application.log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
When I debug my SpecFlow tests and I reach the line XmlConfigurator.Configure(); (look example above) I'm still getting
log4net:ERROR Failed to find configuration section 'log4net' in the application's.
This drops me mad now and I have no clue of what might be wrong. Could this be the cause of running test?? Note: I have log4net set up ONLY in FrameworkProject
I have log4net set up ONLY in FrameworkProject
That's the problem. Roughly speaking, your "entry point" during test execution is your Test Project, hence it's looking for log4net configuration section inside of "entry point's" application configuration file (Test Project's app.config). Thus you should move your log4net configuration to Test Project's application configuration file.
On a second notice, it looks like you don't need to call XmlConfigurator.Configure if you use assembly level attribute: 1, 2.

Log4Net error : "Failed to find configuration section log4net"

I'm getting started with log4net.I'm working on a small console project in which i must implement this framework.
At the beginning i created a small console project to see how it works without any other code.
I managed to make it work properly.
Now i try to migrate all the code in my application and i get this error when i execute the .exe of my console application:
"ERROR failed to find configuration section "log4net" in the application's .config
file.Check your .config file for the <log4net> and <configSections> elements. The
configuration section should look like : <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler.log4net"/>
The code:
public class Program
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
ILog log = log4net.LogManager.GetLogger(typeof(Program));
...
The app.config didn't exist yet so its content is the same as the test project i did:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
<file value="D:\WEB\SAI\log\nas\log.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
</configuration>
After some searches on internet, i added:
[assembly: log4net.Config.XmlConfigurator()]
to my AssemblyInfo.cs as it was suggested but the result is still the same...
Thanks in advance for your help
ADD
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
in AsseblyInfo.cs

Error when handling NServiceBus Subscription messages

After adding logging (using log4net) to my application, it no longer handles subscription messages correctly and puts them on to the error queue. Below, some namespace names have been changed to protect the innocent.
app.config
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
<section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
<section name="MsmqSubscriptionStorageConfig" type="NServiceBus.Config.MsmqSubscriptionStorageConfig, NServiceBus.Core" />
<section name="Logging" type="NServiceBus.Config.Logging, NServiceBus.Core" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<Logging Threshold="INFO" />
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] <%X{auth}> - %m%n"/>
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] <%X{auth}> - %m%n"/>
</layout>
</appender>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] <%X{auth}> - %m%n"/>
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="logfile.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="INFO"/>
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
<MsmqTransportConfig
InputQueue="BankRequestDispatcherInputQueue_DEV2"
ErrorQueue="error"
NumberOfWorkerThreads="1"
MaxRetries="5"
/>
<UnicastBusConfig ForwardReceivedMessagesTo="auditqueue">
<MessageEndpointMappings>
<add Messages="<assembly>.BankRequestBatchClosed,<assembly>" Endpoint="ScheduledBatchAgentInputQueue_DEV2" />
</MessageEndpointMappings>
</UnicastBusConfig>
<MsmqSubscriptionStorageConfig Queue="BRDispatcher_DEV2_subscriptions" />
<!-- Neccessary for Fluent/NHibernate/SQLLite dlls -->
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<appSettings>
<add key="TempRequestFileLocation" value="c:\temp\"/>
<add key="KeepRequestFiles" value="true"/>
<add key="Environment" value="TEST"/>
</appSettings>
</configuration>
I've also changed the Endpoint config to this:
namespace myNamespace.BRDispatcher
{
/// <summary>
/// Interface tells NServiceBus which roles to setup for this class.
/// </summary>
public class BRDEndpointConfig : IConfigureThisEndpoint, IWantCustomInitialization
{
#region Class References -1-
/// <summary>
/// Reference to Logger object.
/// </summary>
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion
public void Init()
{
NServiceBus.SetLoggingLibrary.Log4Net(log4net.Config.XmlConfigurator.Configure);
Logger.Info("BankRequestDispatcher - Init()");
NServiceBus.Configure.With()
//.Log4Net()
.DefaultBuilder()
.XmlSerializer()
.MsmqSubscriptionStorage()
.MsmqTransport()
.IsTransactional(true)
.PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(false)
.LoadMessageHandlers()
.CreateBus()
.Start();
Logger.Info("BankRequestDispatcher - Init() Complete");
}
}
}
When it fires up, any subscription message received gets dumped onto the error queue and I see this in the log:
2012-02-22 17:02:48,013 [Worker.8] ERROR NServiceBus.Unicast.Transport.Msmq.MsmqTransport [(null)] - Message has failed the maximum number of times allowed, ID=94b95c71-896f-4991-b3ba-9d2068a68c63\81504.
This is due to a bug in RC4, please try it with
RC5 and see if that fixes the issue.
I have found one cause of the error/problem. If the message forwarding queue is specified in the app.config (ForwardReceivedMessagesTo) but the queue does not exist on the host machine then you will get the same error.
app.config
<UnicastBusConfig ForwardReceivedMessagesTo="auditqueue">
<MessageEndpointMappings>
<add Messages="<assembly>.BankRequestBatchClosed,<assembly>" Endpoint="ScheduledBatchAgentInputQueue_DEV2" />
</MessageEndpointMappings>
The problem was caused as only one process out of the six I've got running named the missing queue in the Test environment. Five were set to 'auditqueue' and one was 'auditqueue_test2' which, sadly was the correct name except it didn't exist and it does not auto-create the queue in this instance nor make any remark in the DEBUG statements that this is the problem.
I created a new transactional queue called 'auditqueue_test2' and it's now running. I'm going to add in the logging again and see if it works.

Categories