Stuck setting up Log4Net - Saving to SQL database [duplicate] - sql

Description
I have a config file as a resource in my assembly and want to change the ConnectionString programmatically in my application.
I load the configuration using log4net.Config.XmlConfigurator.Configure.
I have some breakpoints and see that the configuration is loaded successfuly and the connectionstring is Data Source=localhost\SQLExpress;Initial Catalog=Log;Integrated Security=SSPI; (local SQLExpress).
Problem
Nothing happens, no exception and no log entry. Any ideas.
using (Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MyNamespace.Properties.log4net.config"))
{
// stream is NOT null
log4net.Config.XmlConfigurator.Configure(stream);
}
Hierarchy hier = LogManager.GetRepository() as Hierarchy;
if (hier != null)
{
//get ADONetAppender
var adoAppender = (AdoNetAppender)hier.GetAppenders().Where(appender => appender.Name.Equals("AdoNetAppender", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
if (adoAppender != null)
{
// update connectionstring
adoAppender.ConnectionString = configuration.GetConnectionString(ConnectionStringNames.Log).ConnectionString;
//refresh settings of appender
adoAppender.ActivateOptions();
}
}
ILog logger = LogManager.GetLogger("MyProject");
logger.Warn("Test");
content of the log4net.config file
<?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="[we will set this automatically at runtime]" />
<commandText value="INSERT INTO Log ([Date],[Level],[Logger],[Message],[Exception])
VALUES (#log_date, #log_level, #logger, #message, #exception)" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%p" />
</layout>
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<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="ALL" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
</configuration>

You can debug log4net by hooking into the log4net DebugAppender:
Add a log4net app setting in your app.config file:
<appSettings>
<!-- log4net configuration when running in debug mode. -->
<add key="log4net.Internal.Debug" value="true" />
</appSettings>
Add a debug appender in the log4net config:
<appender name="DebugAppender" type="log4net.Appender.DebugAppender">
<immediateFlush value="true" />
<layout type="log4net.Layout.SimpleLayout" />
</appender>
Add the appender to the log4net config root:
<root>
<level value="ALL" />
<appender-ref ref="AdoNetAppender" />
<appender-ref ref="DebugAppender" />
</root>
When you run your application, look in the output window of Visual Studio and you should see all the internal logging for log4net. If not, then the log4net config file is never loading.
Edit
If you can use a connection string from your app.config file, then remove the connection string from the log4net AdoNetAppender and just call the connection string by name:
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<bufferSize value="1" />
<!-- note: you can use the 4.0 assembly -->
<connectionType value="System.Data.SqlClient.SqlConnection,
System.Data,
Version=4.0.0.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089" />
<!-- This will retrieve a connection string by name from the app.config -->
<connectionStringName value="ConnectionStringNameFromAppConfig" />
<!-- snip -->
</appender>

Here are some things that I tried that worked out for me...
I wasn't seeing anything because my <appender-ref ref="AdoNetAppender" /> didn't properly reference my <appender name="AdoNetAppender" ... /> in the Web.config. The 'AdoNetAppender' names need to match.
Added <bufferSize value="1" /> to the <appender name="AdoNetAppender" /> section of the Web.config
I created a user account with a password on the SQL server instead of using windows authentication. Granted user access to perform selects and inserts on the table
In Global.asax.cs I initialize log4net using log4net.Config.XmlConfigurator.Configure();
In my C# code I instantiate a new adoAppender object and call logger.Info("save to db");
The documentation on Apache's website is helpful as well ...
http://logging.apache.org/log4net/release/config-examples.html#MS%20SQL%20Server
Hope that saves somebody some time and frustration. Thanks!

I had a log4net configuration running for years, that stopped logging to database this spring 2022.
I solved it by specifying: size value="7" to a DateTime2 database parameter in the log4net configuration. Type in database: datetime2(7), not null.
Why size on that type suddenly is madatory in log4net I don't know.

Related

Log4net cannot Write database using C#

I have already tried it and found many similar questions, but i can't see one data on my SQL.
Here it's my app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<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" />
<connectionString value="data source=.;initial catalog=dblog;integrated security=false;persist security info=True;User ID=bernie4;Password=GoodSQL" />
<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>
</log4net>
</configuration>
Here is another code ,i tried add to my app.config for code track, but i review my C drive or other position not found the log4net.txt or data.
<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>
Here is how I'm using C# Create to the log:
using System;
using System.Windows.Forms;
using log4net;
using System.Reflection;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
log4net.ILog log;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
}
private void button1_Click(object sender, EventArgs e)
{
log.Info("your data has been successfully saved.");
}
}
}
if these code successful work , i can see it show string is "your data has been successfully saved" on my SQL ,when i Triggered button1_Click event,but the database not showing nothing.
i watch many people has similar questions ,i tried edit my code,but still useless.
1.bufferSize value="1"
2.log4net.Config.XmlConfigurator.Configure();
3.name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"
finally , here is my software and dll version:
C# :2017
log4net.dll :2.0.8.0 -Net 4.5
SQL :2017
You don't see any logging (including no Log4net debug logging) because your App.config file doesn't get loaded as it isn't valid;
the <configSections> element must be the first child element under <configuration>.
With that in place, you will at least see the internal log4net debug logging.
If the AdoNetAppender has been configured correctly, the database logging will also be present; if not, you can refer to the debug logging.
Your App.config should look like here below.
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<appSettings>
<add key="log4net.Internal.Debug" value="true" />
</appSettings>
<log4net>
<!-- Your log4net configuration goes here -->
</log4net>
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add
name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="c:\tmp\log4net.txt" />
</listeners>
</trace>
</system.diagnostics>
</configuration>

Filter Asp.netcore logs in Log4Net

I am using ASP.NET Core and have created a Log4net logging provider.
My current log4net.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<log4net debug="true">
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\\" />
<appendToFile value="true" />
<DatePattern value="yyyy\\\\MM\\\\dd'.inf.log'" />
<rollingStyle value="Date" />
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %message%newline" />
</layout>
</appender>
<appender ref="HangfireLoggerAppender" type="log4net.Appender.RollingFileAppender">
<file value="logs\HangfireLog.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<logger additivity="false" name="Hangfire">
<level value="INFO" />
<appender-ref ref="HangfireLoggerAppender" />
</logger>
</log4net>
The log is showing A LOT of asp.net core junk. SQL Logs ect.
I would like to filter out :
Microsoft.AspNetCore.*
Microsoft.EntityFrameworkCore.*
How do I do this with Log4net?
you need to configure logging on your WebHostBuilder as follows :
[Program.cs -> BuildWebHost(string[] args) ]
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
ConfigureLogging((hostingContext, logging) =>
{ logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddFilter("Microsoft.AspNetCore", LogLevel.Information);
logging.AddFilter(" Microsoft.EntityFrameworkCore", LogLevel.Information);
logging.AddConsole();
logging.AddDebug();
})
.Build();
You call the logging.AddFilter method specifying the namespace as first parameter and LogLevel as the second parameter.
This can be also done using configuration in appsettings.json file if you don't want to do in code. You can read more here

mvc 4 log4net not working

i am tring to use log4net for log but it is not working
My log file is created empty, without data.
There is no NHibernate data and There is no USER data.
Does anybody know why?
I am tring to do like this:
web.config
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="log4net.Config" value="log4net.config"/>
<add key="log4net.Config.Watch" value="True"/>
</appSettings>
<log4net debug="true">
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender, log4net">
<file type="log4net.Util.PatternString" value="Logs/"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<staticLogFileName value="false"/>
<datePattern value="'MyLog_'yyyyMMdd'.log'"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss.fff} %-5level: %message%newline"/>
</layout>
</appender>
<logger name="LogEmArquivo">
<level value="DEBUG"/>
<appender-ref ref="FileAppender"/>
</logger>
<logger name="NHibernate">
<level value="WARN" />
</logger>
<logger name="NHibernate.SQL">
<level value="DEBUG" />
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="LogEmArquivo" />
</root>
</log4net>
On AssemblyInfo
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
On my Helper
log4net.Config.XmlConfigurator.Configure();
log = LogManager.GetLogger("LogEmArquivo");
What is wrong? i already tried many diferent way and the only things that is happining is create the file MyLog_20170303.log with no data.
I keep my log4net config in a seaprate file
Here's my complete file that works.
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="logs/error.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level %thread %logger - %message%newline" />
</layout>
</appender>
<logger name="NHibernate">
<level value="WARN" />
</logger>
<logger name="NHibernate.SQL">
<level value="DEBUG" />
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFile" />
</root>
Have you tried a simpler log configuration with a static log file name to see if it is your log4net configuration.
You can also turn on internal debugging for log4net to verify your configuration is valid. See this answer here How to track down log4net problems
Maybe are you encountering the LOG4NET-506 issue: latest versions of log4net issue an exclusive mutex named according to file configuration property.
It does not cause issues if the file configuration actually target a file.
But in your case, it is a directory. If you have many processes trying to log to that directory, only one of them will be able of logging.
As a workaround, I have instructed log4net in my cases to log in a Logs\ sub-directory dedicated to each application. Like: file="Logs\App1\".

