Turn off Debug Logging during Release in Log4net - log4net

When I compiled my application in release mode, I found that the Log4Net still logs debug information; any idea how to fix this?
This is my App.Config file:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="C:\Documents and Settings\test\Application Data\Log.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} - %m%n" />
</layout>
</appender>
</log4net>
Did I miss anything?

There's nothing in your App.Config file to tell log4net to do things differently in release or debug mode. If you want logging to be different between the two builds, you have to change your configuration file between the two builds.
Your best bet is probably to create one App.Config for Release, one for Debug, and then follow the advice in the StackOverflow question:
Deploy an app.config based on build configuration
NOTE: The difference between your release and debug App.Config will be the following line in the debug version
<level value="DEBUG" />
versus the following line in the release version (or of course you could choose ERROR or FATAL if you want):
<level value="INFO" />

Maybe try something like this instead? Set to whatever minimum level you want to receive.
<level value="WARN" />

If your App.Config looks like this:
<root>
<level value="Info" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingFileAppender" />
</root>
You can modify the log level by code (put the code in Program.cs):
#if DEBUG
log4net.Repository.ILoggerRepository RootRep;
RootRep = LogManager.GetRepository(Assembly.GetCallingAssembly());
XmlElement section = ConfigurationManager.GetSection("log4net") as XmlElement;
XPathNavigator navigator = section.CreateNavigator();
XPathNodeIterator nodes = navigator.Select("root/level");
foreach (XPathNavigator appender in nodes)
{
appender.MoveToAttribute("value", string.Empty);
appender.SetValue("Debug");
}
IXmlRepositoryConfigurator xmlCon = RootRep as IXmlRepositoryConfigurator;
xmlCon.Configure(section);
#endif

Related

What's wrong with my log4net config file

I have a config file with two appenders, one file appender and one database appender. I want to log everything to the file appender, and only log exceptions to the database appender. When setting up both appenders in the section it logs fine but all log events are sent to both appenders, which is not what i want.
I changed the configuration but with this current configuration, exceptions get logged to the database, and nothing is getting written to the file appender. Can anyone tell me why I am not getting anything written to the file appender?
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\Log4net\Workflow\TestLog.txt" />
<threshold value="All" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p {%logger} %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<!-- Removed to keep this snippet simple-->
</appender>
<root>
<level value="Error" />
<appender-ref ref="AdoNetAppender" />
</root>
<logger name="AllLogs">
<level value="ALL" />
<appender-ref ref="RollingLogFileAppender" />
</logger>
</log4net>
What you have here is the following:
all logs events with the level Error or more will go to the AdoNetAppender
all logs events originating from a logger whose name is based on AllLogs will go to the RollingLogFileAppender
From what I understand you want all logs to default to the file, and only error ones to go also to the database. Then simply add both appenders to your root logger so that both get all events, and add filters to only let filters you're interested in pass through: a level range filter on your database appender would work
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!-- rest of config snipped to save space -->
</appender>
<appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="ERROR" />
<levelMax value="FATAL" />
</filter>
<!-- rest of config snipped to save space -->
</appender>
<root>
<appender-ref ref="AdoNetAppender" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
Of course if you don't want any duplicate just filter errors and above in the rolling file appender

Log4Net - Output not showing up at file

I have an Log4Net configuration that produces output as expected in a console application.
I have the exact same config, and invokation code (all done at the earliest point possible in the execution flow), but in the context of NUnit tests.
I know the configuration is loaded correctly. Additionally, I have turned the system diagnostics for Log4Net, and the debug prints are the exact same in both cases.
In the console application the text gets written. Otherwise, the file is empty.
The configuration code:
<log4net>
<!--APPENDERS-->
<!--Endpoint File Appender-->
<appender name="EndpointFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\Temp\Endpoint.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="10" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%message" />
</layout>
</appender>
<!--LOGGERS-->
<logger name="EndpointLog">
<level value="ALL" />
<appender-ref ref="EndpointFileAppender" />
</logger>
The Invocation code (first thing at application boot):
log4net.Config.XmlConfigurator.Configure();
ILog log = LogManager.GetLogger("EndpointLog");
log.Info("Hello World.");
Any ideas? Thanks
Is it that you need a root section? Try adding this:
<root>
<level value="All" />
<appender-ref ref="EndpointFileAppender" />
</root>
When you are running in an unittest context, you need to copy the log4net config into the bin folder with your unittest dlls. You can do this by setting copy tot output folder on the log4net config.

