Configuring log4net to connect to an initially offline database engine - c#

I have a windows service set up with log4net, logging to a file and a SQL Server database.
During initilization, I do my XmlConfigurator.Configure() call. Early on in the service, I execute some logging. It's a windows service, so it's starting up around the same time that SQLServer starts up. My service is doing logging before the DB is up. When the DB is up, log4net has given up logging to the DB and it fails to proceed.
I'd like for log4net ADONetAppender to start appending to the log database as soon as the database is online. Is this possible? Can I just call XmlConfigurator.Configure() when the DB is back online?
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="C:\Logs\MyLog.txt" />
<param name="AppendToFile" value="true" />
<param name="ImmediateFlush" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="Header" value="[Header]
" />
<param name="Footer" value="[Footer]
" />
<param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
<appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
<bufferSize value="1"/>
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<connectionString value="Data Source=localhost\SQLEXPRESS;Initial Catalog=tests_db;Integrated Security=True"/>
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES
(#log_date, #thread, #log_level, #logger, #message, #exception)"
/>
<parameter>
<parameterName value="#log_date"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.RawUtcTimeStampLayout"/>
</parameter>
<parameter>
<parameterName value="#thread"/>
<dbType value="String"/>
<size value="32"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%t"/>
</layout>
</parameter>
<parameter>
<parameterName value="#log_level"/>
<dbType value="String"/>
<size value="512"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%p"/>
</layout>
</parameter>
<parameter>
<parameterName value="#logger"/>
<dbType value="String"/>
<size value="512"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%c"/>
</layout>
</parameter>
<parameter>
<parameterName value="#message"/>
<dbType value="String"/>
<size value="4000"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%m"/>
</layout>
</parameter>
<parameter>
<parameterName value="#exception"/>
<dbType value="String"/>
<size value="2000"/>
<layout type="log4net.Layout.ExceptionLayout"/>
</parameter>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="ADONetAppender"/>
</root>
</log4net>

Related

Log4net with MySql not logging

In properties of log I noticied all the level logs (IsErrorEnabled) have value false, in log.Logger.Repository.Configured has value false.
I dont know if LogManager can't find the log4net node in app.config or there's something wrong in xml.
I'm trying:
[TestMethod]
public void TestLog()
{
ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
log.Debug("teste");
}
Before, I used Sql and all worked perfectly, but since I changed to MySql the logs dont work anymore.
Can anyone help me?
This is my XML
<log4net>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" />
<connectionString value="Server=localserver;Database=DataBaseName;Uid=user;Pwd=pass;" />
<commandText value="INSERT INTO LogServico ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception);" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
I'm find the errors.
Thanks [stuartd] for reply.
First I forget the XmlConfigurator.Configure()
After I enable the log4net debug by:
<add key="log4net.Internal.Debug" value="true"/>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
So Log4net logged the error:
The command text was wrong
"INSERT INTO LogServico ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception);"
The rigth way is:
"INSERT INTO LogServico (Date,Thread,Level,Logger,Message,Exception) VALUES (?log_date, ?thread, ?log_level, ?logger, ?message, ?exception);"
And change all parameter name to ?name like:
<parameterName value="?log_date" />
So my final app.config is:
<log4net>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" />
<connectionString value="Server=127.0.0.1;Database=dbname;Uid=user;Pwd=pass;" />
<commandText value="INSERT INTO LogServico (Date,Thread,Level,Logger,Message,Exception) VALUES (?log_date, ?thread, ?log_level, ?logger, ?message, ?exception);" />
<parameter>
<parameterName value="?log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="?thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="?log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="?logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="?message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="?exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
My funcional method test:
[TestMethod]
public void TestLog()
{
log4net.Config.XmlConfigurator.Configure();
ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
log.Error("test", new Exception("test"));
}
It's important remember all that is to log in mysql. In Sql the command text can use [namecolumn] and the parameter has #nameparameter
There are a number of possible reasons:
Your log4net config file is not set to "Copy Local" on build
You are not initialising log4net (ie calling XmlConfigurator.Configure or using an assembly attribute).
Your config is invalid.
As you say this worked previously, then it seems probable that it is 3, and your config is invalid.

Log4Net error : “Failed to find configuration section log4net” AdoNetAppender

I made a new project only for testing. I am trying to use Log4Net to write into my DB. But I am getting this error.I think something in my config is missing.
log4net: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" />
AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Logging.config", Watch = true)]
Logging.config
<!--This is the root of your config file-->
<configuration>
<!-- Level 0 -->
<!--This specifies what the section name is-->
<configSections>
<!-- Level 1 -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<!-- Level 2 -->
</configSections>
<log4net>
<!-- Level 1 -->
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=xxx;initial Catalog=xxx; Integrated Security=True;"/>
<commandText value="INSERT INTO dbo.Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception)" />
<parameter>
<parameterName value="#log_date"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.RawTimeStampLayout"/>
</parameter>
<parameter>
<parameterName value="#thread"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread"/>
</layout>
</parameter>
<parameter>
<parameterName value="#log_level"/>
<dbType value="String"/>
<size value="50"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level"/>
</layout>
</parameter>
<parameter>
<parameterName value="#logger"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger"/>
</layout>
</parameter>
<parameter>
<parameterName value="#message"/>
<dbType value="String"/>
<size value="4000"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message"/>
</layout>
</parameter>
<parameter>
<parameterName value="#exception"/>
<dbType value="String"/>
<size value="2000"/>
<layout type="log4net.Layout.ExceptionLayout"/>
</parameter>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="AdoNetAppender"/>
</root>
<logger>
<!-- Level 2 -->
<level />
<!-- Level 3 -->
<appender-ref />
<!-- Level 3 -->
</logger>
</log4net>
</configuration>
Form1.cs
private static readonly log4net.ILog log = log4net.LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private void simpleButton1_Click(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
log.Info("Info logging");
log.Debug("DADASDASD");
}
Your log4net conf should be as following you should not put anything on the top of log4net node since your configuration is in an independent file:
<log4net>
<!-- Level 1 -->
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=xxx;initial Catalog=xxx; Integrated Security=True;"/>
<commandText value="INSERT INTO dbo.Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception)" />
<parameter>
<parameterName value="#log_date"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.RawTimeStampLayout"/>
</parameter>
<parameter>
<parameterName value="#thread"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread"/>
</layout>
</parameter>
<parameter>
<parameterName value="#log_level"/>
<dbType value="String"/>
<size value="50"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level"/>
</layout>
</parameter>
<parameter>
<parameterName value="#logger"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger"/>
</layout>
</parameter>
<parameter>
<parameterName value="#message"/>
<dbType value="String"/>
<size value="4000"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message"/>
</layout>
</parameter>
<parameter>
<parameterName value="#exception"/>
<dbType value="String"/>
<size value="2000"/>
<layout type="log4net.Layout.ExceptionLayout"/>
</parameter>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="AdoNetAppender"/>
</root>
<logger>
<!-- Level 2 -->
<level />
<!-- Level 3 -->
<appender-ref />
<!-- Level 3 -->
</logger>
</log4net>
If you are still facing problems try to load the conf as following:
XmlConfigurator.Configure(new FileInfo("PATH\Logging.config")

Configuring log4net to write on a database

I am trying to configure log4net to log in the database, it is already configured to write in a file, but when I change the appender to the database it doesn't do anything. The connection to the database is ok because if I change the password I can see an entry in the eventviewer saying the password is wrong.
Here it is my app.config:
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} [%thread] %level %logger - %message%newlineExtra Info: %property{testProperty}%newline%exception"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO"/>
<levelMax value="FATAL"/>
</filter>
</appender>
<securitycontext type="log4net.Util.WindowsSecurityContext">
<credentials value="Process">
</credentials>
</securitycontext>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="100" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=PCKMA0348\SQLEXPRESS;initial catalog=dbServicesLog;User ID='rb';Password='Test1234';multipleactiveresultsets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception)" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#exception" />
<dbType value="String" />
<size value="1000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="mylogfile.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="FATAL"/>
<appender-ref ref="AdoNetAppender"/>
</root>
<logger name="Log4NetTest.OtherClass">
<level value="DEBUG"/>
<appender-ref ref="AdoNetAppender"/>
</logger>
</log4net>
Any guess?
Do I need to create the database and the table manually or it will be automatically created?
You need to create the database and the Log table yourself.
If you want to diagnose possible issues with log4net, you can create a diagnostic trace by adding this to your .config file:
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\whatever\your\path\is\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
and adding the debug switch:
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>

