in this time I try to log into a DB whit L4N, this is the struct of the table:
[TcpClientTracer]
[ID] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[Thread] [varchar](20) NOT NULL,
[EventType] [varchar](20) NOT NULL,
[ClientId] [int] NOT NULL,
[ModemId] [varchar](128) NOT NULL,
[EventText] [varchar](2000) NOT NULL
to fill this table I use this appender:
<appender name="TcpAdoNetAppender" type="log4net.Appender.AdoNetAppender,log4net">
<bufferSize value="50" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=[IPADDRES]; Initial Catalog=XYXY; User Id=username;Password=password" />
<commandText value="INSERT INTO TcpClientTracer ([Date],[Thread],[EventType],[ClientId],[ModemId],[EventText]) VALUES (#log_date, #thread, #eventtype, #clientid, #modemid, #eventtext)" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="20" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="#eventtype" />
<dbType value="String" />
<size value="20" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="eventtype" />
</layout>
</parameter>
<parameter>
<parameterName value="#clientid"/>
<dbType value="Int32"/>
<layout type="log4net.Layout.RawPropertyLayout">
<key value="clientid" />
</layout>
</parameter>
<parameter>
<parameterName value="#modemid" />
<dbType value="String" />
<size value="128" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="modemid" />
</layout>
</parameter>
<parameter>
<parameterName value="#eventtext" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.RawPropertyLayout">
<key value="eventtext" />
</layout>
</parameter>
</appender>
the logger is this:
<logger name="TcpClientTracer" additivity="false">
<level value="ALL"/>
<appender-ref ref="TcpAdoNetAppender" />
</logger>
and...to pass the data from C# I use this method:
public static void writeLog(GroupType mGrupo, Hashtable mValues)
{
ILog Logger = oLogger.GetLoggerByGroup(mGrupo);
Type declaringType = typeof(log4net.LogManager);
LoggingEvent loggingEvent = new LoggingEvent(declaringType, Logger.Logger.Repository, Logger.Logger.Name, Level.All, null, null);//null = Message, Exception
foreach (DictionaryEntry CurrentEntry in mValues)
{
loggingEvent.Properties[CurrentEntry.Key.ToString()] = CurrentEntry.Value;
}
Logger.Logger.Log(loggingEvent);
}
I don't know how works the LoggingEvent, but I use it to fill other table and work perfectly.
If somebody can help me with this issue, I apreciate!!
Thanks to read my bad english!!
I am not 100% sure what you are asking. What I can tell you for sure is this: If you want to log custom properties, you need to use RawPropertyLayout and specify property name. Example:
<parameter>
<parameterName value="#clientid"/>
<dbType value="Int32"/>
<layout type="log4net.Layout.RawPropertyLayout">
<key value="clientid" />
</layout>
</parameter>
Related
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?
I'm trying to log my errors/warnings... in my DB using log4net (.NET 6).
I've tried even with different packages (Microknights) but it still won't save anything in my database.
Am I missing something?
When I'm debugging it seems to be hitting the right methods all the right times, with no exceptions raised.
This is the config file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<root>
<level value="ALL"></level>
<appender-ref ref="AdoNetAppender"></appender-ref>
</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="ConnectionStringDB" />
<commandText value="INSERT INTO dbo.Log4NetLog ([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>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs\web-log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="50000KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
</log4net>
<connectionStrings>
<add name="ConnectionStringDB" connectionString="Data Source=mydatabase;Initial Catalog=mycatalog;User Id=user;Password=password;TrustServerCertificate=true" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
And this is what I have in Program.cs:
var builder = WebApplication.CreateBuilder(args);
XmlConfigurator.Configure(new FileInfo("log4net.config"));
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddMemoryCache();
builder.Services.AddHttpContextAccessor();
builder.Host.ConfigureServices(services =>
{
//...services configuration
.
});
// Log4Net
builder.Host.ConfigureLogging(log =>
{
log.AddLog4Net("log4net.config");
log.SetMinimumLevel(LogLevel.Warning);
});
Here are a few things for you to check/fix...
In the database check that you have the correct table schema specified. The older AdoNetAppendeder class documentation shows the following table definition without an Exception column:
CREATE TABLE [dbo].[Log] (
[ID] [int] IDENTITY (1, 1) NOT NULL ,
[Date] [datetime] NOT NULL ,
[Thread] [varchar] (255) NOT NULL ,
[Level] [varchar] (20) NOT NULL ,
[Logger] [varchar] (255) NOT NULL ,
[Message] [varchar] (4000) NOT NULL
) ON [PRIMARY]
To be current (and also using your custom table name) it should instead be:
CREATE TABLE [dbo].[Log4NetLog] (
[Id] [int] IDENTITY (1, 1) NOT NULL,
[Date] [datetime] NOT NULL,
[Thread] [varchar] (255) NOT NULL,
[Level] [varchar] (50) NOT NULL,
[Logger] [varchar] (255) NOT NULL,
[Message] [varchar] (4000) NOT NULL,
[Exception] [varchar] (2000) NULL
)
Also your configuration is formatted as though it's intended to be in an App.config or Web.config file but your program code is loading it from log4net.config instead. To use a standalone .config file like that you need to have <log4net> as the root element, i.e.:
<?xml version="1.0"?>
<log4net>
<root>
<level value="ALL" />
<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="ConnectionStringDB" />
<commandText value="INSERT INTO dbo.Log4NetLog ([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>
Note that there's no <connectionStrings> element nor any other ASP.NET Core configuration in the above. To work around that you also need to replace the <connectionStringName> element with a <connectionString> element, i.e.:
<!-- ... --->
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<!-- NOPE: <connectionStringName value="ConnectionStringDB" /> -->
<connectionString value="Data Source=mydatabase;Initial Catalog=mycatalog;User Id=user;Password=password;TrustServerCertificate=true" />
<commandText value="INSERT INTO dbo.Log4NetLog ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception)" />
<!-- ... --->
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>
`
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.
I tried using log4net for logging info into db and I stuck with it now.Not sure what I am doing wrong.Whatever message i send its not received in the database,neither shows any error
I have a C# basic WINForm application and I am trying to insert log into db.
My log4net.xml below.
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="ADONetAppender" />
</root>
<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=CTI-OPT780-06\MSSQL2008; Initial Catalog=MYDB; Integrated Security = True;" />
<commandText value="INSERT INTO [Log] ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception)" />
<parameter>
<parameterName value="#log_date"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.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="#context" />
<dbType value="String" />
<size value="512" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%x" />
</layout>
</parameter>
</appender>
</log4net>
C# code to access it :
private ILog logger = LogManager.GetLogger(typeof(DBAccess));
public TestDB()
{
logger.Debug("Here is a debug log.");
logger.Info("... and an Info log.");
logger.Warn("... and a warning.");
logger.Error("... and an error.");
logger.Fatal("... and a fatal error.");
}
Create table for Log
CREATE TABLE [dbo].[Log]
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[Thread] [varchar](32) NOT NULL,
[Context] [varchar](512) NULL,
[Level] [varchar](512) NOT NULL,
[Logger] [varchar](512) NOT NULL,
[Message] [varchar](4000) NOT NULL,
[Exception] [varchar](2000) NULL
)
It would really great if someone points me where I m making mistake . Thanks
thanks for your wonderful help .Its so stupid of me I didnt do "configure" .
Added
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(sFIleName + "\\log4net.xml"));
and everything got fixed..
Using the debug trace as told by #sgmoore also helped to fix the db access rights issue.