Log4net C#4.0 [(null)] in output

When I use log4net for logging in .NET4.0 I use the following code
LogManager declaration:
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
And when used in code:
log.Info("My info text");
This outputs the following to the log-file:
2013-10-01 14:41:11,010 [3] INFO MyNamespace.MyClass [(null)] - My info text
I am wondering what the [(null)] means and how I can remove/change it?
This is my config-file:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<param name="File" value="log-file.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
Fix
To stop it appearing in the log remove [%property{NDC}] from the config file.
This happens because log4net automatically populates a context of information that might be useful for logging - in some cases this might result in a null value.
log4net NDC
This post explains how to use NDC: When to use 'nested diagnostic context' (NDC)?
In short log4net calls the static method log4net.NDC.Push to set the context of the the code.
You could for example set the NDC manually by running the following:
log4net.NDC.Push("context")
From that point forward outputting a log message will supply %property{NDC} as the string context.
UPDATE:
NDC.Push has been deprecated. Alternatively, you can use ThreadContext.Stacks["NDC"].Push("context")
if you just want the (null) to disappear you can also set log4net.Util.SystemInfo.NullText to some other value like "" or string.Empty, it will use that instead.

Log4Net section in Web.Config generates Error

So I am trying to set up Log4Net in my Web .NET 4.0 application. I have added the correct .dll to my project and have appended the following to my Web.Config file as starters:
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</configSections>
<log4net debug="true">
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\\TestProj\\TestLog.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
</layout>
</appender>
However, if I append the "log4net" section to Web.Config, I will receive the error message
Unable to start debugging on the web server. See help for common
configuration problems.....
Make sure the server is running correctly. Verify there are no syntax
errors in the web.config........
NOTE
I can remove all the internals of this section and leave only the declaration:
<log4net></log4net>
and I will still get the same error.
Can someone give me some pointers on how to track down this error?
For developers who are not sure exactly how to get started following might be a help
ConfigSections in app.config
Remember to tell your application that a library is introducing a custom configuration section are you are intended to utilize, I am not perfectly sure if it is mandatory or not but I always use it as first section within root <configuration> tag.
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
log4net config in app.config
There are quite a variety of different appenders available in log4net but I usually use RollingFileAppender so I am using the same one in this sample, you can find rest of those here.
<log4net>
<!-- file appender -->
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:/logs/my_log_file.log"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<maxSizeRollBackups value="30"/>
<datePattern value=".yyyy-MM-dd"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingFileAppender"/>
</root>
</log4net>
Update AssemblyInfo.cs file
I always miss this step whenever I have to create a new project. So remember you have to tell your application to watch for XMLConfigurator to perform configuration of log4net, so following line goes at the end of AssemblyInfo.cs file:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Get Started
Remember to include the reference of log4net.dll then use following line of code to initialize logger within a class
private static ILog log = LogManager.GetLogger(typeof(MyClass));
And at the end lets use it like following
log.Info("Hello log4net");
Happy Logging :)
Take a look at a sample configurations at log4net documentation homepage.
Chances are you've misplaced required tags.

log4net 1.2 RollingFileAppender not working

I'm using log4net v1.2 with a Windows Service App. My RollingFileAppender seems not to work. I'm pasting the logging sections of my service.exe.config below. Can anyone advise where I'm going wrong?
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
.....(lots of other config stuff)
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender,log4net" >
<param name="File" value="D:\\Trinity\\Booking\\OneDay_PostTrade\\logs\\Trinity.log" />
<param name="MaximumFileSize" value="20MB" />
<param name="MaxSizeRollBackups" value="10" />
<param name="StaticLogFileName" value="true" />
<param name="Threshold" value="ALL" />
<param name="RollingStyle" value="Composite" />
<param name="appendToFile" value="true" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
</layout>
</appender>
...(stuff in between)
<root>
<level value="ALL" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingFileAppender" />
</root>
.....(stuff in between)
<logger name="CSFB.PostTradeRulesEngine">
<level value="ALL"/>
</logger>
The user your windows service is running as might not have write permission for the log file.
Another possibility is that you forgot to execute XmlConfigurator.Configure();
try writing:
<log4net debug="true">
it will post all errors to console.
thanks to everyone who responded. I dont know what i changed but my logging has started working fine.
Posting my logging sections. I didnt change anything in the code, except a line in the AssemblyInfo.cs:
[assembly: log4net.Config.Domain(UseDefaultDomain=true)]
Thanks again.:)

Resources