Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programatically force a new log file with Log4Net

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.

like image 944
Vaccano Avatar asked Apr 30 '13 16:04

Vaccano


2 Answers

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;
like image 76
Vaccano Avatar answered Nov 14 '22 18:11

Vaccano


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.

like image 2
bastos.sergio Avatar answered Nov 14 '22 18:11

bastos.sergio