8

NOTE: I read this question and answer, and it does not work for what I want: Log4Net: Programmatically specify multiple loggers (with multiple file appenders)

I have a WCF service that is a "Question and Answer" style service. It gets inputs and sends outputs. It does not persist much at all.

I need to log each Question and Answer session in a separate file.

I have a single Appender (currently the RollingAppender).

Is there some way to start a new log file for each call to my WCF service?

NOTE: I am using an XML Layout, the idea is that the output of the log can be parsed and displayed graphically (a later feature). Kind of like a "Query Plan". This is another reason that I need them in a separate file.

NOTE: In case another reason is needed, the Log4Net XmlLayoutBase will not drop xml footers until the app closes. Which is not really a planned event for an WCF Service hosted in IIS.

Community
  • 1
  • 1
Vaccano
  • 78,325
  • 149
  • 468
  • 850

3 Answers3

6

This seems to work for me:

public static void StartNewFile(this ILog log, string newFileName)
{
    Logger logger = (Logger) log.Logger;

    while (logger != null)
    {
        foreach (IAppender appender in logger.Appenders)
        {
            FileAppender fileAppender = appender as FileAppender;
            if (fileAppender != null)
            {
                fileAppender.File = newFileName;
                fileAppender.ActivateOptions();
            }
        }
        logger = logger.Parent;
    }
}

It requires the following references:

using log4net;
using log4net.Appender;
using log4net.Repository.Hierarchy;
Vaccano
  • 78,325
  • 149
  • 468
  • 850
2

Instead of logging to a file, maybe you could try logging to a database table and log the session id with the logged data. This way you can do selects against the table based on the session id and see only their data.

bastos.sergio
  • 6,684
  • 4
  • 26
  • 36
  • Problem is I have a multiple node levels going in my xml logging system. It does not map well to a static database table. I "could" put the XML in a data table, but I usually try not to mix XML and SQL. I find that it makes for complex queries and hard to maintain clients. – Vaccano Apr 30 '13 at 16:49
  • While my code works, I am going to end up going to the database. So I am giving your question the "answer". – Vaccano May 01 '13 at 14:06
0

Perhaps not the exact solution you are looking for but you could create a different logger for each session by calling this at the start of each interface call:

ILog logger = LogManager.GetLogger(<SessionID>);

You will get all the entries in the same log file but it is then really easy to view each session separately with a viewer such as log4view.

Hope it helps

EZDsIt
  • 921
  • 1
  • 9
  • 14