log4net

hamid441
hamid441 used Ask the Experts™
on
Hi all,
anyone familiar with log4net can tell me how can I configure my Appender to meet the below requirements
1. create a new log file everyday
2. the date be part of  the file name (i.e. 20120319-Back.log, 20120318-Back.log etc)
3. write a trademark message at the beginning of every log file
4. keep the logs for 30 days logs.

Also, can multiple projects inside a solution use the same appender? Or each project needs its own log4net configuration?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
afaik, you have at least RollingFileAppender (see example configs here: http://logging.apache.org/log4net/release/config-examples.html)

also, you can easily extend it just inheriting desired appender class and adding missing features, eg

    public class ZipLogFileAppender : RollingFileAppender
    {
        int lastZipIdx = 0;
        public ZipLogFileAppender()
        {
            Debug.WriteLine("ZipLogFileAppender(): Created");
            LiveAdClientSettings clientSettings = MyOwnSettingsClass.GetClientSettings();
            string logFolder = MyOwnSettingsClass.APP_DATA_FOLDER + "\\" + clientSettings.LogFolder;
            string[] zipFiles = Directory.GetFiles(logFolder, "*.zip");
            int idx = -1, value = 1;
            string parse = "";
            foreach (string zipFile in zipFiles)
            {
                idx = zipFile.LastIndexOf(".");
                if (idx < 0)
                    continue;
                parse = zipFile.Substring(0, idx);
                idx = parse.LastIndexOf(".");
                if (idx < 0)
                    continue;
                if (!SystemInfo.TryParse(parse.Substring(idx + 1), out value))
                    continue;
                if (value > lastZipIdx)
                    lastZipIdx = value;
            }
            lastZipIdx++;
        }
        protected override void RollFile(string fromFile, string toFile)
        {
            try
            {
                //base.RollFile(fromFile, toFile);
                // Zip old log
                string nextZipFileName = fromFile + "." + lastZipIdx.ToString() + ".zip";
                DeleteFile(nextZipFileName);
                ZipFile zipFile = ZipFile.Create(nextZipFileName);
                zipFile.NameTransform = new ZipNameTransform(Path.GetDirectoryName(fromFile));
                zipFile.BeginUpdate();
                zipFile.Add(fromFile);
                zipFile.CommitUpdate();
                zipFile.Close();
                // Now let it rock'n'roll...
                base.RollFile(fromFile, toFile);
                //...and finally delete the old log
                DeleteFile(toFile);
                lastZipIdx++;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ZipRollFile(): " + ex.Message);
                ErrorHandler.Error("An error occurred while connecting to the logging service.", ex);
            }
        }
    }

Open in new window


Above class doesn't do what you want, I put it here just to illustrate that you have full control over the logging
Top Expert 2010

Commented:

Author

Commented:
Hey alexey_gusev,

How were you able to override RollFile(string fromFile, string toFile) as it is not a  virtual function? when I tried to do this, I got  the below error:
'log4netExample.DailyRollingFileAppender.RollFile(string, string)': cannot override inherited member 'log4net.Appender.RollingFileAppender.RollFile(string, string)' because it is not marked virtual, abstract, or override

  public  class DailyRollingFileAppender : RollingFileAppender
    {


      protected override void RollFile(string fromFile, string toFile)
      {

          base.RollFile(fromFile, toFile);
      }
    }

Open in new window

Hi,

I'm using both log4Net and NLog. NLog seem more flexible than log4Net

Generate dynamic logfile names is easy in NLog.
Please note that currently Nlog writes the header every time the application is started.

NLog.config
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 
  <targets>
    <target name="file" xsi:type="File" fileName="${basedir}/logs/defaultName.log"  />
  </targets>
   
  <rules>
    <logger name="*" minlevel="Debug" writeTo="file" />
  </rules>
 
</nlog>


    class Logger
    {
        private static NLog.Logger nlog = NLog.LogManager.GetCurrentClassLogger();
 
        public static NLog.Logger log()
        {          
            
            NLog.Config.LoggingConfiguration config = nlog.Factory.Configuration;
 
            NLog.Targets.FileTarget fileTarget = (NLog.Targets.FileTarget)(config.FindTargetByName("file"));
            fileTarget.Layout = "${longdate} |${level} |${callsite} |${message}";
            fileTarget.FileName = "${basedir}/logs/" + DateTime.Now.ToString("yyyyMMdd") + "-Back.log";
            fileTarget.ArchiveEvery = NLog.Targets.FileArchivePeriod.Day; /*Time-based file archival*/
            fileTarget.MaxArchiveFiles = 30; /*keep the logs for 30 days logs*/
            fileTarget.ConcurrentWrites=true; 
            fileTarget.KeepFileOpen=false;
            fileTarget.Header = "My trademark message"; /*write at the beginning of every log file*/
            return nlog;
        }
 
    }

    class Program
    {
        static void Main(string[] args)
        {
            Logger.log().Info("Hello World #1");
            Logger.log().Info("Hello World #2");
            Logger.log().Info("Hello World #3");
            Console.ReadKey();
 
        }
 
     }


Output
My trademark message
2012-04-20 10:50:58.3513 |Info | |Hello World #1
2012-04-20 10:50:58.4573 |Info | |Hello World #2
2012-04-20 10:50:58.4633 |Info | |Hello World #3

Open in new window

ah, I definitely updated log4net sources then :) - sorry, it was so long ago that I simply forgot
        virtual protected void RollFile(string fromFile, string toFile) 
		{
			if (FileExists(fromFile))
			{
				// Delete the toFile if it exists
				DeleteFile(toFile);

				// We may not have permission to move the file, or the file may be locked
				try
				{
					LogLog.Debug("RollingFileAppender: Moving [" + fromFile + "] -> [" + toFile + "]");
					using(SecurityContext.Impersonate(this))
					{
						System.IO.File.Move(fromFile, toFile);
					}
				}
				catch(Exception moveEx)
				{
					ErrorHandler.Error("Exception while rolling file [" + fromFile + "] -> [" + toFile + "]", moveEx, ErrorCode.GenericFailure);
				}
			}
			else
			{
				LogLog.Warn("RollingFileAppender: Cannot RollFile [" + fromFile + "] -> [" + toFile + "]. Source does not exist");
			}
		}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial