Configure Nhibernate log into file - nhibernate

I have programmatically create log4net log from config file:
var properties = new NameValueCollection
{
{"configType", "FILE"},
{"configFile", #"c:/log4net.config"}
};
Common.Logging.LogManager.Adapter = new Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter(properties);
This is my log4net.config (EDITED for simplicity as dove suggested) :
<log4net>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="c:/log.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="5" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<level value="All" />
<appender-ref ref="RollingFile" />
</root>
<logger name="NHibernate">
<level value="All" />
<appender-ref ref="RollingFile" />
</logger>
</log4net>
I got Spring.NET successfuly logging into that file, but not NHibernate.
Nhibernate is configured fluenltly:
protected override void PostProcessConfiguration(Configuration config)
{
base.PostProcessConfiguration(config);
var msSqlCfg = MsSqlConfiguration.MsSql2000.ConnectionString(ConnectionString)
.ShowSql();
Fluently.Configure(config).Database(msSqlCfg)
.Mappings(m => m.FluentMappings.Add<EmployeeMap>())
// Other mappings
.BuildSessionFactory();
}
What should I fix to get Nhibernate log working?

Does it log if you generate statistics?
Configuration.ExposeConfiguration(c =>
c.SetProperty("generate_statistics", "true"));
To narrow things down can you remove additivity flag and appeder from within logger and just log one to start, i.e. exactly like this
<logger name="NHibernate">
<level value="ALL" />
</logger>

Related

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

Nhibernate show_sql=false not working

This is how I create Session Factory using Fluent Nhibernate
public static ISessionFactory CreateSessionFactory()
{
FluentNHibernate.Cfg.FluentConfiguration fconfig;
fconfig = FluentNHibernate.Cfg.Fluently.Configure()
.Cache(c=>c.UseQueryCache())
.Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
.ConnectionString(c => c.FromConnectionStringWithKey("Database"))
.ProxyFactoryFactory<NHibernate.ByteCode.LinFu.ProxyFactoryFactory>()
.Mappings(
m => m.FluentMappings
.AddFromAssemblyOf<NHibernateRepositoryRegistry>()
.Conventions.Add<Conventions.PrimaryKeyConvention>()
.Conventions.Add<Conventions.IdForeignKeyConvention>()
.Conventions.Add<Conventions.ReferenceForeignKeyConstraintNameConvention>()
)
// i have tried this but it did not work
//.ExposeConfiguration(config=>{config.SetProperty("show_sql", "false");});
return fconfig.BuildSessionFactory();
}
This is my log4net config inside Web.config
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="nhibernate.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level %thread %logger - %message%newline" />
</layout>
</appender>
<appender name="RollingFile2" type="log4net.Appender.RollingFileAppender">
<file value="nhibernatesql.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="INFO" />
<appender-ref ref="RollingFile" />
</logger>
<logger name="NHibernate.SQL">
<level value="ALL" />
<appender-ref ref="RollingFile2" />
</logger>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFile" />
</root>
</log4net>
I had ShowSql() setup perviously
and I was trying to set it via web.config appsettings so i can turn on or off based on configuration
so I removed ShowSql() and tried following ( right now i am just passing "false" value )
.ExposeConfiguration(config=>{config.SetProperty("show_sql", "false");});
also tried
.ExposeConfiguration(config=>{config.SetProperty("hibernate.show_sql", "false");});
but I am still getting sql generated in nhibernatesql.log file
I am using NHibernate v3.1.0.4000 and FluentNHibernate v1.2.0.712 and ASP.NET MVC3
does anyone know why sql is still generating?
does show_sql or ShowSql() is only meant for Console.output purpose and sql is sent to log4net regardless ?
my main concern is slow performance if ShowSQL is set to true
not sure whether I am setting ShowSql somewhere else
ok I think I got the answer
based on http://www.davesquared.net/2008/01/viewing-sql-generated-by-nhibernate.html
show_sql is used of Console.out purpose only and sql is sent to log4net regardless.. and that is why I am seeing sql in the logs

How can I get the previous logged events when a particular logger is triggered?

I need to show the previous 10 events when a particular logger is triggered. The goal is to show what previous steps occurred immediately before NHibernate.SQL logging was issued.
Currently, I am logging NHibernate sql to a separate file - this is working correctly.
<appender name="NHibernateSqlAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs\NHibernate.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10000KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{dd/MM/yy HH:mm:ss,fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<logger name="NHibernate.SQL" additivity="false">
<level value="ALL"/>
<appender-ref ref="NHibernateSqlAppender"/>
</logger>
<logger name="NHibernate" additivity="false">
<level value="WARN"/>
<appender-ref ref="NHibernateSqlAppender"/>
</logger>
But this only outputs SQL, without context. I would like all previous logs within a specified namespace to also be logged, but only when the HNibernate.SQL appender is triggered.
I have investigated the use of BufferingForwardingAppender as a means to collect all events, and then filter them within the NHibernateSqlAppender, but this is not working. I have read about the LoggerMatchFilter class, which seems like it is going to help, but I'm not sure where to put it.
<appender name="BufferingForwardingAppender" type="log4net.Appender.BufferingForwardingAppender" >
<bufferSize value="10" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ALL"/>
</evaluator>
<appender-ref ref="NHibernateSqlAppender" />
</appender>
<appender name="NHibernateSqlAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs\NHibernate.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10000KB" />
<staticLogFileName value="true" />
<filter type="log4net.Filter.LoggerMatchFilter">
<loggerToMatch value="NHibernate.SQL" />
<loggerToMatch value="Laan" />
</filter>
<filter type="log4net.Filter.LoggerMatchFilter">
<loggerToMatch value="NHibernate" />
<acceptOnMatch value="false"/>
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{dd/MM/yy HH:mm:ss,fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="BufferingForwardingAppender"/>
</root>
The idea is that buffering appender will store all events, but then the NHibernateSqlAppender will only flush when an NHibernate.SQL event fires, plus it will flush the buffer (of 10 previous items, within the specified logger level, which in this example is Laan.*).
I would implement ITriggeringEventEvaluator that returns true in the IsTriggeringEvent() method when a certain logger (ideally configurable) fires. Have a look a the implementation of the LevelEvaluator class, it should be quite easy. The code would look like this:
public bool IsTriggeringEvent(LoggingEvent loggingEvent)
{
if (loggingEvent == null)
{
throw new ArgumentNullException("loggingEvent");
}
return (loggingEvent.LoggerName == triggeringLoggerName);
}
With this new evaluator your configuration should work though you should remove the filters (I guess).

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>

Can't get NHibernate and Log4Net to generate logging.

I can't get any logging of NHibernate or my application. I tried EVERYTHING that I could think about, but nothing works!
Here is my code:
using System.Reflection;
using NHibernate.Cfg;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
namespace NHibernate_Log4Net
{
class Program
{
static void Main(string[] args)
{
var cfg = new Configuration()
.Configure()
.AddAssembly(Assembly.GetCallingAssembly());
}
}
}
namespace NHibernate_Log4Net.Model
{
public class Item
{
public int Id { get; set; }
public int Title { get; set; }
public int Alias { get; set; }
}
}
Item.hbm.xml file:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="NHibernate_Log4Net.Model.Item" assembly="NHibernate_Log4Net" auto-import="false">
<class name="User" table="Users">
<id name="Id">
<generator class="Native"/>
</id>
<property name="Title" length="255" not-null="true" />
<property name="Alias" length="255" not-null="true" />
</class>
</hibernate-mapping>
Log4Net.config file:
<?xml version="1.0" encoding="utf-8"?>
<log4net debug="false">
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log4netLogger.log" />
<appendToFile value="false" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1000KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<appender name="OutputDebugStringAppender" type="log4net.Appender.OutputDebugStringAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %m - %c -%n" />
</layout>
</appender>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date - %message%newline"/>
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
<appender-ref ref="OutputDebugStringAppender" />
<appender-ref ref="TraceAppender" />
</root>
<logger name="NHibernate" additivity="false">
<level value="FATAL"/>
<appender-ref ref="RollingFileAppender" />
<appender-ref ref="OutputDebugStringAppender" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="TraceAppender" />
</logger>
<logger name="NHibernate.SQL" additivity="false">
<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingFileAppender" />
</logger>
<!--
NHibernate.Loader.Loader logs diagnostic stuff and SELECTs.
You can use either logger, or both, depending on you needs.
-->
<logger name="NHibernate.Loader.Loader" additivity="false">
<level value="INFO" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingFileAppender" />
</logger>
</log4net>
NHibernate throws an error that the class Users doesn't exist. This is expected, but why do I not see any logging from this, from NHibernate?
(I can log it myself, but the point that I can't see any log from NHibernate).
The config file needs to match the executable, is your executable named Log4Net.exe?
I have had trouble using the XmlConfigurator attribute in the past. Perhaps you should just call XmlConfigurator explicitly in your main like so:
namespace NHibernate_Log4Net
{
class Program
{
static void Main(string[] args)
{
XmlConfigurator.ConfigureAndWatch(new FileInfo("log4net.config"));
var cfg = new Configuration()
.Configure()
.AddAssembly(Assembly.GetCallingAssembly());
}
}
}
If the logging levels set for the NHibernate loggers are too high (or off), you may not see any log messages from NHibernate. For example, what is the value of
((log4net.Repository.Hierarchy.Logger)LogManager.GetLogger("NHibernate").Logger).Level?
You should have a section in your config file like this:
<log4net>
<appender name="NHLog" type="log4net.Appender.FileAppender">
<file value="logs/nhibernate.log" />
<appendToFile value="false" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<logger name="NHibernate" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="NHLog"/>
</logger>
</log4net>
Update: If the log file is always created (when non-existent before a run) but is always empty, this points to an exception during appending. To minimise the possibility of an exception, have a very simple conversionPattern (perhaps just "%m%n") and see if any output is generated. If there is, add back elements of the conversion pattern until you find where the problem is. If no output is generated, log something to the NHibernate logger from your own code (this is perfectly OK) and step through it in the debugger.
ILog log = LogManager.GetLogger("NHibernate");
log.Info("Application starting");
If still no joy, you may have to post some of your code/configuration.
https://web.archive.org/web/20110514164829/http://blogs.hibernatingrhinos.com/nhibernate/archive/2008/07/01/how-to-configure-log4net-for-use-with-nhibernate.aspx
I used the above link to set up logging. Try the following
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
namespace NHibernate_Log4Net
{
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
var cfg = new Configuration()
.AddAssembly(Assembly.GetCallingAssembly());
.Configure()
}
}
}
The extra is this line
log4net.Config.XmlConfigurator.Configure();
It didnt work for me till I added that. I know this is somewhat similar to what Jeffery suggested, but... just my 2cents.
Also, shouldnt the Configure() call on the Nhibernate configuration object come last? After the Assembly is added?