Question

I have a program which uses SLF for logging. This program runs 24/7 and I would like to upload the log files to a remote server every night for later review.

My question is, how do I release the file lock for the log without closing the program?

I was hoping to suspend logging, upload the logs, either delete the log file or erase the contents, and then resume logging.

ILogger logger = LoggerService.GetLogger(typeof(TaskScheduler).FullName);

// Other initialization here

foreach (var task in managedTasks.OrderBy(t => t.Priority))
{
    if (task.NextRunTime <= DateTime.Now)
    {
        dataManager.CurrentStatus = AppStatus.Running;
        if (task.Name == "Log Sender")
        {
             logger = null;
        }

        // Run the task

        if (task.Name == "Log Sender")
        {
            logger = LoggerService.GetLogger(typeof(TaskScheduler).FullName);
        }

        dataManager.CurrentStatus = AppStatus.Idle;
    }
}

Currently, when I do this, I'm still getting an IOException because the file is still locked by the Task Scheduler.

EDIT: I'm using SLF over log4net if that helps.

Was it helpful?

Solution

I would consider this as a design issue rather than technical. Log events for each day in an individual file and upon next day you can do anything you want with yesterday's log file. You can narrow log period according to your need (i.g. every 12 hours).

OTHER TIPS

After posting this question and getting the recommendations to reconsider my design. I started to look into creating a rolling log file for each date. I happened across this, which solved my problem completely:

<appender name="InfoRollingLogFileAppender" type="log4net.Appender.RollingFileAppender,log4net">
  <param name="File" value="log.txt" />
  <param name="StaticLogFileName" value="true"/>
  <maximumFileSize value="1024KB" />
  <appendToFile value="true" />
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%logger: %date{dd MMM yyyy HH:mm:ss} [%thread] %-5level - %message %newline" />
  </layout>
</appender>

I configured the log4net appender in my app.config to follow the lockingModel to include a "MinimalLock" this enabled me to pull the contents of the logs, upload them to the server and then erase the local logs without having to create separate log files for a specified time/date span.

Again, thanks to everyone for your help, I wouldn't have stumbled across this handy change without your suggestions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top