How to use log4net with Nunit? - c#

I have a DLL class that create log4net log:
[SetUpFixture]
public class Application
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
[SetUp]
private Application()
{
log4net.Config.BasicConfigurator.Configure();
ILog log = log4net.LogManager.GetLogger(typeof(Application));
log.Debug("This is a debug message");
log.Warn("This is a warn message");
}
}
and Log4Net.config:
<?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:\\mylogfile.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>
My program starts the nunit.exe by:
string nunitAppPath = #"C:\Program Files (x86)\NUnit 2.6.4\bin\nunit.exe";
Process.Start(new ProcessStartInfo(nunitAppPath));
and have a reference to DLL.
I have a text file in c name :mylogfile.txt, but it's always null.

Related

How to fix log4net console output configuration

I have created a Console App (.Net Framework) project for my NSelene UI automation project. Currently, I am configuring log4net. Unfortunately, I am unable to log into an output window (log4net is writing only into a file).
Test output showing next error:
log4net:ERROR XmlHierarchyConfigurator: No appender named [DebugAppender] could be found.
log4net:ERROR Appender named [DebugAppender] not found.
I have added [assembly: log4net.Config.XmlConfigurator(Watch = true)] into AssemblyInfo.cs file
app.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<appender name="DebugAppender "
type="log4net.Appender.DebugAppender">
<immediateFlush value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] -
%m%n" />
</layout>
</appender>
<appender name="RollingLogFileAppender"
type="log4net.Appender.RollingFileAppender">
<file value="log/SBT.UI.log"/>
<encoding value="utf-8"/>
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<datePattern value="yyyyMMdd"/>
<maxSizeRollBackups value="10"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{dd/MM/yyyy HH:mm:ss},
%message%newline"/>
</layout>
</appender>
<appender name="ConsoleAppender"
type="log4net.Appender.ConsoleAppender">
<param name="Threshold" value="DEBUG" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c [%x] -
%m%n" />
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingLogFileAppender"/>
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="DebugAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Project.cs
[SetUp]
public void Initialize()
{
logger.Debug("test1");
logger.Info("test2");
logger.Warn("test3");
logger.Error("test4");
logger.Fatal("test5");
}

log4net is not generating log.txt file

I built a basic windows service in c# in VS2017 straight from the project template Windows Service. Built no problem. Installed no problem.
Here is the app.config with log4net section:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
<log4net>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<backColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="White" />
<backColor value="Yellow" />
</mapping>
<mapping>
<level value="INFO" />
<foreColor value="White" />
</mapping>
<mapping>
<level value="DEBUG" />
<backColor value="Green" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="FileAppender" />
</root>
</log4net>
</configuration>
And I want to log some events, like here:
public partial class Service1 : ServiceBase
{
private ILog log = LogManager.GetLogger(typeof(Service1));
public Service1()
{
InitializeComponent();
XmlConfigurator.Configure();
}
protected override void OnStart(string[] args)
{
log.Info("OnStart");
}
protected override void OnStop()
{
log.Info("OnStop");
}
}
When I start the service, I dont see any log.txt file created in the folder where the exe resides (Debug\Bin).
Any idea why?
I think the issue here I think is that your log variable is being initialized prior to the constructor being called. So basically you are calling LogManager.GetLogger prior to calling XmlConfigurator.Configure()
Try initializing log in the constructor after configuring log4net and see if that solves your problem.
public Service1()
{
InitializeComponent();
XmlConfigurator.Configure();
log = LogManager.GetLogger(typeof(Service1));
}
Adding another answer since my previous hunch seemed to be wrong (or maybe you actually have two problems here). Assuming you posted your whole app.config file, it doesn't look like you declare the log4net config section anywhere in there:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
Perhaps that's the problem?
In my particular case, we always set the app.config file when initialize Log4Net on the Class Constructor:
log4net.Config.XmlConfigurator.Configure(new Uri(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "YouAppConfigFile.config")));
Log = log4net.LogManager.GetLogger("ServiceClass1");
Log.Info("ServiceClass1 Started!!!");

