mvc 4 log4net not working - asp.net-mvc-4

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\".

Related

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

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.

NHibernate Doesn't Log Errors

I'm getting an NHibernate exception that I want to try to get more info on, but it doesn't seem to be logging errors. I was actually looking to get more granular error info, but discovered the initial problem of not logging errors at all.
Here's my log4net sectionf rom config file:
<log4net>
<appender name="NHibernateAppender" type="log4net.Appender.RollingFileAppender">
<file value=".\\Logs\\NHibernate.log" />
<appendToFile value="true" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10000KB" />
<rollingStyle value="Size" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<header value="[Header]
" />
<footer value="[Footer]
" />
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="NHibernateSQLAppender" type="log4net.Appender.RollingFileAppender">
<file value=".\\Logs\\NHibernate.Sql.log" />
<appendToFile value="true" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10000KB" />
<rollingStyle value="Size" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<header value="[Header]
" />
<footer value="[Footer]
" />
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<logger name="NHibernate" additivity="false">
<level value="ERROR" />
<appender-ref ref="NHibernateAppender" />
</logger>
<logger name="NHibernate.SQL" additivity="false">
<level value="ERROR" />
<appender-ref ref="NHibernateSQLAppender" />
</logger>
</log4net>
I've tried "ALL" as well; it writes "DEBUG" and "INFO", but no "ERROR" entries. Any suggestions? Thanks!
If you add this into your web.config:
<appSettings>
...
<add key="log4net.Internal.Debug" value="true"/>
</appSettings>
And:
<system.diagnostics>
<trace autoflush="true">
<listeners>
<add name="textWriterTraceListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="log.txt" />
</listeners>
</trace>
</system.diagnostics>
This will show up any problems log4net may be having itself, e.g. trying to configure your appenders.

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.

Can't get log4net to output anything when using NHibernate

I have this in my web.config file (edited to reflect some changes):
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net debug="true">
<appender name="DebugAppender" type="log4net.Appender.AspNetTraceAppender">
<layout type="log4net.Layout.PatternLayout, log4net">
<param name="ConversionPattern" value="%d %p %m%n" />
</layout>
</appender>
<appender name="DataLog" type="log4net.Appender.RollingFileAppender">
<file value="c:\temp\nhlog.txt" />
<appendToFile value="true" />
<maximumFileSize value="100MB" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<priority value="DEBUG" />
<appender-ref ref="DebugAppender" />
</root>
<logger name="NHibernate" additivity="false">
<level value="INFO"/>
<appender-ref ref="DebugAppender"/>
</logger>
</log4net>
I'm calling log4net.Config.XmlConfigurator.Configure() from Application_Start().
I have [assembly: log4net.Config.XmlConfigurator(Watch = true)] in the AssemblyInfo.cs file in my web project.
Why do I get no NHibernate debugging messages in my output window? (I trying to get ALL of the messages that NHibernate spits out.) If I use the RollingFileAppender it works fine. I've tried the DebugAppender, TraceAppender, OutputDebugStringAppender, and AspNetTraceAppender and none of them output stuff to the output window.
Try using a different appender.
ConsoleAppenders probably don't work for web applications. Use something like a FileAppender.
See this for examples on configuraiton.
Similar to quip's answer, ConsoleAppender is not the right appender to use in a web application. An OutputDebugStringAppender will give you messages in your debug window. You may also want to look into AspNetTraceAppender.
You could try to associate the specific NHibernate logger with a log4net appender.
If you want to log all the generated sql, try adding this to your log4net config section:
<logger name="NHibernate.SQL" additivity="false">
<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
</logger>
If, for some reason, you only wanted to log Select statements and diagnostic info, you could use NHibernate.Loader.Loader, like this:
<logger name="NHibernate.Loader.Loader" additivity="false">
<level value="INFO" />
<appender-ref ref="ConsoleAppender" />
</logger>

nHibernate disables my log4net logs

So, we had a little ETL app that had some issues with updates. Which were nicely solved in an afternoon sprint with nHibernate. But this app relied upon log4net to push logging output to a few different destinations based upon command line switches. Once we got nHibernate wrapped into the app, it ETL'd flawlessly. But the logging functions failed completely. From the debugger's point of view, any of our loggers have all log4net's levels disabled.
Here's the log4net config:
<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="import-" />
<staticLogFileName value="false" />
<appendToFile value="false" />
<rollingStyle value="Date" />
<maxSizeRollBackups value="5" />
<datePattern value="yyyyMMdd-HHmm".log"" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level - %message%newline" />
</layout>
</appender>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level : %message%newline" />
</layout>
</appender>
<appender name="Email" type="log4net.Appender.SmtpAppender">
<to value="wwb#example.com" />
<from value="PeepsImporter#example.com" />
<subject value="Cte Importer Error" />
<smtpHost value="smtp.example.com" />
<bufferSize value="512" />
<lossy value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date %-5level : %message%newline%newline%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
</root>
<logger name="Console">
<level value="INFO" />
<appender-ref ref="Console" />
</logger>
<logger name="File">
<level value="INFO" />
<appender-ref ref="RollingFile" />
</logger>
<logger name="DebugConsole">
<level value="DEBUG" />
<appender-ref ref="Console" />
</logger>
<logger name="DebugFile">
<level value="DEBUG" />
<appender-ref ref="RollingFile" />
</logger>
<logger name="EmailErrors">
<level value="ERROR" />
<appender-ref ref="Email" />
</logger>
</log4net>
Not sure what other code would help, but I'm happy to post anything else from this app.
What version of NHibernate are you using? Builds older than 1.0-RC1 turned logging on internally. In 1.0-RC1 they changed this so you have to manually call log4net.XmlConfigurator.Configure(). This was done to give developers more control over logging.
You could try turning on the internal debugging in log4net: See this section in the following link:
"How do I enable log4net internal debugging?"
http://logging.apache.org/log4net/release/faq.html