Using stored procedures in log4net configuration - c#

I'm trying to use log4net in my C# console application. I'm not too sure how this is used with stored procedures. With the configuration info below, how exactly will doing something like log.Info("message here") execute the stored procedure with parameters if all I pass is the message string?
I'm using SQL Server Express as database. In AssemblyInfo.cs I've added the following line:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
From what I've found here on StackOverflow, I have the following in my app.config:
<root>
<level value="DEBUG" />
<appender-ref ref="FileAppender" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="AdoNetAppender" />
</root>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<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" />
<connectionString value="data source=MyPC\\SQLEXPRESSPC;initial catalog=MyDBName;integrated security=false;persist security info=True;User ID=MyDBUser;Password=MyDBPassword" />
<commandText value="InsertGoogleDriveLog" />
<commandType value="StoredProcedure" />
<parameter>
<parameterName value="#user_name" />
<dbType value="String" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%username" />
</layout>
</parameter>
<parameter>
<parameterName value="#message_text" />
<dbType value="String" />
<size value="1024" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
</appender>
In my logger class I have the line:
log.Info("OK, here we are");
Also, I removed , PublicKeyToken=b77a5c561934e089 from the connectionType string value, as I'm not sure where this is obtained from when I copied it from the question here.

it seems you are missing some elements in your configuration (log4net -> should contain the root and appender elements):
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="AdoNetAppender" />
</root>
<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" />
<connectionString value="data source=MyPC\\SQLEXPRESSPC;initial catalog=MyDBName;integrated security=false;persist security info=True;User ID=MyDBUser;Password=MyDBPassword" />
<commandText value="InsertGoogleDriveLog" />
<commandType value="StoredProcedure" />
<parameter>
<parameterName value="#user_name" />
<dbType value="String" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%username" />
</layout>
</parameter>
<parameter>
<parameterName value="#message_text" />
<dbType value="String" />
<size value="1024" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
</appender>
</log4net>

Related

log4net logging error in mysql database logging

i am using log4net for logging in mysql database. log4net configuration is correct and because i have tested to log in sql server and in file but when i'm writing logs in mysql database then it prompt an error to me.
my log4net config is below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6"/>
</startup>
<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=logdb;Uid=abc;Pwd=abc;" />
<commandText value="INSERT INTO log (timestamp,Thread,Level,Logger,Message) VALUES (?log_date, ?thread, ?log_level, ?logger, ?message);" />
<parameter>
<parameterName value="?log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="?thread" />
<dbType value="String" />
<size value="32" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="?log_level" />
<dbType value="String" />
<size value="32" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="?logger" />
<dbType value="String" />
<size value="256" />
<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>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="textWriterTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="C:\Logs\log4net.txt"/>
</listeners>
</trace>
</system.diagnostics>
</configuration>
and the log consuming code is here
class Program
{
private static readonly ILog Logger = LogManager.GetLogger(System.Environment.MachineName);
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
Logger.Info("Testing information log from .Net app");
Logger.Debug("Testing Debug log from .Net app");
Logger.Fatal("Testing Fatal log from .Net app");
}
}
i also the
"[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Web.config", Watch = true)]
"
this line in assembly file.
the error i'm encountering is
**
log4net:ERROR [AdoNetAppender] ErrorCode: GenericFailure. Exception while writing to database
System.InvalidOperationException: Parameter '?log_date' was not found during prepare.
at MySql.Data.MySqlClient.PreparableStatement.Prepare()
at MySql.Data.MySqlClient.MySqlCommand.Prepare(Int32 cursorPageSize)
at MySql.Data.MySqlClient.MySqlCommand.Prepare()
at log4net.Appender.AdoNetAppender.SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)
log4net: Shutdown called on Hierarchy [log4net-default-repository]
**
but actually I'm passing all required parameters dnt know why I'm getting this error.
can anyone guide.
This is a bug in MySql.Data. There isn't a bug report filed for it as far as I know, but you can see from the MySqlConnector integration tests that MySql.Data fails if you call MySqlCommand.Prepare before adding the parameters.
However, that's exactly what AdoNetAppender does. (There is a try/catch block in that code, but that's a recent change, after 2.0.12.)
There are two possible fixes:
Switch to MySqlConnector and change the <connectionType /> to use it.
Add IgnorePrepare=true to your MySql.Data connection string, which will cause Prepare to be a no-op. (Note: this option was removed in 8.0.24.)
As #Bradley Grainger mentioned, MySqlConnector does the job
I sadly cannot comment but #hashimkayani asked for an example, I did try it out and it works perfectly fine:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
<log4net>
<appender name="dbAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="MySqlConnector.MySqlConnection, MySqlConnector" />
<connectionString value="Server=localhost;Database=dbName;Uid=dbUser;Pwd=dbPassword;persistsecurityinfo=True;SslMode=none;" />
<commandText value="INSERT INTO afmlog(date, thread, level, logger, message) VALUES (#log_date, #thread, #log_level, #logger, #message);" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%thread" />
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout" value="%level" />
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout" value="%logger" />
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout" value="%message" />
</parameter>
</appender>
</log4net>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\temp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>