No log file when using log4net with XML configuration

I have a problem logging to a file when using log4net and my XML configuration in the app.config below. The logfile doesn't appear on the filesystem, so there is probably something wrong, but I can't figure out what it might be.
The code and configuration is shown below.
App.config
</configSections>
<log4net>
<appender name="Console" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<!-- Pattern to output the caller's file name and line number -->
<conversionPattern value="%5level [%thread] (%file:%line) - %message%newline" />
</layout>
</appender>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="example.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level %thread %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="Console" />
<appender-ref ref="RollingFile" />
<appender-ref ref="LogFileAppender" />
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<system.serviceModel>
<bindings />
<client />
</system.serviceModel>
<applicationSettings>
<NetSuiteClient.Properties.Settings>
<setting name="NetSuiteClient_com_netsuite_webservices_NetSuiteService"
serializeAs="String">
<value>https://webservices.netsuite.com/services/NetSuitePort_2016_1</value>
</setting>
</NetSuiteClient.Properties.Settings>
</applicationSettings>
</configuration>
Declaring:
private static readonly ILog _Log = LogManager.GetLogger(typeof(Form));
Calling:
private void Form1_Load(object sender, EventArgs e)
{
_Log.Info("Info");
_Log.Debug("Debug");
_Log.Error("Error");
}
Are you instructing Log4Net to look for its configuration in the app.config file? You can do that by using the following assembly-level attribute:
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
Example taken from here

log4net log file is not getting created in C#

log file is not getting created,
using below call to get logger and config file.
is it required to give full path for file?
private static readonly log4net.ILog logger = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
<?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" requirePermission="false"/>
</configSections>
<!-- Log4net Logging Setup -->
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="50" />
<maximumFileSize value="50MB" />
<staticLogFileName 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="RollingFileAppender" />
</root>
</log4net>
</configuration>
Does your code call
log4net.Config.XmlConfigurator.Configure();
on startup?
The <root> section I use has priority, not level:
<root>
<priority value="ALL" />
<appender-ref ref="LogFileAppender" />
</root>
(Apparently, that's not the issue https://stackoverflow.com/a/24188507/21336)
after adding below line in AssemblyInfo.cs, could see log file getting created and logs coming.
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

log4net writes to one file, but should to different

I have two programs: program1 and program2 (they are modules of biggest program and could be run simultaneously), which of them use log4net.dll. Log4net.dll is one and shared between both programs. Each program has its own log configuration. Configurations are only different by logging path.
First path:
"..\Logs\Program1\Log_%date{yyyyMMdd}.log"
Second path:
"..\Logs\Program2\Log_%date{yyyyMMdd}.log"
Here is an example of logging configuration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="..\Logs\Program1\Log_%date{yyyyMMdd}.log" />
<appendToFile value="true" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger � %message%newline" />
</layout>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
</configuration>
Everything works almost fine, but sometimes program2 writes log to program1 log file. It looks like log4net.dll cached program1 logging settings, and when program2 asked to log, framework uses the same settings. Please suggest, how can I resolve it?
In order for the two programs to write to the same file, you should define loggers for each in their config files.
So, instead of just defining a <root> logger, define a specific logger for Program1 in its config, and the same for Program2 in its config:
<!-- program1.config -->
<appender name="Program1RollingFileAppender"
type="log4net.Appender.RollingFileAppender"> …
<logger name="Program1">
<level value="INFO" />
<appender-ref ref="Program1RollingFileAppender" />
</logger>
<!-- program2.config -->
<appender name="Program2RollingFileAppender"
type="log4net.Appender.RollingFileAppender"> …
<logger name="Program2">
<level value="INFO" />
<appender-ref ref="Program2RollingFileAppender" />
</logger>
Then, in each program, instantiate a logger with the same name, and it will pick up the correct appender:
public class Program1
{
ILog log = LogManager.GetLogger("Program1"); …
public class Program2
{
ILog log = LogManager.GetLogger("Program2"); …

Categories