Log4net is not logging anything - asp.net

I cannot get log4net working on my ASP.NET project. My web.config looks like this:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net debug="true">
<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="CardGame.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
</log4net>
And my LogHelper class looks this:
public class LogHelper
{
private static LogHelper _instance = new LogHelper();
private static volatile object _lock = new object();
public ILog Logger;
public static LogHelper Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new LogHelper();
}
}
return _instance;
}
}
private LogHelper()
{
Logger = LogManager.GetLogger(typeof(LogHelper));
Logger.Debug("Debug message");
Logger.Warn("Warn message");
Logger.Error("Error message");
Logger.Fatal("Fatal message");
}
}
I have also added the line
log4net.Config.XmlConfigurator.Configure();
to Application_Start in global.asax.cs
However none of the loggings in the constructor works and I am running out of ideas on why it does not work.

Make sure that the user running the app has write permissions on the target folder.
I always test that case by adding everyone and restarting the pool. If it works you know it's a permissions issue, otherwise check the code/config.

Which version are you using ? this is setting from my web.config
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Log.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="30" />
<maximumFileSize value="15MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<!--<conversionPattern value="%-5p %d %5rms [%thread] %-22.22c{1} %-18.18M - %m%n" />-->
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<!-- Options are "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" and "OFF". -->
<level value="ALL" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>

Related

Log4net not working with windows service written by netcore

I have a windows service application which written by .net core.
In application, i using Log4net to log information to file but nothing is logged.
I tried to change application to console app, any thing is OK.
Please tell me how to fix this issue. Below is my logging config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler"/>
</configSections>
<log4net>
<root>
<level value="ERROR" />
<appender-ref ref="System_Appender"/>
</root>
<logger name="System">
<level value="DEBUG" />
<appender-ref ref="System_Appender" />
</logger>
<appender name="System_Appender" type="log4net.Appender.RollingFileAppender">
<file value="Logs\System.txt"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maximumFileSize value="1MB" />
<maxSizeRollBackups value="10" />
<encoding value="utf-8" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c - %m%n"/>
</layout>
</appender>
</log4net>
</configuration>
I spent a lot of time messing with log4net .Net Core 3.1 running as a service. I will give some suggestions and code and configuration to review.
Running windows services with service account that has access to the logging and other databases doesn't log to the database
with log4net.
Running as a process but not as a service there was no problem with the log4net configuration. Only when running as a service
did the log4net not add logs to the database.
public static void Main(string[] args)
{
System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
Configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
// run as a console or as a service, configure in appsettings.json
_runAsService = Configuration["RunAsService"].ConvertToBool();
_ServerCertThumbprint = Configuration["ConfigSettings:ServerCertThumbprint"];
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureAppConfiguration((context, config) =>
{
// configure the app here.
}).ConfigureServices((hostContext, services) =>
{
services.AddLogging(logging =>
{
logging.AddConfiguration(Configuration.GetSection("Logging"));
logging.ClearProviders();
logging.AddLog4Net("log4net.config", true);
// logging.AddConsole();
logging.AddDebug();
logging.AddEventLog();
logging.SetMinimumLevel(LogLevel.Trace);
// logging.AddLog4Net("log4net.config", true );
}).Configure<LoggerFilterOptions>(options => options.MinLevel = LogLevel.Information);
services.AddSingleton(x);
services.AddSingleton<xxx>();
services.AddSingleton<xxx>();
services.AddSingleton<IXXX, XXX>();
services.AddSingleton<XXX>();
services.AddHostedService<Worker>();
});
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender" >
<file value="logfile.log" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level %logger - %message%newline" />
</layout>
</appender>
<appender name="AdoNetAppender" type="MicroKnights.Logging.AdoNetAppender, MicroKnights.Log4NetAdoNetAppender">
<bufferSize value="1" />
<!--<connectionType value="System.Data.SqlClient.SqlConnection, System.Data" />-->
<connectionType value="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient, Version=1.0.0.0,Culture=neutral,PublicKeyToken=23ec7fc2d6eaa4a5"/>
<connectionStringName value="Log4Net" />
<connectionStringFile value="appsettings.json" />
<commandText value="INSERT INTO dbo.Log

log4net AdoNetAppender in .Net core not supported?

I'm trying to implement log4net 2.0.8 in our dot net core 1.1.2 app. The ConsoleAppender is working fine, but the AdoNetAppender throws an error:
Could not load type 'log4net.Appender.AdoNetAppender'
Is AdoNetAppender still not supported in Dot Net Core?
My config:
<?xml version="1.0" encoding="utf-8" ?>
<log4net debug="true">
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} [%thread] %-5level %logger: %message%newline" />
</layout>
</appender>
<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=MyMSSQLServer; initial catalog=MyDatabase;integrated security=false;persist security info=True;User ID=sa;Password=***" />
<commandText value="dbo.prcLog4Net_LogMsg" />
<commandType value="StoredProcedure" />
<parameter>
<parameterName value="#session_id" />
<dbType value="Int" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{session_id}" />
</layout>
</parameter>
<parameter>
<parameterName value="#message" />
<dbType value="AnsiString" />
<size value="4000" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</parameter>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="AdoNetAppender" />
</root>
</log4net>
The ado.net appender is not supported, you can look it up in the following page:
framework-support.html#Appenders

