I have enabled log4net and run my app which is giving an exception.
But the log file is empty.
Doesn't NHibernate log info about the exception???
Malcolm
You need to configure log4net. Just by adding log4net dll to the project doesn't log anything. You need to create appenders to specify where all the loggin should be directed to. Create a xml file like this one:
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs\Trace.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="30" />
<maximumFileSize value="1000KB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level - %message%newline" />
</layout>
<threshold value="DEBUG"/>
</appender>
<root>
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
...and configure it when starting up the application:
public static void Main()
{
var logconfig = new System.IO.FileInfo(PATH_TO_LOG_CONFIG);
if(logconfig.Exists)
{
log4net.Config.XmlConfigurator.ConfigureAndWatch(logconfig);
}
}
Related
I am new to log4net and I am just trying to get familiar with it in a console line app. Firstly I noticed from the few tutorials that the general configuration differs slightly, so it maybe the case that I have not got things setup properly.
The console printed fine, but the tutorial I was following placed the file in the same directory of the console app. I found with mine I had to give it the explicit path to my project to work.
Here is my Program.cs
static void Main(string[] args)
{
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead("log4net.config"));
var repo = LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
var logger = LogManager.GetLogger(typeof(Program));
logger.Error("Hello, World!");
}
Here is my config
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
<appender name="console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
<appender name="file" type="log4net.Appender.RollingFileAppender">
<file value="c:\users\dpg\developer\TestLogging\TestLog4Net\loggingfun.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="25MB" />
<lockingmodel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
you can use relative path for work folder
<file value="ErrorLog.txt"/>
for saving it to windows location such as LOCALAPPDATA
<file type="log4net.Util.PatternString" value="${LOCALAPPDATA}\Temp\Log\App.log" />
if using .NET core, and an environment variable like this:
<file type="log4net.Util.PatternString" value="${LOCALAPPDATA}\Temp\Log\App.log" />
the log file will end in App/bin/debug/${LOCALAPPDATA}\Temp\Log\App.log
I found a way to solve this problem, by using a GlobalContext property.
In code:
log4net.GlobalContext.Properties["LocalAppData"] = Environment.GetEnvironmentVariable("LOCALAPPDATA");
var repository = LogManager.GetRepository(Assembly.GetCallingAssembly());
XmlConfigurator.Configure(repository, new FileInfo("App.config"));
In App.config
<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
<param name="StaticLogFileName" value="true" />
<file type="log4net.Util.PatternString" value="%property{LocalAppData}\Temp\Log\App.log" />
<appendToFile value="true" />
<encoding value="utf-8" />
<rollingStyle value="Date" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%appdomain] [%thread] %-5level %logger - %message%newline%exception%newline" />
</layout>
</appender>
Those who are looking to set the file path to Project root dicrectory Path can refer below code. I have implemented this in .NET 5 API Project
Changes for Log4net.config file. Remember type="log4net.Util.PatternString" this line is very important
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%property{LoggerFilePath}\Logs\server.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %5level %logger.%method [%line] - MESSAGE: %message%newline %exception" />
</layout>
</appender>
Then, in Program.cs file
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((context,loggerBuilder) =>
{
log4net.GlobalContext.Properties["LoggerFilePath"] = context.HostingEnvironment.ContentRootPath;
loggerBuilder.ClearProviders();
loggerBuilder.AddLog4Net();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Cheers !
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
We are using log4net library with .NET Core for writing logs in file. But we are getting this error when executing the application "log4net:ERROR ConfigureFromXml called with null 'element' parameter".
Here is our Program.cs file:
public class Program
{
public static void Main(string[] args)
{
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead("log4net.config"));
var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));
log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Here is Configure method in Startup.cs file:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
loggerFactory.AddConsole(LogLevel.Trace);
loggerFactory.AddLog4Net();
app.UseIdentityServer();
}
Here is log4net.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
<!-- Log4net Logging Setup -->
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
<file value="c:\LogFiles\Applications\IdentityServer\log.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
</configuration>
Replace your log4net.config with below code :
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="C:\Temp\" />
<datePattern value="yyyy-MM-dd.'txt'"/>
<staticLogFileName value="false"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<maxSizeRollBackups value="100"/>
<maximumFileSize value="15MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level App %newline %message %newline %newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
In fact, the accepted response is not accurate, the problem with the XML is the .NET configuration on top of log4net configuration. The original configuration file is a .NET configuration file instead of a log4net one, and it's rooted with a configuration node instead of with a log4net node.
The second configuration XML on the other hand is correct, but it's replacing the original configuration (maybe with a better one, for sure), not only fixing the problem but replacing the original configuration with a new one.
The a better response for the change would be:
Remove the configuration root node from the original xml file together with the configSections node and leave the log4net node as root of the XML resulting in:
<?xml version="1.0" encoding="utf-8" ?>
<!-- Log4net Logging Setup -->
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender,log4net">
<file value="c:\LogFiles\Applications\IdentityServer\log.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO" />
<levelMax value="FATAL" />
</filter>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="FileAppender"/>
</root>
</log4net>
Reconfigure your appender with a Rolling appender if needed...
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
I have a .Net 4.0 windows service application that uses log4net.
Here's my log4net config.
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{Context}] - %message%newline" />
</layout>
</appender>
<appender name="ColorConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="FATAL" />
<foreColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="Blue, HighIntensity" />
</mapping>
<mapping>
<level value="INFO" />
<forecolor value="White, HighIntensity" />
</mapping>
<mapping>
<level value="DEBUG" />
<forecolor value="Green, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{Context}] - %message%newline" />
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<appendToFile value="true" />
<datePattern value="yyyyMMdd" />
<file value="Logs/Server.log" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{Context}] - %message%newline" />
</layout>
<maximumFileSize value="10MB" />
<rollingStyle value="Composite" />
<staticLogFileName value="true" />
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{Context}] - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="ColorConsoleAppender" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
Logging works as expected when the service starts up while using the exe that was built in debug mode (log files are created at the right file path), but doesn't work when it is using the exe built in release mode.
I've tried using a recompiled log4net dll for .Net 4.0 following the steps mentioned at this blog.. http://tseonet.blogspot.com/2010/07/making-log4net-run-on-net-40.html.
But, that didn't work either.
Any help is greatly appreciated.
I suggest to turn on internal debugging as explained here:
log4net - Appenders not working in IIS7.5
Thanks Deepu
adding [assembly: log4net.Config.XmlConfigurator(Watch = true)] to the assemblyInfo file worked for me
I stumbled upon the same issue today and after going through log4net docs did the following and it worked for me.
log4net.Config.XmlConfigurator.Configure();
Thought it will be worth sharing. Below is the logger class which uses log4net as provider
/// <summary>
/// Logger class using log4net library
/// </summary>
public class Log4NetLogger : ILogger
{
public Log4NetLogger(Type configType)
{
log4net.Config.XmlConfigurator.Configure();
this._logger = LogManager.GetLogger(configType);
}
}
For me assembly attribute was not an option as I wrapped logging functionality into a separate assembly where log4net was one of the providers.