log4net log being created but remaining empty - c#

I'm attempting to use log4net. When I fire up the app it creates the log file, but no matter how many times I call Log.Info("Application Started"); it remains empty. I've researched the first two pages that google returns and my code seems to match all examples.
Code:
[assembly: XmlConfigurator(Watch = true)]
namespace Generator
{
public class Run
{
private static readonly log4net.ILog Log =
log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public List<BILL_RUN> PerformBillRun()
{
XmlConfigurator.Configure();
Log.Info("Application Started");
var enabled = Log.IsInfoEnabled; //This is true
}
}
}
app.config
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="log-files.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="All" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
Any pointers as to what may be wrong?

This always happens to me...as soon as I post the question.
It turns out my <configSections></configSections> tags weren't directly a child to <configuration> meaning that the config wouldn't be picked up (I assume), and because log4net swallows all exceptions this only manifested itself further into my app.
Logging is working fine now.

Related

Cannot get log4net to write a log for a browser helper object (BHO) dll

I'm at my wits end, is it even possible to use log4net with an internet explorer browser helper object (BHO). I've tried just about everything I can find on the web and still no logfile.
My configuration is a separate log4net.config file and a bho that is designed to secure the browser for test takers. The log4net.config file is being picked up by the app and seems to be working, even to the point of an 'IsDebugEnabled' query. It seems to execute the write but nothing results.
My log4net.config
enter code here
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="c:\Logs\lockdown.txt" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<!--<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="DEBUG" />
<levelMax value="FATAL" />
</filter>-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p %d %-22.22c{1} %-25.25M - %m%n" />
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="FileAppender" />
</root>
</log4net>
</configuration>
public BHO()
{
LoadLogging();
_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
if (_log.IsDebugEnabled)
_log.Debug("************** Browser session started *************");
}
public void LoadLogging()
{
Debugger.Launch();
if (!log4net.LogManager.GetRepository().Configured)
{
var codeBase = Assembly.GetExecutingAssembly().CodeBase;
var uri = new UriBuilder(codeBase);
var pathDataString = Uri.UnescapeDataString(uri.Path);
var path = Path.GetDirectoryName(pathDataString);
var configFile = new FileInfo(path + "\\log4net.config");
if (!configFile.Exists)
{
throw new FileLoadException($"The configuration file {configFile} does not exist.");
}
log4net.Config.XmlConfigurator.Configure(configFile);
}
}
Any help would be appreciated ...
Whilst it may be possible (but unlikely) that BHOs are blocked from writing to a file, I doubt it would be blocked from writing to the debug window.
Try configuring log4net to write to the debug window:
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="DebugAppender"/>
</root>
<appender name="DebugAppender" type="log4net.Appender.DebugAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{dd.MM.yyyy HH:mm:ss.ffff} [%thread] %level %logger%exception - %message%newline" />
</layout>
</appender>
</log4net>

How to write text into log4net file

I have a C# application. I would like to integrate a log File. Then I try do this in App.config
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="logfile.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
</layout>
</appender>
<appender name="InfoFileAppender" type="log4net.Appender.FileAppender">
<file value="info_logfile.txt" />
<appendToFile value="true" />
</appender>
<appender name="ErrorFileAppender" type="log4net.Appender.FileAppender">
<file value="error_logfile.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="FileAppender" />
<level value="INFO" />
<appender-ref ref="InfoFileAppender" />
<level value="ERROR" />
<appender-ref ref="ErrorFileAppender" />
</root>
</log4net>
So I try to write in infoFile:
log.Info("chiamata json");
but I don't see any text in info_logfile.txt
Where is my error?
Can we help me?
Reguards
Do you instantiate your log file? Try the following to see that it works with a console appender. (this example is copied from David Saltner)
using log4net;
using log4net.Config;
public class LogTest
{
private static readonly ILog logger =
LogManager.GetLogger(typeof(LogTest));
static void Main(string[] args)
{
BasicConfigurator.Configure();
logger.Debug("Here is a debug log.");
logger.Info("... and an Info log.");
logger.Warn("... and a warning.");
logger.Error("... and an error.");
logger.Fatal("... and a fatal error.");
}
}
.
private static readonly ILog logger =
LogManager.GetLogger(typeof(LogTest));
This creates a logger for the class LogTest. You don't have to use a different logger for each class you have, you can use different loggers for different sections or packages within your code. The class of the logger is output to the log so you know where any logged information has come from.
BasicConfigurator.Configure();
This method initializes the log4net system to use a simple Console appender. Using this allows us to quickly see how log4net works without having to set up different appenders.
This should get you started. Check out this great article for a brief introduction on how to set up appenders and more.
If the configuration is in your app.config file you need to add the sections in the config file:
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0,
Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
It is better practice to configure your log4.net is a log4net.config file. Then you need to add the following line to your assembly which reads your configuration file:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Not able to get log4net working to write to file

I am using sharpdevelop to create a console application in C#. I have added in the reference for log4net and I added my logging statements while I was writing the code but I never looked at the log file. Now I am done with the code I need to get the log file working. My program runs fine, even the logging statements, but I can't find the log file.
I have tried to cobble together a couple of examples on getting log4net working. I have the lines to read from the configuration and then to instantiate the object, these are the first lines in my program to run:
log4net.Config.XmlConfigurator.Configure();
ILog datalogger = LogManager.GetLogger("myLog"); //initiate the data logger
Then in various places throughout the code I have this:
datalogger.Info(DateTime.Now.ToString() + ": using file: " + ProDirectory.ToString() + #"\" + myProFile.ToString());
I have also put the following in my app.config file:
<appender name="myLogAppender" type="log4net.Appender.RollingFileAppender" >
<file value="myLog.log" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%n" />
</layout>
</appender>
<logger name="myLog">
<level value="All"></level>
<appender-ref ref="myLogAppender" />
</logger>
No matter what I do, I can't see the log file being produced. I have changed the directory and even paused the program to see if I could find a handle open to the log file. Each time I come up empty. Not sure what I could be doing wrong.
not sure if this will help. I also had hard times making log4net work in different scenarios.
I use log4net root xml node to specify the appender. hope it will help.
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="250KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
UPDATE
You might also want to check Visual Studio output log. First setup the output log to log "ALL" (somewhere in VS settings). Then you should see exact error message of log4net in the output window of Visual Studio.
Whenever I have had issues with log4net creating the log file, it usually wound up being a file / directory permissions issue.
Change your <file value="log.txt" /> to something that you know will be accessible by the current user / process running devhost.
For example: <file value="%USERPROFILE%\Documents\log.txt" /> will create a log file in the user's My Documents folder. This is a folder that the user has permissions to write data to, and shouldn't give you any troubles with.
For more information on special folder values, see this link.
Looks like I just had to clean up my XML a little, after I did the log file is working fine:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections> <!-- Level 1 -->
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,
log4net"/> <!-- Level 2 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>
<log4net>
<appender name="myLogAppender" type="log4net.Appender.RollingFileAppender" >
<file value="myLog.log" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %level - %message%n" />
</layout>
</appender>
<logger name="myLog">
<level value="All"></level>
<appender-ref ref="myLogAppender" />
</logger>
</log4net>
</configuration>

programatically altering the fileappender of log4net

I am trying to set up logging using log4net, with no prior experience of log4net, in a wpf application
taken from this SO answer, I have
public partial class App : Application
{
private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected override void OnStartup(StartupEventArgs e)
{
XmlConfigurator.Configure();
base.OnStartup(e);
//Set data directory
string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + #"\BlowTrial";
if (!Directory.Exists(baseDir))
{
Directory.CreateDirectory(baseDir);
}
//Set logging
foreach (var appender in LogManager.GetRepository().GetAppenders())
{
var fileAppender = appender as FileAppender;
if (fileAppender != null)
{
fileAppender.File = fileAppender.File.Replace("|DataDirectory|", baseDir);
...
but there are no elements in LogManager.GetRepository().GetAppenders() despite the app.config having the following within the configuration node:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender"/>
<appender-ref ref="ColoredConsoleAppender"/>
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="|DataDirectory|\log.txt"/>
<param name="AppendToFile" value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="1MB"/>
<staticLogFileName value="false"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger: %message%newline"/>
</layout>
</appender>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger: %message%newline"/>
</layout>
</appender>
</log4net>
I was wondering why the appender "LogFileAppender" is not an element within the LogManager.GetRepository().GetAppenders() method, and how I might change the name of the file?
Thanks for your expertise
The RollingFileAppender does some stuff internally when it's initialized (using XmlConfigurator.Configure();), which results in the path of |DataDirectory|\log.txt throwing a System.ArgumentException when trying to retrieve the path. You can view how to debug log4net if you want more details here.
According to this answer, since you're using a special folder path anyways, you can specify this in the app.config, and not worry about setting the path from the code:
<param name="File" type="log4net.Util.PatternString" value="%envFolderPath{CommonApplicationData}\\BlowTrial\\log.txt"/>

log4net not working in dll

I'm currently having issues with getting log4net to work within a particular dll. I'm currently using log4net in other dlls being called by my test app and logging is working fine within those dlls and also within my test app. It's this one particular dll that I'm having trouble with. Here is snippet of code from the dll I'm having trouble with.
//This is from ABC.dll
public class SessionFactory
{
protected static ISessionFactory sessionFactory;
private static readonly ILog log = LogManager.GetLogger(typeof(SessionFactory));
private static void Init()
{
try
{
//Read the configuration from hibernate.xml.cfg or app.config
Configuration normalConfig = new Configuration().Configure();
ConfigureNhibernateValidator(normalConfig);
log.Debug("Initializing session factory");
sessionFactory = Fluently.Configure(normalConfig)
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<OrderHeaderMap>()
.Conventions.AddFromAssemblyOf<PascalCaseColumnNameConvention>())
.ProxyFactoryFactory("NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu")
.BuildSessionFactory();
log.Debug("Finished initializing the session factory");
}
catch(Exception ex)
{
//Code not shown
}
}
}
In my test app I am calling:
log4net.Config.XmlConfigurator.Configure();
Here is my log4net configuration in my App.config file:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<!-- ALL|DEBUG|INFO|WARN|ERROR|FATAL|OFF -->
<root>
<level value="DEBUG"/>
<appender-ref ref="SpeedTest"/>
</root>
<!-- This is a default logger that nhibernate uses to push out all the SQL statements to-->
<logger name="NHibernate.SQL" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="NHibernateConsoleLog"/>
<appender-ref ref="NHibernateFileLog"/>
</logger>
<!-- This is a default logger that nhibernate uses to push out all the debugging type information to-->
<logger name="NHibernate" additivity="false">
<level value="DEBUG"/>
<appender-ref ref="NHibernateFileLog"/>
</logger>
<appender name="NHibernateConsoleLog" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<appender name="NHibernateFileLog" type="log4net.Appender.RollingFileAppender">
<file value="Logs/nhibernate.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
<appender name="SpeedTest" type="log4net.Appender.RollingFileAppender">
<file value="Logs/SpeedTest.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
</layout>
</appender>
</log4net>
</configuration>
Again logging is working fine within my test application using the SpeedTest appender but the logging within the above snippet of code is not working. I set breakpoints above on when it initializes the logger and it seems to hit it. I can post the log4net debug output if necessary but I didn't really see much. Just let me know if you need it and I will post.
Any suggestions as to why logging is not being recorded in the above snippet of code?
It seems that this issue was stemming from me changing the directory to all my external dependencies (log4net being one of them) awhile back in TFS. All I did was drop all my references in my visual studio project and re-add them from my new dependencies folder and everything worked as expected after this. Thanks for all those that helped here.
My suspicion would be that it isn't reading the configuration from the configuration file when you call configure.
If you add the following lines to your application, what do you see (either on the console, or in IDE output window, or by stepping through in the debugger):
var log4netConfig = ConfigurationManager.GetSection("log4net");
var log4netConfigIsNull = log4netConfig == null;
Console.WriteLine(log4netConfigIsNull);
Does it look like the configuration is actually available from the configuration file?
[Edit: in response to your comment]
If you now add another line of debug code to your app:
Console.WriteLine(log.IsDebugEnabled);
what output do you get? Does the logger think it is configured for debug logging? (I'm particularly interested in the behaviour of this in, or after, SessionFactory.Init).
The immediate thought would be that your logging code isn't getting hit, possibly due to an exception being thrown prior to your first log4net call. Can you put a log entry into a finally block, just to test that the logger works?

Categories

Resources