File and Database multiple configuration for log4net

I have Web API that needs to write log data, both to a file and to the database.
Is it possible to configure such a setup? I am trying to understand ILoggerRepository but I am confused.
Can someone give me the some tips on how to configure it and how to use it in application?
It sounds to me like you want to write to two different style appenders at the same time.
The good news is that this is built right into the log4Net library.
What you want to do so configure you configuration file to two different appenders. A file Appender and a Database appender.
Examples of the different appenders can be found here.
http://logging.apache.org/log4net/release/config-examples.html
Here is an example of an web.config that i whipped together. You are going to have to tweak it to get it to work for you, but it will get you on the right start.
One last point, your log4net configuration does not have to be in your web.config but IMHO it just makes things easier to get started. Worry about breaking it out once your web.config starts to get a little cluttered.
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="log-file.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="100" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=[database server];initial catalog=[database name];integrated security=false;persist security info=True;User ID=[user];Password=[password]" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception)" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="AdoNetAppender" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
</configuration>

Retrieving logs from log4net table

I am using log4net for my c# code to insert log into database using the configuration,
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="100" />
<connectionType value="System.Data.SqlClient.SqlConnection,
System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=[database server];
initial catalog=[database name];integrated security=false;
persist security info=True;User ID=[user];Password=[password]" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],
[Message],[Exception]) VALUES (#log_date, #thread, #log_level,
#logger, #message, #exception)" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
So i just need to use their inbuilt functions for inserting data to table. Now i need to retrieve data from the log table. Is log4net providing any functions for retrieving data from table? Or the only way to retrive data from this table is writing my own query? Anyone please help me.
I haven't tried it, but a simple Google search got me to http://code.google.com/p/log4net-db-viewer/ and some other results.
It does not look like there is any built in reader for any appender.
Log4net does not give you any tools to read your logs. Its only for making logs and it depends on the appenders to format and save the logs somewhere. There are many projects and samples which can read your logs depending on your appender:
read log4net logs

Categories

Resources