Reputation: 1300
I've wrote a wrapper class for using the loggers, and since I've never used log4net before (I use log4c++ at work, but it's already configured and I never needed to mess with it),
I don't know how to configure it properly and get it to work...
This is the current source code for the wrapping class:
using System.Text;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Layout;
namespace GotLoggingService
{
public sealed partial class LoggerManager
{
private ILog Logger { get; }
#region Info Methods
public void Info(string message)
{
Logger.Info(message);
}
public void InfoFormat(string format, params object[] args)
{
Logger.InfoFormat(format, args);
}
#endregion
#region Debug Methods
public void Debug(string message)
{
Logger.Debug(message);
}
public void DebugFormat(string format, params object[] args)
{
Logger.DebugFormat(format, args);
}
#endregion
#region Warn Methods
public void Warn(string message)
{
Logger.Warn(message);
}
public void WarnFormat(string format, params object[] args)
{
Logger.WarnFormat(format, args);
}
#endregion
#region Error Methods
public void Error(string message)
{
Logger.Error(message);
}
public void ErrorFormat(string format, params object[] args)
{
Logger.ErrorFormat(format, args);
}
#endregion
#region Fatal Methods
public void Fatal(string message)
{
Logger.Fatal(message);
}
public void FatalFormat(string format, params object[] args)
{
Logger.FatalFormat(format, args);
}
#endregion
#region Getters
public static LoggerManager GetLogger(string name)
{
return new LoggerManager(name);
}
public static LoggerManager GetLogger(string name, LoggerManager parent)
{
return new LoggerManager(name, parent);
}
public static LoggerManager GetRootLogger()
{
return RootLooger;
}
#endregion
}
// Manage stuff here
public sealed partial class LoggerManager
{
private const string FORMAT = "%timestamp %-5level %logger %ndc - %ndc %message%newline";
// Initializes root logger
private LoggerManager()
{
Logger = LogManager.GetLogger(ROOT_LOGGER_NAME);
BasicConfigurator.Configure(new FileAppender
{
AppendToFile = true,
Encoding = Encoding.UTF8,
File = "C:/log.txt",
ImmediateFlush = true,
Layout = new PatternLayout(FORMAT)
});
}
private LoggerManager(string name) : this(name, GetRootLogger())
{
}
private LoggerManager(string name, LoggerManager parent)
{
Logger = GetILog(name, parent);
}
private const string ROOT_LOGGER_NAME = "root";
private static readonly LoggerManager RootLooger = new LoggerManager();
private static ILog GetILog(string name, LoggerManager parent)
{
return LogManager.GetLogger(GetLoggerName(name, parent.Logger.Logger.Name));
}
private static string GetLoggerName(string name, string parent = ROOT_LOGGER_NAME)
{
StringBuilder nameBuilder = new StringBuilder();
nameBuilder.AppendFormat("{0}.{1}", LogManager.GetLogger(parent).Logger.Name, name);
return nameBuilder.ToString();
}
}
}
As you can see, I've tried configuring with BasicConfigurator, supplying it with a FileAppender. I've tried logging stuff and it doesn't add anything to the file... Here's a short example of how I use the logger wrapper:
using GotLoggingService;
namespace trythelog
{
class LoggerTry
{
private LoggerManager logger;
public static void Main(string[] args)
{
LoggerTry logger = new LoggerTry();
}
public LoggerTry()
{
logger = LoggerManager.GetLogger("some-logger");
logger.Info("this is a log message");
}
}
}
This is basically all I have to say... Thanks for reading and I would like it if you could point out stuff I messed up at.
I now use App.Config instead of BasicConfigurator
This is the app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG"/>
<appender-ref ref="RollingLogFileAppender"/>
<appender-ref ref="ConsoleAppender"/>
</root>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger %ndc - %ndc %message%newline" />
</layout>
</appender>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="logs/" />
<datePattern value="yyyyMMdd'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger %ndc - %ndc %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
I get this exception when I try to run : http://pastebin.com/qftQAHkn
ליו להיות הצאצא הראשון של אלמנט הבסיס <configuration>. (C:\GameOfThrowsUnityRepository\GameOfThrowsU
nity\GameOfThrowsServer\trythelog\bin\Debug\trythelog.exe.Config line 7)
ב- System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
ב- System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors sch
emaErrors)
ב- System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
ב- System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
--- סוף רכיב מעקב אחר מחסנית של מצב חריג פנימי ---
ב- System.Configuration.ConfigurationManager.PrepareConfigSystem()
ב- System.Configuration.ConfigurationManager.get_AppSettings()
ב- log4net.Util.SystemInfo.GetAppSetting(String key) ב- c:\log4net\tags\1.2.15RC1\src\Util\Syste
mInfo.cs:שורה 954
log4net:ERROR Failed to parse config file. Is the <configSections> specified as: <section name="log4
net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.15.0, Culture=neut
ral, PublicKeyToken=669e0ddf0bb1aa2a" />
System.Configuration.ConfigurationErrorsException: אתחול מערכת התצורה נכשל. ---> System.Configuratio
n.ConfigurationErrorsException: אלמנט <configSections> אחד בלבד מותר לכל קובץ config ואם הוא קיים, ע
ליו להיות הצאצא הראשון של אלמנט הבסיס <configuration>. (C:\GameOfThrowsUnityRepository\GameOfThrowsU
nity\GameOfThrowsServer\trythelog\bin\Debug\trythelog.exe.Config line 7)
ב- System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
ב- System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors sch
emaErrors)
ב- System.Configuration.BaseConfigurationRecord.ThrowIfInitErrors()
ב- System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
--- סוף רכיב מעקב אחר מחסנית של מצב חריג פנימי ---
ב- System.Configuration.ConfigurationManager.PrepareConfigSystem()
ב- System.Configuration.ConfigurationManager.GetSection(String sectionName)
ב- log4net.Config.XmlConfigurator.InternalConfigure(ILoggerRepository repository) ב- c:\log4net\
tags\1.2.15RC1\src\Config\XmlConfigurator.cs:שורה 173
Press any key to continue . . .
Sorry for the hebrew stuff :x
Upvotes: 2
Views: 3094
Reputation: 531
In my case, the issue was caused by file property Copy to Output Directory. It was set to Do Not Copy (and it works for Web App) however, for Console App it must be set to Copy always
(use F4 key in Visual Studio to show Properties window)
Upvotes: 0
Reputation: 5284
Try:
Code
using log4net;
...
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure(); // Missing!!?
ILog log = LogManager.GetLogger("MyLogger");
log.Info("message");
App.Config or Web.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections> <!-- must be the first child -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
...
<log4net>
<logger name="MyLogger">
<level value="INFO" />
<appender-ref ref="RollingLogFileAppender" />
</logger>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<file value="logs/" /> <!--YOUR PATH-->
<datePattern value="yyyyMMdd'.log'" />
<staticLogFileName value="false" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %level %logger - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
Upvotes: 1