I'm using log4net
in order to create a log, but it doesn't do anything.
Here is the app.config
:
<?xml version="1.0" encoding="utf-8">
<configuration>
<configSection>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSection>
<log4net>
<appender name="WriteToFile" type="log4net.Appender.FileAppender">
<file value="log.txt" />
<layout ="log4net.Layout.SimpleLayout" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="WriteToFile"/>
</root>
</log4net>
</configuration>
I have the following line in AssemblyInfo.cs
:
[assembly: log4net.Config.XmlConfigur(ConfigFile ="App.config", Watch= true)]
Here is an attempt to write to the file:
private static readonly ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void write()
{
log.Info("Some text here");
}
And the following line:
log4net.Config.XmlConfigurator.Configure();
If this is an executable I suppose that your config file is not called App.config
at the resulting bin folder but rather MyApp.exe.config
. So you may try fixing this:
ConfigFile ="App.config"
You can also skip the config file name if you are using the default:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Also make sure that the account you are running your application under has write permission to the folder in which you expect the log file to be written.
UPDATE:
Step by step guide:
Use the following in your App.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="WriteToFile" type="log4net.Appender.FileAppender">
<file value="log.txt" />
<layout type="log4net.Layout.SimpleLayout" />
</appender>
<root>
<level value="ALL" />
<appender-ref ref="WriteToFile" />
</root>
</log4net>
</configuration>
And in your Program.cs
:
using log4net;
using System.Reflection;
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace ConsoleApplication1
{
class Program
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
log.Info("Some text here");
}
}
}
I have only been successful with log4net when I ran the static Configure
method:
log4net.Config.XmlConfigurator.Configure();
Wrapping it in one method below read default config for the application, be it web.config or app.config:
private static void InitLogging()
{
log4net.Config.XmlConfigurator.Configure();
_logger = Common.Logging.LogManager.GetLogger(typeof(Program));
_logger.Debug("Logging initialized");
}
It seems more elegant with an decorator attribute the way you are suggesting, but the above mentioned may be worth a try.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With