log4net not inserting into database but working fine for file

I am using this code in WCF application in VS 2012, SQL Express is 2008 R2.
I have included the fileAppendor and Database Appendor, File Appender works fine but its not inserting data into the database.
I have verified the same connection string its working fine and inserting records in to the table.
Also I have set the buffer value to 1, still no luck
<bufferSize value="1" />
This is my config file
<?xml version="1.0"?>
<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=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<connectionString value="server=(local)\\SQLEXPRESS;database=Log_DB;Integrated Security=SSPI;Connection Timeout=360;" />
<connectionString value="data source=[(local)\\SQLEXPRESS];initial catalog=[Log_DB];integrated security=SSPI" />
<commandText value="INSERT INTO [Error_Log] ([Date_time] ) VALUES (#Date_time)" />
<parameter>
<parameterName value="#Date_time" />
<dbType value="DateTime" />
<!--<layout type="log4net.Layout.RawTimeStampLayout" />-->
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
</parameter>
</appender>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="log-file.txt"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] ID=%property{EventID} - %message%newline" />
</layout>
</appender>
<!-- Setup the root category, add the appenders and set the default level -->
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
...
</configuration>
Do I am missing any other stuff?
Also I am not getting any information by setting Internal.Debug to true.
How to get internal debug details of log4net?
Finaly I got the answer for this, I am sharing here since it may help others.
Need to use the System/Machine Name instead of (local) in the Connection string. Even with the dotnet application (local) works but for log4net need to use the System name.

