Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make FluentFTP to log to log4net log?

I couldn't find any information on how to do it. Basically FluentFTP is using System.Diagnostics to log their messages. FluentFtp expose the following static method:

FtpTrace.AddListener(TraceListener listener);

However I don't know if there is any way to implement (or use existing implementation, which?) TraceListener in the way it relays everything to log4net engine.

Any hints or ideas?

Thanks, Radek

like image 592
Radek Strugalski Avatar asked Mar 06 '23 10:03

Radek Strugalski


1 Answers

You can attach a listener to the OnLogEvent method that FluentFTP exposes.

private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

public static void UploadFTP(FileInfo localFile, string remoteFileLocation, string remoteServer, NetworkCredential credentials)
{
    FtpClient client = new FtpClient(remoteServer, credentials);
    client.RetryAttempts = 3;
    client.OnLogEvent = OnFTPLogEvent;

    client.Connect();

    if (!client.UploadFile(localFile.FullName, remoteFileLocation, FtpExists.Overwrite, false, FtpVerify.Retry | FtpVerify.Throw))
    {
        throw new Exception($"Could not Upload File {localFile.Name}. See Logs for more information");
    }
}

private static void OnFTPLogEvent(FtpTraceLevel ftpTraceLevel, string logMessage)
{
    switch (ftpTraceLevel)
    {
        case FtpTraceLevel.Error:
            Log.Error(logMessage);
            break;
        case FtpTraceLevel.Verbose:
            Log.Debug(logMessage);
            break;
        case FtpTraceLevel.Warn:
            Log.Warn(logMessage);
            break;
        case FtpTraceLevel.Info:
        default:
            Log.Info(logMessage);
            break;
    }
}

The method OnFTPLogEvent will be called every-time the OnLogEvent action will be called allowing you to extend any logging you have already built into your application.

like image 135
Dean Meehan Avatar answered Mar 19 '23 05:03

Dean Meehan