Logging into Database using log4net and Microknights in asp.net core 3.1 didn't work

I have gone through many articles saying AdoNetAppender is not supported in .net core, but we can use MicroKnights to do the same.
I am trying to achieve DB logging in .net core 3.1 application using the same but still not succeed.
My log4net.config file placed in roots is as follows:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net debug="true">
<appender name="AdoNetAppender" type="MicroKnights.Logging.AdoNetAppender, MicroKnights.Log4NetAdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection,System.Data.SqlClient,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089" />
<connectionStringName value="log4net" />
<connectionStringFile value="appsettings.json" />
<commandText value="INSERT INTO ApplicationLog(ApplicationID, CreateDate, LogLevel, Message, Exception)
VALUES (#ApplicationID, #CreateDate, #LogLevel, #Message, NULLIF(#Exception,''))" />
<!--<commandText value="dbo.sp_InsertApplicationLog" />
<commandType value="StoredProcedure" />-->
<parameter name="ApplicationID">
<parameterName value="#ApplicationID" />
<dbType value="Int16" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{ApplicationID}" />
</layout>
</parameter>
<parameter name="CreateDate">
<parameterName value="#CreateDate" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter name="LogLevel">
<parameterName value="#LogLevel" />
<dbType value="AnsiString" />
<size value="20" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter name="Message">
<parameterName value="#Message" />
<dbType value="AnsiString" />
<size value="2000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter name="Exception">
<parameterName value="#Exception" />
<dbType value="AnsiString" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%exception" />
</layout>
</parameter>
<threshold value="DEBUG"/>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="DEBUG" />
<levelMax value="ERROR" />
</filter>
</appender>
<!--<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
<appender-ref ref="AdoNetAppender" />
</root>-->
<root>
<level value="ALL"/>
<appender-ref ref="RollingFileAppender" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
</configuration>
My startup.cs file calling AddLog4Net() method.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddLog4Net();
}
And I am trying to log in database is like this,
private static readonly string LOG_CONFIG_FILE = #"log4net.config";
private static readonly ILog log = LogManager.GetLogger(typeof(Log4NetLoggingService));
private static void SetLog4NetConfiguration()
{
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead(LOG_CONFIG_FILE));
var repo = LogManager.CreateRepository(
Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
AdoNetAppenderHelper.SetConnectionString(Configuration
.GetSection("Data:Logging")
.GetSection("DbConnectionString").Value);
}
public void LogError(Exception exception)
{
var message = string.IsNullOrEmpty(exception.Source) ? exception.Message : exception.Source;
SetLog4NetConfiguration();
log.Error(message, exception);
}
I cannot understand where I am wrong, but I tried my best but didn't succeed.
For .Net Core 3.1, Microsoft has changed path for the SqlClient library.
So you have to update the connectionType element inside the log4net.config to:
<connectionType value="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient, Version=1.0.0.0,Culture=neutral,PublicKeyToken=23ec7fc2d6eaa4a5"/>
You can find more details here microknights/Log4NetAdoNetAppender Github README.md

Log4net - multiple appenders

I currently have two appenders, one is for logging in a file and the other is for logging in a database. The ado net appender is not working, it's not logging anything in the table. The rolling file appender however, works just fine. It logs in the file. If I remove the rolling file appender, the logging in the database works just fine.
Here's part of my app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="Log4NetDBConnection" connectionString="Data Source=localhost;Initial Catalog=DataProcessing;UID=dpp-user;PWD=dpp-user" providerName="System.Data.SqlClient" />
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net1211">
<arg key="configType" value="INLINE" />
</factoryAdapter>
</logging>
</common>
<log4net configSource="App.log4net.config" />
<dependentAssembly>
<assemblyIdentity name="Common.Logging.Core" publicKeyToken="af08829b84f0328e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.3.0.0" newVersion="3.3.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.3.0.0" newVersion="3.3.0.0" />
</dependentAssembly>
</assemblyBinding>
And here is my App.Log4net.config file:
<log4net>
<!-- Needed for default logger behavior to the log table-->
<root>
<level value="ERROR" />
<level value="WARN" />
<appender-ref ref="AdoNetAppender" />
</root>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection,System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionStringName value="DPPLog4NetDBConnection" />
<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>
<!-- <root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<level value="ALL" />
<file value="c:/logs/WorkflowEngineApp.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger -
%message%newline%exception" />
</layout>
</appender> -->
</log4net>
As you can see, I have the rolling file appender commented because otherwise it only logs in a file. What am I doing wrong? Can I use these two appenders together?
I suspect your are on the right track, looks like both appenders needs to be specified in the same root see example and link below:
<root>
<level value="ERROR" />
<level value="WARN" />
<appender-ref ref="AdoNetAppender" />
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
File and Database multiple configuration for log4net