ASP.NET MVC with Castle Logging and log4net woes

In my installer, I have
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.AddFacility<LoggingFacility>(f => f.UseLog4Net("log4net.config"));
}
My log4net config file (which gets deployed to the bin directory of my ASP.NET MVC app) is:
<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=GCO06773\SQLEXPRESS;initial catalog=GEMS;integrated security=false;persist security info=True;User ID=<<userid removed>>;Password=<<password removed>>#" />
<commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (#log_date, #thread, #log_level, #logger, #message, #exception)" />
<parameter>
<parameterName value="#log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="#thread" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%thread" />
</layout>
</parameter>
<parameter>
<parameterName value="#log_level" />
<dbType value="String" />
<size value="50" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="#logger" />
<dbType value="String" />
<size value="255" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="String" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
<parameter>
<parameterName value="#exception" />
<dbType value="String" />
<size value="2000" />
<layout type="log4net.Layout.ExceptionLayout" />
</parameter>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
I have a controller that's instantiated via Castle.Windsor The relevant code is:
public ILogger Logger { get; set; }
public ActionResult Index()
{
Logger.Info("Info");
Logger.Debug("Debug");
Logger.Error("Error");
Logger.Fatal("Fatal");
Logger.Warn("Warn");
return View();
}
The Logger is a valid castle logger and when I delve into it in the watch window, it appears that there are no appenders associated with the underlying log4net logger, except for the root appender.
According to procmon, the log4net.config file is actually being accessed at some point, so I'm assuming it's being read. I get no errors in the IIS log, no errors in the event log and no exceptions or errors that I can detect. I'm stumped.
UPDATE 1:
Forgot to mention, I added this:
<add key="log4net.Config" value="log4net.config"/>
to the web.config, but it didn't seem to change anything.
UPDATE 2:
I'm using Log4Net 1.2.10.0 with public key token: 1b44e1d426115821 (this matters with Castle Logging which is why I mention it).
The log4net.config file should be in root of your web, not in bin directory.