TimeEvaluator for SmtpAppender in log4net doesn't work for web project

I have an ASP.NET web app that uses log4net to log to various appenders. I have successfully added a SmtpAppender with a LevelEvaluator and can get e-mails to be sent with this; however if I replace this with a TimeEvaluator I cannot get e-mails to send.
My appender with the LevelEvaluator looks like this (this is working):
<appender name="EmailErrorAppender" type="log4net.Appender.SmtpAppender">
<to value="to#myemail" />
<from value="from#myemail" />
<subject value="Alert Subject" />
<smtpHost value="mymailhost" />
<bufferSize value="50" />
<lossy value="true" />
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="FATAL" />
</filter>
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="ERROR"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger%newline%newline" />
</layout>
</appender>
The problematic appender with the TimeEvaluator looks like this (this is not working):
<appender name="EmailErrorAppender" type="log4net.Appender.SmtpAppender">
<to value="to#myemail" />
<from value="from#myemail" />
<subject value="Alert Subject" />
<smtpHost value="mymailhost" />
<bufferSize value="50" />
<lossy value="true" />
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="FATAL" />
</filter>
<evaluator type="log4net.Core.TimeEvaluator">
<interval value="30"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger%newline%newline" />
</layout>
</appender>
I've checked log4net's internal debug and it says it is loading it fine.
I would appreciate any help - is TimeEvaluator broken in an ASP.NET web context?

log4net not logging to event viewer from IIS

I have a web service set up in my IIS, the appender that logs to a text file is working fine (the text file is in the same directory as where the web service is running from). The appender that writes to the Event Viewer isn't working, I'm currently connected to the web service as administrator so I should in theory be able to do this, what else should I check/see if I'm missing?
log4net.config:
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{ABSOLUTE} [%thread] %level %logger - %message%newlineExtra Info: %property{testProperty}%newline%exception"/>
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO"/>
<levelMax value="FATAL"/>
</filter>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<param name="ApplicationName" value="Lending Service" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message %newline %exception" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="INFO"/>
<levelMax value="FATAL"/>
</filter>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<threshold value="DEBUG"/>
<file value="webLog.log"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="5"/>
<maximumFileSize value="10MB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline%exception"/>
</layout>
</appender>
<root>
<appender-ref ref="RollingFileAppender"/>
<appender-ref ref="EventLogAppender" />
</root>
<logger name="LendingService.Global_asax">
<appender-ref ref="RollingFileAppender"/>
<appender-ref ref="EventLogAppender" />
</logger>
<logger name="LendingService.LendingService">
<appender-ref ref="RollingFileAppender"/>
<appender-ref ref="EventLogAppender" />
</logger>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
The best way to find out what is going wrong is enable log4net interal debug, this will tell you where log4net is failing:
<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>
Log4net FAQ

log4net won't write to the visual web developer console

this is my config for log4net but it wont write to the console
see appender: ConsoleAppender
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<param name="File" value="C:\Users\name\Documents\visual studio 2010\Projects\logs\logfile.txt" />
<param name="AppendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %C %m%n%newline" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %C %m%n%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
</log4net>
</configuration>
Why doesn't it write to the console?
Edit 1
This is how I initialize it:
log4net.Config.XmlConfigurator.Configure(new FileInfo("C:\\Users\\name\\Documents\\Visual Studio 2010\\Projects\\ExecutionEngine\\Libraries\\App.Config"));
Thanks
You can use the trace appender for this purpose. For instance like this:
<appender name="TraceAppender"
type="log4net.Appender.TraceAppender" >
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-6level - %message%newline" />
</layout>
</appender>

Resources