namespace Com.Foo
{
public class Bar
{
private static readonly ILog log = LogManager.GetLogger(typeof(Bar));
public void DoIt()
{
log.Info("Did it again!");
}
}
}
class Program
{
private static readonly ILog log = LogManager.GetLogger(typeof(Program));
static void Main(string[] args)
{
string sfile = #"C:\development\Framework\Logging\ConsoleApplication1\app.config";
XmlConfigurator.Configure(new System.IO.FileInfo(sfile));
log.Info("Entering application.");
Bar bar = new Bar();
bar.DoIt();
log.Info("Exiting application.");
Console.ReadLine();
}
}
My log4net configuration looks as follows:
<!-- A1 is set to be a ConsoleAppender -->
<appender name="A1" type="log4net.Appender.ConsoleAppender">
<!-- A1 uses PatternLayout -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" />
</layout>
</appender>
<!-- Set root logger level to DEBUG and its only appender to A1 -->
<root>
<level value="DEBUG" />
<appender-ref ref="A1" />
</root>
<!-- Print only messages of level WARN or above in the package Com.Foo -->
<logger name="Com.Foo">
<level value="WARN" />
</logger>
The output of my application still shows log from Com.Foo
67 [10] INFO ConsoleApplication1.Program (null) - Entering application.
100 [10] INFO ConsoleApplication1.Com.Foo.Bar (null) - Did it again!
100 [10] INFO ConsoleApplication1.Program (null) - Exiting application.
How do I configure such that Com.Foo.Bar stops from showing up for WARN level?
What am I missing?
Thanks
Configuration, which you provided should work.
When you create logger Com.Foo.Bar it inherits settings from Com.Foo logger in hierarchy. Com.Foo logger inherits his appenders from root logger, but it has own level, which is set to WARN. So, when you trying to write logging event via Com.Foo.Bar logger, effective level will be retrieved from hierarchy - it's a level of nearest logger up in the hierarchy tree (root logger always has level). In your case it is WARN, so logging event will not be passed to appenders.
I think your configuration differs from what you provided. Maybe you are reading wrong configuration file. Try this code (app configuration file will be used):
XmlConfigurator.Configure();
Or (even better) use configuration via attribute:
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
UPDATE
If changing logger retrieving from typeof(Bar) to "Com.Foo" worked, then you provided us wrong namespace of Bar class. Because log4net behind the scene takes full name of type as name of logger. Thus with namespace Com.Foo all should work.
I just figured it out.. I was not setting the logger properly in Foo.Bar class.
Update the following line
private static readonly ILog log = LogManager.GetLogger(typeof(Bar));
to the following..
private static readonly ILog log = LogManager.GetLogger("Com.Foo");
and it worked.
Try
<levelToMatch value="WARN" />
Related
I am working on an Integration Test for a REST Endpoint that connects to a vendors Rest Api on a hardware device. My software has to be tested on the physical device periodically. I created a test project (VSTest VS 2015) and I want to add logging to my test harness. I realize that there is a tremendous amount of documentation on log4net, but I still can't make it work. My goal is to log to the console and also to a file. The vendor wants a log file to validate that my tests completed.
First, I initialize log4net to read a standalone file.
using log4net.Config;
using log4net;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics;
namespace MyProgram
{
[TestClass]
public class AssemblyInitializer
{
private static ILog log = null;
[AssemblyInitialize]
public static void Configure(TestContext Context)
{
Debug.WriteLine("Starting log4net setup and configuration");
XmlConfigurator.Configure(new FileInfo("log4net.properties"));
log = LogManager.GetLogger(typeof(AssemblyInitializer));
log.Debug("log4net initialized for Integration Test");
Debug.WriteLine("Completed log4net setup and configuration");
}
}
}
My log4net.properties file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionpattern value="%date [%thread] %-5level %logger{1} - %message%newline"/>
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="IntegrationTests.log" />
<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="ConsoleAppender"/>
<appender-ref ref="FileAppender"/>
</level>
</root>
</log4net>
</configuration>
I don't think the Test Explorer reads the Assembly.Info file, but I included a reference just in case.
[assembly: log4net.Config.XmlConfigurator(Watch = false)]
I have tried just about everything I can think of. I am out of ideas. Any help would be appreciated.
The code below works. It is not the same implementation, but I am getting both loggers to work. See my above comments. I believe that the log file was either in an unknown location, or I should have accessed a repository along the way. The following code works great and initializes before my tests are run, and logs my test results as needed.
using log4net;
using log4net.Config;
using log4net.Repository.Hierarchy;
using log4net.Core;
using log4net.Appender;
using log4net.Layout;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MyProgram
{
[TestClass]
public class AssemblyInitializer
{
private static ILog log = null;
[AssemblyInitialize]
public static void Configure(TestContext Context)
{
Debug.WriteLine("Starting log4net setup and configuration");
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository();
hierarchy.Root.RemoveAllAppenders();
PatternLayout patternLayout = new PatternLayout();
patternLayout.ConversionPattern = "%date [%thread] %-5level %logger - %message%newline";
patternLayout.ActivateOptions();
FileAppender fileAppender = new FileAppender();
fileAppender.Name = "Integration Test FileAppender";
fileAppender.File = #"Logs\IntegrationTest.log";
fileAppender.AppendToFile = false;
fileAppender.Layout = patternLayout;
fileAppender.ActivateOptions();
hierarchy.Root.AddAppender(fileAppender);
ConsoleAppender consoleAppender = new ConsoleAppender();
consoleAppender.Name = "Integration Test ConsoleAppender";
consoleAppender.Target = Console.Out.ToString();
consoleAppender.ActivateOptions();
consoleAppender.Layout = patternLayout;
hierarchy.Root.AddAppender(consoleAppender);
hierarchy.Root.Level = Level.Debug;
hierarchy.Configured = true;
log = LogManager.GetLogger(typeof(AssemblyInitializer));
log.Debug("log4net initialized for Integration Test");
Debug.WriteLine("Completed log4net setup and configuration");
}
}
}
I'm going to expand on my comment. Because Log4Net drove me insane too.
This is all that's in my App.config in my Test project for NLog.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<appSettings>
</appSettings>
<nlog autoReload="true"
throwExceptions="true"
internalLogLevel="Debug" internalLogFile="c:\temp\nlog-test.log" >
<targets>
<target type="Console" name="console" error="true"/>
</targets>
<rules>
<logger name="*" writeTo="console" />
</rules>
</nlog>
</configuration>
You define a target which is a destination for logging and then specify which loggers write to that target.
They want you to use the LoggingManger to create a logger (a source) for every class you want to log from. But I just wrapped a single logger in a static class and created some pass-thru methods. You lose some details that the logger could automatically capture for you (e.g. the exact site of the logging call), but I usually have sufficent detail in the message I'm writing to log.
~
Nlog is on Github https://github.com/NLog/NLog. Log4Net is still svn. That tells me something.
There also some nice Windows forms targets for Nlog available on NuGet.
I am creating logs in C# by using object of ILog in log4net. I am passing two parameters 1) repository where it will create log file 2)name of log file but it is showing exception that directory is not defined and if I do it by just passing name of log file ,program runs successfully but I am unable to find the log file.
Here is my code :-
private void createLogger(string Logdirectory)
{
if (Directory.Exists(Logdirectory))
{
Log = LogManager.GetLogger( Logdirectory , LogFilename);
}
else
{
Log = LogManager.GetLogger(LogFilename);
}
}
Here is console output :-
Help me find suitable way of getting logger by Ilog or by any other method except filestream
Read the documentation, log4net is very configurable and well documented.
Documentation: https://logging.apache.org/log4net/release/manual/configuration.html
using Com.Foo; // Import log4net classes.
using log4net;
using log4net.Config;
public class MyApp
{ // Define a static logger variable so that it references the // Logger instance named "MyApp".
private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));
static void Main(string[] args)
{ // Set up a simple configuration that logs on the console.
BasicConfigurator.Configure();
log.Info("Entering application.");
Bar bar = new Bar();
bar.DoIt();
log.Info("Exiting application.");
}
}
Take note the difference in the method for getting to log instance.
You're asking for an ILog for the current Type not an explicitly a filename
You're telling log4net to read configuration settings from the app.config/web.config
Depending on your config you may need to use the XmlConfigurator
An example of the .config file is:
<log4net> <!-- A1 is set to be a ConsoleAppender -->
<appender name="A1" type="log4net.Appender.ConsoleAppender"> <!-- A1 uses PatternLayout -->
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" />
</layout>
</appender>
<!-- Set root logger level to DEBUG and its only appender to A1 -->
<root>
<level value="DEBUG" />
<appender-ref ref="A1" />
</root>
</log4net>
There are lots of Appenders, above is a ConsoleAppender, but a DatabaseAppender exists and other types that might fit with you're need.
I have an issue to diagnose, and to get an understanding of it, I wrote two unit tests - one that gets a Logger that exists in my config, and another that gets logger that doesn't exist.
The first surprise was that even if the logger name doesn't exist, I'm still getting back something (instead of NULL, as I was expecting). And it even has a ConsoleAppender attached to it.... okay.... but where does that come from?
Log4net config:
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\tmp\log" />
... (some other settings) ....
</appender>
<root>
<level value="FATAL"/>
<appender-ref ref="RollingFileAppender" />
</root>
<logger name="DefinedLogger" additivity="false">
<level value="DEBUG" />
<appender-ref ref="MyCustomAppender" />
</logger>
<appender name="MyCustomAppender" type="MyAssembly.CustomAppender, MyAssembly">
.....
</appender>
</log4net>
Next, I was trying to understand how I can check what appenders are configured in each logger. My first attempt using the .Repository kept giving back all three appenders that are configured in my config file - OK, makes sense, since it's all the appenders that are in the repository.... but how can I check for an individual entry what appenders are attached?
[Test]
public void TestGetLoggerWithValidNameGetsLogger() {
// Arrange
string loggerName = "DefinedLogger";
// Act
ILog myCustomLogger = LogManager.GetLogger(loggerName);
// this returns *ALL* appenders in the config - not those attached to this logger....
var appenders = myLogger.Logger.Repository.GetAppenders();
// Assert
Assert.IsNotNull(myCustomLogger, "MyCustomLogger is NULL");
}
Any ideas? How can I check to make sure the proper appender(s) have been attached to my logger here?
I would like to log in the Windows Event Viewer using log4net.
I created a Console Application (.NET Framework 4), I added the reference log4net.dll, I put the following code in my App.config:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="EventLogAppender"/>
</root>
</log4net>
<startup><supportedRuntime version="v2.0.50727"/></startup>
</configuration>
And I put the following code :
class Program
{
static void Main(string[] args)
{
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error("test error", new Exception("error's exception", new Exception("error's innerexception")));
Console.Read();
}
}
It doesn't log, nothing happens, why?
Thanks
You need to call configure.
Change:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "App.config", Watch = true)]
To
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
When you specify ConfigFile = "App.config" its going to look for App.config but your filename would be [FileName].Config.
You need to call XmlConfigurator.Configure from the log4net library to initialize it. (see below)
class Program
{
static void Main(string[] args)
{
// you need this
XmlConfigurator.Configure();
log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
log.Error("test error", new Exception("error's exception", new Exception("error's innerexception")));
Console.Read();
}
}
Call XmlConfigurator.Configure() at the begining of your App.
You also need to grant the user running the application rights to put data in the eventlog.
A good way to do this is with powershell, admin mode
New-EventLog EventLogName -source ApplicationName
Also, add this two parameters into the appender
<param name="LogName" value="EventLogName " />
<param name="ApplicationName" value="ApplicationName" />
Regards,
I am using log4net to perform logging in my application. I have bound my project to TFS. I have created a wrapper around log4net as below:
public static class TestLogger
{
private static readonly ILog log = LogManager.GetLogger("TestLogger");
static TestLogger()
{
log4net.Config.XmlConfigurator.Configure();
}
public static void LogInfo(string information)
{
log.Info(information);
}
public static void LogError(string erroMessage, Exception ex)
{
log.Error(erroMessage, ex);
}
public static void LogWarnings(string warningText)
{
log.Warn(warningText);
}
}
When I tried to execute the program from VS2010 I found that log file is not being created. I create another project (not bound to TFS) and perform some logging, it succeeded and created the file in bin/debug of application.
Below is my log4net configuration file.
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender, log4net">
<file value="Log.txt" />
<appendToFile value="false" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="3" />
<maximumFileSize value="1GB" />
<layout type="log4net.Layout.PatternLayout, log4net">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<logger name="TestLogger">
<level value="ALL" />
<appender-ref ref="RollingFileAppender" />
</logger>
</log4net>
Can anybody help in this issue?
Some troubleshooting tips:
define an absolute path to the Log file in your config file.
check the current working directory in your code (Environment.CurrentDirectory). If you're running under the VS debugger, and you haven't specified a working directory in the Debug tab of your project properties, it may well default to the current Visual Studio working directory.
I don't think being bound to TFS is relevant.
Just change this part
<appendToFile value="true" />
Maybe your application already uses some declarative configuration, which is somewhere burried in the code. Search for something like this:
[assembly: log4net.Config.XmlConfigurator(Watch=true)]
Otherwise try to get hold of the log4net repository with
log4net.LogManager.GetRepository(). It returns an object of the type ILoggerRepository. You can try to use this object to write some information about the current log4net configuration into the Console or somewhere else.
Try to turn on internal debugging as explained here. This should tell you what the problem is. If there is no output from internal debugging then you probably did not configure log4net.