Log4net with MySql not logging - c#

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.

Related

Is there a way to store custom properties in database while logging with log4net using AdoNetAppender?

I am having a controller, where I inject the log4net dependency like this:
public CalendarController(ILogger<CalendarController> logger) : base(logger) { }
[HttpGet]
public List<MyClass> Get()
{
var log = new
{
Message = "asd123",
LogLevel = "Error",
LogDate = DateTime.Now,
EndpointName = "testendpoint",
Username = "myusername",
Userdomain = "mydomain"
};
_logger.LogError(JsonConvert.SerializeObject(log));
return someValue;
}
My db structure looks like this:
The log4net.config file looks like this:
<log4net debug ="true">
<root>
<level value="WARN" />
<appender-ref ref="AdoNetAppender" />
<!--ENABLE THIS FOR DEBUGGING #1-->
<!--<appender-ref ref="DebugAppender" />-->
</root>
<!-- ENABLE THIS FOR DEBUGGING #2-->
<!--<appender name="DebugAppender" type="log4net.Appender.DebugAppender">
<immediateFlush value="true" />
<layout type="log4net.Layout.SimpleLayout" />
</appender>-->
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data" />
<connectionString value="connectionStringPlaceHolder"/>
<commandText value="INSERT INTO dbo.Logs (Message, LogLevel, LogDate, EndpointName, Username, Userdomain)
VALUES (#message, #log_level, #log_date, #endpointname, #username, #userdomain)" />
<parameter>
<parameterName value="#message"/>
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%m" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_level"/>
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%p" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout"/>
</parameter>
<parameter>
<parameterName value="#endpointname"/>
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="Endpointname" />
</layout>
</parameter>
<parameter>
<parameterName value="#username"/>
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%w" />
</layout>
</parameter>
<parameter>
<parameterName value="#userdomain" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="Userdomain" />
</layout>
</parameter>
</appender>
</log4net>
I thought RawProperty layouts is the thing I want, but it is not. How can I configure this XML, so that the parameters I gave to _logger.LogError() are correctly inserted into the database?

Logs do not get saved into Logs table

I'm trying to save any logs I received from the application into a log table in my db and so far, nothing gets saved. I'm using Log4net and AdoNetAppender for saving the logs into my table inside SQL Server. This code sits inside a Web API project on the server side of my app.
I set up the logs as follows:
1) Setup the XML in my Web.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=token" />
<connectionString value="data source=db;Initial Catalog=dbname;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
<commandText value="dbo.procLogs_Insert" />
<commandType value="StoredProcedure" />
<parameter>
<parameterName value="#log_timestamp" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#log_recordNum" />
<dbType value="Int32" />
<size value="32" />
<layout type="log4net.Layout.RawPropertyLayout" />
</parameter>
<parameter>
<parameterName value="#log_computerName" />
<dbType value="String" />
<size value="128" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%X{machine}" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_processTimeStamp" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#log_group" />
<dbType value="StringFixedLength" />
<size value="1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_type" />
<dbType value="StringFixedLength" />
<size value="1" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_eventId" />
<dbType value="Int32" />
<size value="32" />
<layout type="log4net.Layout.RawPropertyLayout" />
</parameter>
<parameter>
<parameterName value="#log_userId" />
<dbType value="Int32" />
<size value="32" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%identity" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_line" />
<dbType value="Int32" />
<size value="32" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%line" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_description" />
<dbType value="AnsiString" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message%newline %exception" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_source" />
<dbType value="AnsiString" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%file" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_data" />
<dbType value="AnsiString" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_addTimeStamp" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#log_deviceId" />
<dbType value="StringFixedLength" />
<size value="10" />
<layout type="log4net.Layout.PatternLayout" />
</parameter>
</appender>
<appender name="asyncForwarder" type="Log4Net.Async.AsyncForwardingAppender,Log4Net.Async">
<appender-ref ref="AdoNetAppender" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="asyncForwarder" />
</root>
</log4net>
2) Here's the code inside my Global.asax.cs:
public class WebApiApplication : System.Web.HttpApplication
{
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected void Application_Start()
{
XmlConfigurator.Configure();
_log.Info("Service Started");
GlobalConfiguration.Configure(WebApiConfig.Register);
}
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
}
}
3) Added the Stored Procedure to the db:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.procLogs_Insert
#log_timestamp datetime,
#log_recordNum int,
#log_computerName varchar(128),
#log_processTimeStamp datetime,
#log_group char(1),
#log_type char(1),
#log_eventId int,
#log_userId varchar(128),
#log_line int,
#log_description text,
#log_source text,
#log_data text,
#log_addTimeStamp datetime,
#log_deviceId char(10)
AS
BEGIN
SET NOCOUNT ON;
insert into dbo.BS_ApplicationLogs(LogTimestamp, RecordNum, ComputerName, ProcessTimestamp, LogGroup, [Type],EventId,UserId,Line,[Description],[Source],[Data],AddTimestamp,DeviceID)
values (#log_timestamp, #log_recordNum, #log_computerName, #log_processTimeStamp, #log_group, #log_type, #log_eventId, #log_userId, #log_line,#log_description,#log_source,#log_data,#log_addTimeStamp,#log_deviceId)
END
GO
Question: Where should this stored procedure be saved in SSMS? When I save the stored procedure, it automatically defaults it to Documents\SSMS but I want to save it under DB/Programmability/StoredProcedures folder but I don't see it there. However, I did execute the stored procedure successfully without any errors.
4) added logs to other files inside my app project outside of the global.asax.cs file. Does Log4Net know to log those as well?
So yeah I'm not sure what I did wrong and nothing gets logged to my table in SQL Server. Did I miss a step in the process of setting up Log4Net?
EDIT: Internal debugger says:
log4net: Created Appender [AdoNetAppender]
log4net: Created Appender [asyncForwarder]
log4net: Adding appender named [asyncForwarder] to logger [root].
log4net: Hierarchy Threshold []
log4net:ERROR [AdoNetAppender] ErrorCode: GenericFailure. Exception while writing to database
System.ArgumentNullException: Key cannot be null.
Parameter name: key
at System.Collections.Hashtable.get_Item(Object key)
at log4net.Util.PropertiesDictionary.get_Item(String key)
at log4net.Core.LoggingEvent.LookupProperty(String key)
at log4net.Layout.RawPropertyLayout.Format(LoggingEvent loggingEvent)
at log4net.Appender.AdoNetAppenderParameter.FormatValue(IDbCommand command, LoggingEvent loggingEvent)
at log4net.Appender.AdoNetAppender.SendBuffer(IDbTransaction dbTran, LoggingEvent[] events)
at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)
What key?
3) Sounds like you've created the Stored Procedure, however its ended up in the Master database (Master/Programmability/StoredProcedures).
You should either select the DropDownList and change from Master to your DB or you can use the syntax USE YourDB before the stored proc and click the Execute button:
USE YourDB
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.procLogs_Insert
#log_timestamp datetime,
#log_recordNum int,
#log_computerName varchar(128),
#log_processTimeStamp datetime,
#log_group char(1),
#log_type char(1),
#log_eventId int,
#log_userId varchar(128),
#log_line int,
#log_description text,
#log_source text,
#log_data text,
#log_addTimeStamp datetime,
#log_deviceId char(10)
AS
BEGIN
SET NOCOUNT ON;
insert into dbo.BS_ApplicationLogs(LogTimestamp, RecordNum, ComputerName, ProcessTimestamp, LogGroup, [Type],EventId,UserId,Line,[Description],[Source],[Data],AddTimestamp,DeviceID)
values (#log_timestamp, #log_recordNum, #log_computerName, #log_processTimeStamp, #log_group, #log_type, #log_eventId, #log_userId, #log_line,#log_description,#log_source,#log_data,#log_addTimeStamp,#log_deviceId)
END
GO
This is a file I have that works, writing to a MS SQL server
It refers to user defined properties %property{xxx}, that are populated in code like this
GlobalContext.Properties["user"] = Environment.UserName;
Maybe you can replace some of your properties with that to figure out which one is causing the issue
<appender name="AppenderDB" type="log4net.Appender.AdoNetAppender">
<bufferSize value="0" />
<reconnectOnError value="true" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral" />
<connectionString value="Data Source=MYDB\DB;Initial Catalog=XXX;Integrated Security=True;" />
<commandText value="EXECUTE WriteLogEntry #time, #recipeName, #userId, #timeSeries, #loadTimeMs" />
<parameter>
<parameterName value="#time" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawUtcTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#recipeName" />
<dbType value="String" />
<size value="1024" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{recipeName}" />
</layout>
</parameter>
<parameter>
<parameterName value="#userId" />
<dbType value="String" />
<size value="20" />
<layout type="log4net.Layout.PatternLayout" value="%property{user}"/>
</parameter>
<parameter>
<parameterName value="#timeSeries" />
<dbType value="String" />
<size value="1024" />
<layout type="log4net.Layout.PatternLayout" value="%property{timeSeries}"/>
</parameter>
<parameter>
<parameterName value="#loadTimeMs" />
<dbType value="Int32" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout" value="%property{loadTimeMs}"/>
</parameter>
`

log4net AdoNetAppender stops logging - Can't find type - Custom logger

I'm hoping someone can give me some insight into why when using log4net's AdoNetAppender I'll get logs for a day, maybe two, and then they just stop. I have reconnectOnError set to true, but still no logs. My bufferSize is also set to 1, so if I write a log, I should see it instantly, which I do when the application is started. I have two log tables, one for tracking information, and one for normal logs. The normal log4net log is unmodified and I believe always logs, the other is a custom log I use to track web service requests. Both logs work as expected after startup.
A day latter, sometimes more, sometimes less, I go back to check the logs and the application work, but nothing is log to the custom logger.
Update!! After letting everything sit overnight, I find this in the error logs:
log4net:ERROR Failed to find type [Fcn.Logging.TrackingLayoutPattern]
System.TypeLoadException: Could not load type [Fcn.Logging.TrackingLayoutPattern]. Tried assembly [log4net, Version=1.2.13.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a] and all loaded assemblies
at log4net.Util.SystemInfo.GetTypeFromString(Assembly relativeAssembly, String typeName, Boolean throwOnError, Boolean ignoreCase)
at log4net.Util.SystemInfo.GetTypeFromString(String typeName, Boolean throwOnError, Boolean ignoreCase)
at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
log4net:ERROR Failed to create object to set param: layout
All the Fcn.Logging objects are in a separately built library called Common that is shared by multiple applications at Fcn. I don't remember this issue when the objects were part of each web service, but I believe the problem started when I split them up so that I wouldn't have to drop them into each and every application that I create that needs them.
I'm initializing log4net in the Global.asax.cs with the following code:
private static readonly ILog log4net = LogManager.GetLogger(typeof(Global));
protected void Application_Start(object sender, EventArgs e)
{
XmlConfigurator.Configure();
log4net.Info("Logging initialized");
}
My web.config configuration for this is as follows:
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="textWriterTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="E:\PseudoFileServer\Logging\wsFCNCheck\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="TestLog2.txt" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<param name="ImmediateFlush" value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%d{yyyy-MM-dd HH:mm:ss}] [%p] [%c:%L] - %m%n" />
</layout>
</appender>
<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="AdoLog4NetAppender" 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=Server;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=UserName;Password=UserPass" />
<reconnectOnError>true</reconnectOnError>
<commandText value="[WS].[WebServiceLogOnly_Insert]" />
<commandType value="StoredProcedure" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime2" />
<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="-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>
<appender name="AdoNetTrackingAppender" 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=Server;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=UserName;Password=UserPass" />
<reconnectOnError>true</reconnectOnError>
<commandText value="[WS].[WebServiceTracking_Insert]" />
<commandType value="StoredProcedure" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime2" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#WebServiceRequestTypeKey" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{webservicerequesttypekey}" />
</layout>
</parameter>
<parameter>
<parameterName value="#CallerSource" />
<dbType value="String" />
<size value="5" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{callersource}" />
</layout>
</parameter>
<parameter>
<parameterName value="#UserID" />
<dbType value="String" />
<size value="50" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{userid}" />
</layout>
</parameter>
<parameter>
<parameterName value="#Request" />
<dbType value="Xml" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{request}" />
</layout>
</parameter>
<parameter>
<parameterName value="#ResponseTypeKey" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{responsetypekey}" />
</layout>
</parameter>
<parameter>
<parameterName value="#WebServiceResponseMessageKey" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{webserviceresponsemessagekey}" />
</layout>
</parameter>
<parameter>
<parameterName value="#Response" />
<dbType value="Xml" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{response}" />
</layout>
</parameter>
<parameter>
<parameterName value="#StartTime" />
<dbType value="DateTime2" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{starttime}" />
</layout>
</parameter>
<parameter>
<parameterName value="#EndTime" />
<dbType value="DateTime2" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{endtime}" />
</layout>
</parameter>
<parameter>
<parameterName value="#StoredProcedureCallTimeInMS" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{storedprocedurecalltimeinms}" />
</layout>
</parameter>
<parameter>
<parameterName value="#MSGeocode" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{msgeocode}" />
</layout>
</parameter>
<parameter>
<parameterName value="#GeocodeFailOverUsed" />
<dbType value="Boolean" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{geocodefailoverused}" />
</layout>
</parameter>
<parameter>
<parameterName value="#GeocodeRequest" />
<dbType value="String" />
<size value="-1" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{geocoderequest}" />
</layout>
</parameter>
<parameter>
<parameterName value="#GeocodeResponse" />
<dbType value="String" />
<size value="-1" />
<layout type="Fcn.Logging.TrackingLayoutPattern">
<conversionPattern value="%Tracking{geocoderesponse}" />
</layout>
</parameter>
</appender>
<root>
<level value="WARNING" />
<appender-ref ref="AdoLog4NetAppender" />
</root>
<logger additivity="false" name="Tracking">
<level value="INFO"/>
<appender-ref ref="AdoNetTrackingAppender" />
</logger>
</log4net>
I changed the reconnect tag to look like this:
<reconnectOnError value="true" /> <!-- I believe this is the correct syntax -->
<reconnectOnError>true</reconnectOnError> <!-- This I believe is incorrect syntax -->
Can someone confirm which is the correct syntax?
At this point I also changed the custom loggers to specify which assembly they are in. This might be the only problem, but I'm getting an additional error at this point. I'll detail the configuration change and then the new error.
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="TestLog2.txt" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<param name="ImmediateFlush" value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%d{yyyy-MM-dd HH:mm:ss}] [%p] [%c:%L] - %m%n" />
</layout>
</appender>
<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="AdoLog4NetAppender" 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=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=Username;Password=Password" />
<reconnectOnError value="true" />
<commandText value="[WS].[WebServiceLogOnly_Insert]" />
<commandType value="StoredProcedure" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime2" />
<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="-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>
<appender name="AdoNetTrackingAppender" 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=ServerName;Initial Catalog=DatabaseName;Persist Security Info=True;User ID=Username;Password=Password" />
<reconnectOnError value="true" />
<commandText value="[WS].[WebServiceTracking_Insert]" />
<commandType value="StoredProcedure" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime2" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#WebServiceRequestTypeKey" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{webservicerequesttypekey}" />
</layout>
</parameter>
<parameter>
<parameterName value="#CallerSource" />
<dbType value="String" />
<size value="5" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{callersource}" />
</layout>
</parameter>
<parameter>
<parameterName value="#UserID" />
<dbType value="String" />
<size value="50" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{userid}" />
</layout>
</parameter>
<parameter>
<parameterName value="#Request" />
<dbType value="Xml" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{request}" />
</layout>
</parameter>
<parameter>
<parameterName value="#ResponseTypeKey" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{responsetypekey}" />
</layout>
</parameter>
<parameter>
<parameterName value="#WebServiceResponseMessageKey" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{webserviceresponsemessagekey}" />
</layout>
</parameter>
<parameter>
<parameterName value="#Response" />
<dbType value="Xml" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{response}" />
</layout>
</parameter>
<parameter>
<parameterName value="#StartTime" />
<dbType value="DateTime2" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{starttime}" />
</layout>
</parameter>
<parameter>
<parameterName value="#EndTime" />
<dbType value="DateTime2" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{endtime}" />
</layout>
</parameter>
<parameter>
<parameterName value="#StoredProcedureCallTimeInMS" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{storedprocedurecalltimeinms}" />
</layout>
</parameter>
<parameter>
<parameterName value="#MSGeocode" />
<dbType value="Int32" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{msgeocode}" />
</layout>
</parameter>
<parameter>
<parameterName value="#GeocodeFailOverUsed" />
<dbType value="Boolean" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{geocodefailoverused}" />
</layout>
</parameter>
<parameter>
<parameterName value="#GeocodeRequest" />
<dbType value="String" />
<size value="-1" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{geocoderequest}" />
</layout>
</parameter>
<parameter>
<parameterName value="#GeocodeResponse" />
<dbType value="String" />
<size value="-1" />
<layout type="Fcn.Logging.TrackingLayoutPattern, Common">
<conversionPattern value="%Tracking{geocoderesponse}" />
</layout>
</parameter>
</appender>
<root>
<level value="WARNING" />
<appender-ref ref="AdoLog4NetAppender" />
</root>
<logger additivity="false" name="Tracking">
<level value="INFO"/>
<appender-ref ref="AdoNetTrackingAppender" />
</logger>
</log4net>
Will the , Common for the assembly name address the Can't find type error?
And the new error is the following:
log4net:ERROR [AdoNetAppender] ErrorCode: GenericFailure. Exception while writing to database
System.Data.SqlClient.SqlException (0x80131904): A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - An established connection was aborted by the software in your host machine.) ---> System.ComponentModel.Win32Exception (0x80004005): An established connection was aborted by the software in your host machine
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSniSyncOverAsync()
at System.Data.SqlClient.TdsParserStateObject.TryReadNetworkPacket()
at System.Data.SqlClient.TdsParserStateObject.TryPrepareBuffer()
at System.Data.SqlClient.TdsParserStateObject.TryReadByte(Byte& value)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
at System.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransaction(TransactionRequest transactionRequest, String name, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest)
at System.Data.SqlClient.SqlInternalConnection.BeginSqlTransaction(IsolationLevel iso, String transactionName, Boolean shouldReconnect)
at System.Data.SqlClient.SqlConnection.BeginTransaction(IsolationLevel iso, String transactionName)
at System.Data.SqlClient.SqlConnection.BeginDbTransaction(IsolationLevel isolationLevel)
at System.Data.Common.DbConnection.System.Data.IDbConnection.BeginTransaction()
at log4net.Appender.AdoNetAppender.SendBuffer(LoggingEvent[] events)
ClientConnectionId:6f780eae-73cd-4c2d-bc26-545b3234f161
Error Number:10053,State:0,Class:20
I'm about to install the updated config section on an internal company server instead of testing locally. I'm wondering if the latest error is due to the VPN being recycled every 12 hours. From googling the error I'm also worried that the connection was closed by SQL server due to inactivity. If this is the case I would suspect the reconnect on error tag set to true to address this. Any ideas on what is going on?

Log4net buffer size not working

im trying to enter every 100 records into the database.If i specify the buffer size as 100.It stills enters each record into the database.Is there a way where i can specify the flush interval and buffer size.So which comes first it takes that.
This is my config.
<log4net>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="10" />
<connectionType value="System.Data.SqlClient.SqlConnection,
System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="data source=;User ID=;Password=" />
<commandText value="INSERT INTO Errorlog ([clientname],[username],[administration],[selectedentity],[project],[Date],[Thread],[Level],[Logger],
[Message],[Exception],[browser],[ipaddress],[url],[errormessage]) VALUES (#clientname,#username,#administration,#selectedentity,#project,#log_date, #thread, #log_level,
#logger, #message, #exception,#browser,#ipaddress,#url,#errormessage)"/>
<parameter>
<parameterName value="#clientname" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{clientname}" />
</layout>
</parameter>
<parameter>
<parameterName value="#username" />
<dbType value="String" />
<size value="100" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{username}" />
</layout>
</parameter>
<parameter>
<parameterName value="#administration" />
<dbType value="String" />
<size value="100" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{administration}" />
</layout>
</parameter>
<parameter>
<parameterName value="#selectedentity" />
<dbType value="String" />
<size value="100" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{selectedentity}" />
</layout>
</parameter>
<parameter>
<parameterName value="#project" />
<dbType value="String" />
<size value="100" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{project}" />
</layout>
</parameter>
<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>
<parameter>
<parameterName value="#browser" />
<dbType value="String" />
<size value="100" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{browser}" />
</layout>
</parameter>
<parameter>
<parameterName value="#ipaddress" />
<dbType value="String" />
<size value="100" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{ipaddress}" />
</layout>
</parameter>
<parameter>
<parameterName value="#url" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{url}" />
</layout>
</parameter>
<parameter>
<parameterName value="#errormessage" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{errormessage}" />
</layout>
</parameter>
</appender>
<root>
<appender-ref ref="AdoNetAppender"/>
</root>
</log4net>
Buffersize only specifies how many items shall be kept in RAM before committing them. It does not define the Lossyness of the logger.
To define a lossy logger, you need to state that explicitly and define what can be lost:
<lossy value="true"/>
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ERROR" />
</evaluator>

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