Log4Net doesn't log or error - c#

I have been attempting to get log4net logging in my asp.net web application with no success or any noticable errors. I am attempting to use the ADONetAppender appender with the following config:
<log4net>
<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="server=" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception],[Context]) VALUES
(#log_date, #thread, #log_level, #logger, #message, #exception, #context)" />
<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="%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="#context" />
<dbType value="String" />
<size value="512" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%x" />
</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="ADONetAppender" />
</root>
In my global.asax Application_Start I call
log4net.Config.XmlConfigurator.Configure();
Then to attempt to log:
protected static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected void Page_Load(object sender, EventArgs e)
{
log.Info("did I log yet?");
}
All of this does nothing as far as I can tell.

you can also set the following appsettings to enable internal log4net debugging information
<appSettings>
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
The internal debug messages are written to the console (if you have one) or the trace (such as the debug window in visual studio or dbgview from sysintenals). This will help you to troubleshoot log4net issues.

Internal debugging for log4Net is the way to go as suggested by #Pratik. To write the details into a file do the following:
Add the following in web.config even if you are using a different config file for 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:\toolbox\SmartClient\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
Reference
How do I enable log4net internal debugging?
log4net - Appenders not working in IIS7.5

Have you added added the following section under under Configuration->Configsections
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
Although it is possible to add your log4net configuration settings to your project’s app.config or web.config file, it is preferable to place them in a separate configuration file. Aside from the obvious benefit of maintainability, it has the added benefit that log4net can place a FileSystemWatcher object on your config file to monitor when it changes and update its settings dynamically.
To use a separate config file, add a file named Log4Net.config to your project and add the following attribute to your AssemblyInfo.cs file:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
Note: for web applications, this assumes Log4Net.config resides in the web root. Ensure the log4net.config file is marked as “Copy To Output” -> “Copy Always” in Properties.
From here.

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>

Log4Net in my .Net website on debugging always shows IsErrorEnabled value as FALSE

I have been trying to log the error in my .Net website to the SQL database using Log4Net AdoNetAppender, but the error message are not getting logged in the database. Looks like the AdoNetAppender is not getting enabled or read. While debugging what I observed is that the Logger.Log shows all its properties values as false. i.e. IsErrorEnabled / IsDebugEnabled / IsFatalEnabled / IsInfoEnabled / IsWarnEnabled all as false.
Version of the log4net.dll I am using is 2.0.8.0
click here to view image of object properties
The logging.cs code is as below:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace Utility.Library
{
public class Logging
{
public static class Logger
{
public static ILog Log = LogManager.GetLogger(typeof(SharedMethods));
}
public static class LogException
{
private static StringBuilder sessionJobLogBuilder = new StringBuilder();
public static void LogError(string sMsg, Exception ex)
{
Logger.Log.Error(sMsg, ex);
sessionJobLogBuilder.AppendLine(sMsg + Environment.NewLine);
sessionJobLogBuilder.AppendLine(ex.ToString() + Environment.NewLine);
}
public static void LogInfo(string sMsg)
{
Logger.Log.Info(sMsg);
sessionJobLogBuilder.AppendLine(sMsg + Environment.NewLine);
}
}
}
}
And below is the app.config:
<?xml version="1.0" encoding="utf-8" ?>
<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=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=xxx\xxx;
initial catalog=xxx;integrated security=false;
persist security info=True;User ID=xxx;Password=xxx" />
<commandText value="EXECUTE [dbo].[WriteLogEntry] #App, #Module, #Ver, #Computer, #UserID, #Level, #Message, #Exception" />
<parameter>
<parameterName value="#App" />
<dbType value="String" />
<size value="30" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%App" />
</layout>
</parameter>
<parameter>
<parameterName value="#Module" />
<dbType value="String" />
<size value="200" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%Module" />
</layout>
</parameter>
<parameter>
<parameterName value="#Ver" />
<dbType value="String" />
<size value="20" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%Ver" />
</layout>
</parameter>
<parameter>
<parameterName value="#Computer" />
<dbType value="String" />
<size value="15" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%Computer" />
</layout>
</parameter>
<parameter>
<parameterName value="#UserID" />
<dbType value="String" />
<size value="30" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%UserID" />
</layout>
</parameter>
<parameter>
<parameterName value="#Level" />
<dbType value="Int32" />
<layout type="log4net.Layout.PatternLayout" />
</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="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
</configuration>
But the Logger.Log properties at all levels show as false.
From your comment I read you have a separate app.config file and the Logger class defined in a separate assembly.
An ASP.NET website only considers the web.config file.
Your app.config file doesn't get loaded, so the Log4net configuration doesn't get applied.
One way to solve this is to transform your app.config file into a separate Log4netconfiguration file and to load that explicitly.
Move the <log4net> ... </log4net> content from the app.config file to a separate file (by convention named Log4net.config) in the root of your website project.
The <log4net> element must be the root xml element in that file.
Remove the [assembly: log4net.Config.XmlConfigurator(Watch = true)] from your Logger project.
Add the following code to Application_Start in Global.asax of the website project to ensure that the log4net configuration gets loaded at website startup phase.
void Application_Start(object sender, EventArgs e)
{
ILoggerRepository repository = log4net.LogManager.GetRepository(Assembly.GetExecutingAssembly());
XmlConfigurator.Configure(repository, new FileInfo(Server.MapPath("log4net.config")));
// Remaining startup code.
}
I have the following log4net.config in the root of my website project (near web.config) with just a RollingFileAppender but the concept is the same.
<log4net>
<appender name="file" type="log4net.Appender.RollingFileAppender">
<param name="ImmediateFlush" value="true" />
<file value="Log.log" />
<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="ERROR" />
<appender-ref ref="file" />
</root>
</log4net>
With your AdoNetAppender setup in my Log4net.config the expected values for IsDebugEnabled, IsErrorEnabled, etc. get shown.
Summary:
Log4net's internal debug logging showed that the configuration file was not being loaded from the presumed location.
The combination of correcting this location (in the XmlConfigurator.Configure method call) and providing a configuration as shown above solved the problem.

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 use a different xml config file when in DEBUG mode compared to RELEASE mode

I have a webapp that I would like to use a different log4net config file when running under DEBUG mode compared to running under RELEASE mode.
I am using log4net version 2.0.3.
In my AssemblyInfo.cs class I have this code:
#if DEBUG
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4netDebug.xml", Watch = true)]
#else
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4netLive.xml", Watch = true)]
#endif
In my Global.asax.cs class I have this code:
log4net.Config.XmlConfigurator.Configure();
log = LogManager.GetLogger(typeof(GlobalApp));
(log is a public static member of GlobalApp.)
In my log4netDebug.xml file I have this code:
<?xml version="1.0" encoding="utf-8"?>
<!-- Configuration for logging using log4net-->
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<!-- Show logging in the Visual Studio output window-->
<appender name="TraceAppender"
type="log4net.Appender.TraceAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-6level - %message%newline" />
</layout>
</appender>
<appender
name="AdoNetAppender"
type="log4net.Appender.AdoNetAppender">
<threshold>INFO</threshold>
<bufferSize
value="1" />
<connectionType
value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=BLAH;initial catalog=BLAH;integrated security=True;persist security info=True" />
<commandText value="INSERT INTO Logs ([Date],[Thread],[Source],[Level], [Logger],[Message],[Exception],[HostName]) VALUES (#log_date, #thread, 'LOG SOURCE',#log_level, #logger, #message, #exception, #hostname)" />
<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="#hostname" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{log4net:HostName}" />
</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="-1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#exception" />
<dbType value="String" />
<size value="-1" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<root>
<level value="ALL" />
<!-- Show logging in the Visual Studio output window-->
<appender-ref ref="TraceAppender" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
</configuration>
I have tested this config script and it works if I place it in my web.config file.
The log4netDebug.xml file has the Copy always property set.
When I try to do something like this:
System.IO.FileInfo fi = new System.IO.FileInfo("Log4NetDebug.xml");
log4net.Config.XmlConfigurator.ConfigureAndWatch(fi);
This doesn't work either.
I have read several stackoverflow and other web pages that describe how to do this and I seem to be doing what they recommend doing but it still deson't seem to work.
Any ideas why?
If you look at the Constructor for the FileInfo class, you will see that it expects The fully qualified name of the new file, or the relative file name..
So when you do this System.IO.FileInfo fi = new System.IO.FileInfo("Log4NetDebug.xml"); you need to specify the full path to the file.
As this is in a web app, you probably want something like this:
var logFile = new FileInfo(Path.Combine(HttpRuntime.BinDirectory, "Log4NetDebug.xml"));

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