8
votes

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.

3

3 Answers

6
votes

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;
2
votes

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.

0
votes

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