log4net does not write log into SQL Server

I'm trying to log using log4net into my database. I've installed log4net using NuGet and set up my web.config like this:
<configSections>
<!-- Log4Net -->
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<!--AdoNet appender is use for write log file into SQL Server-->
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=localhost/SVILUPPO;Initial Catalog=MIODB;user id=sa;password=myPassword;" />
<commandText value="INSERT INTO AppLog ([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>
<!--Add appender which you want to use, You can add more then one appender . Like if you want save log both plain text or sql server ,Add both appender.-->
<root>
<level value="ALL" />
<appender-ref ref="AdoNetAppender" />
<!--Enable this line if you want write log file into sql server-->
</root>
</log4net>
Then I set in my global.asax the call to the configuration:
log4net.Config.XmlConfigurator.Configure();
And this in the page where I want get and save the log
private static ILog log = LogManager.GetLogger(typeof(Login));
log.Debug("Debug message");
log.Warn("Warn message");
log.Error("Error message");
log.Fatal("Fatal message");
but nothing happens :(
Can anyone help me please?
To find the error you can best enable internal debugging in log4net. An error in log4net will not go to your application. You can write it to a log and then see why your logging is not working.
In your app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
...
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="C:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
Log4net FAQ

Log4Net writes nothing in SQL Server database

I found similar questions, but non of the answers worked.
Log4Net doesn't write anything in the log database and I don't really know how to find the error.
This is my config file:
<log4net>
<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=sqlServer;initial catalog=Logging;integrated security=false;persist security info=True;User ID=logUser;Password=logPassword" />
<commandText value="INSERT INTO dbo.myLogTable ([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>
</log4net>
It's actually a complete copy of the SQL Server example on the apache page. I've only changed the connection string. The connection itself should work fine, I've tested the connection string with a SqlConnection.
This is how I create the logging object and load the config:
public static class LogFactory
{
public const string Log4NetConfig = "log4net.config";
public static ILog GetLogger()
{
var uri = new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), Log4NetConfig));
var configFile = new FileInfo(Path.GetFullPath(uri.LocalPath));
XmlConfigurator.ConfigureAndWatch(configFile);
ILog log = LogManager.GetLogger(typeof(LogFactory));
return log;
}
}
Logging itself:
private static readonly ILog Log = LogFactory.GetLogger();
[...]
Log.Info("Test 123");
Logging works fine if I replace the config with my usual "log to file" config, so I guess the error has to be somewhere in the config, but the config is the default example from the homepage.
Can you see an error somewhere?
you did not define when the appender should be used and also with bufferSize you postponed writing to db.
<log4net>
<root>
<level value="ALL" /> <!--send all logs to appenders-->
<appender-ref ref="AdoNetAppender" />
</root>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="100" /> <!--THIS WILL POSTPONE DB WRITING UNTIL A BUFFER OF 100 LOG IS REACHED-->
<threshold value="INFO"/> <!--log when >= INFO -->
.....
</appender>
</log4net>
Final thoughts:
You are calling the log4net configurator every time you need a logger and this is not how you should do it.
It should be called only the first time when you start your app (static Main method) or website (global.asax applicationStart).
Then your classes should have the readonly ILog property:
private static ILog logger = LogManager.GetLogger(typeof(MyClass));
<bufferSize value="100" />
This mean that Log4Net will keep 100 records in memory before inserting into the database.
This is by design to limit round trip to the database. Try setting <bufferSize value="1" /> or maybe 0 could work.
While using AdoNetAppender, i am unable to write the log details into the database.
Following are the changes that has been done to make it a workable solution :
1) Use bufferSize value="1" or bufferSize value="0"
2) 'root' directory should be used before all the Appenders that has been used
Eg.
<root>
<level value="ALL"></level>
<appender-ref ref="AdoNetAppender"></appender-ref>
<appender-ref ref="RollingFileAppender"></appender-ref>
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="mylogfile.txt" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</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=server_name; initial catalog=database_name;integrated security=false; persist security info=True;User ID=user_id;Password=password" />
<commandText value="INSERT INTO ErrorLog ([Logger]) VALUES (#logger)" />
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="100" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
</appender>
</log4net>

Categories