How to write text into log4net file - c#

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)]

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>

Write a Server.MapPath in the web.config file?

Hi there i'm trying to write log for my live website and am having problems with my paths, I need to use the method Server.MapPath but i need it done in my web.config.
How would i go about this?
The file value holds the path, but i need to set a Server.MapPath on it.
<log4net>
<add key="LogFilePath1" value="../Logs/CurrentLog" id="FP1"/>
<add key="LogFilePath2" value="../Logs/CurrentLog.txt" id="FP2" />
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="../Logs/CurrentLog"/>
<appendToFile value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="10000"/>
<staticLogFileName value="true"/>
<filter type="log4net.Filter.LevelRangeFilter">
<acceptOnMatch value="true"/>
<levelMin value="INFO"/>
<levelMax value="FATAL"/>
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level %date [%thread] %-22.22c{1} - %m%n"/>
</layout>
</appender>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="../Logs/Log.txt"/>
<appendToFile value="true"/>
<layout type="log4net.Layout.PatternLayout">
<header value="**"/>
<footer value="**"/>
<conversionPattern value="%newline%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender"/>
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="RollingFileAppender"/>
</root>
<logger name="ConsoleApp.LoggingExample">
<level value="ERROR"/>
<appender-ref ref="EventLogAppender"/>
</logger>
Logger code C#:
public class Logger
{
protected static readonly ILog logger = LogManager.GetLogger(typeof(Logger));
public void logError(string message, Exception ex)
{
HttpContext.Current.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["LogFilePath1"]));
HttpContext.Current.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["LogFilePath2"]));
log4net.Config.XmlConfigurator.Configure();
logger.Error(message + ex);
}
public void logInfo(string message)
{
HttpContext.Current.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["LogFilePath1"]));
HttpContext.Current.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["LogFilePath2"]));
log4net.Config.XmlConfigurator.Configure();
logger.Info(message);
}
}
I have added C# code to Server.MapPath the Keys, i'm just struggling calling the keys in thhe file value =
Store your path in the config as
<add key="LogFilePath1" value="~/Logs/CurrentLog" id="FP1"/>
From your code read the key
string path = GetPath("LogFilePath1");
string fullPath = System.Web.HttpContext.Server.MapPath(path);
Log4net does not use Server.Map path when reading the paths from your configuration files. It does not know it is running in a web context. I geuss you can implement your own version of the Rolling File Appender and override the function which gets the path from the config. However I would just use the full paths to the log locations. Normally you do want to log on an other disk your application is running to prevent running out of diskspace and killing your application.

log4net multiple appenders, writing to event viewer

I am using log4net for logging, I have two appenders one file and other eventlog appender. I have register application in registry editor, problem is now both logger are writing in event viewer. I need fileAppender to write in file and eventLogAppender to be shown in event viewer.
<log4net>
<appender name="LogFileAppender" type="log4net.Appender.FileAppender">
<file value="file.log"/>
<appendToFile value="false"/>
<layout type="log4net.Layout.PatternLayout">
<header value="Logging Start
"/>
<footer value="Logging End
"/>
<conversionPattern value="%date [%thread] %-5level %logger: %message%newline"/>
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender">
<param name="ApplicationName" value="eventlog" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender"/>
<appender-ref ref="EventLogAppender" />
</root>
</log4net>
and then in code
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// private static readonly ILog log = LogManager.GetLogger("LogFileAppender");
private static readonly ILog logEvents = LogManager.GetLogger("EventLogAppender");
I have tried different things but no one is working, any solution?
Thanks!
In order to use multiple ILog instances with log4net and to log different information to each, you must configure at least two Logger elements in the log4net section of your config file.
In your case, you have two targets that you want - file and event log. I'll call them FileLogger and EventLogger.
Here is an example of the additional configuration you need in the log4net section:
<logger name="FileLogger">
<level value="ALL" />
<appender-ref ref="LogFileAppender" />
</logger>
<logger name="EventLogger">
<level value="ALL" />
<appender-ref ref="EventLogAppender" />
</logger>
Then, to use each one in code, instantiate them like so:
private static readonly ILog fileLogger = LogManager.GetLogger("FileLogger");
private static readonly ILog eventLogger = LogManager.GetLogger("EventLogger");
Note that the ref attribute of the appender elements matches the name attribute of the appenders you have already configured and that the name passed to GetLogger matches the name attribute of the logger elements.

log4net log being created but remaining empty

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.

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