Show / Hide Table of Contents

    Introduction

    The FTP server utilizes Microsoft.Extensions.Logging which provides an interface to many logging frameworks (e.g. NLog).

    Example: Using SeriLog

    Adding SeriLog to the project

    Go to the quickstart project created during the Quickstart tutorial and add the following NuGet packages:

    # Serilog.Extensions.Logging
    dotnet add package Serilog.Extensions.Logging
    # Serilog.Sinks.Console
    dotnet add package Serilog.Sinks.Console
    

    Configure serilog in Program.cs

    Add the highlighted lines to your Program.cs:

    using System;
    using System.IO;
    
    using FubarDev.FtpServer;
    using FubarDev.FtpServer.FileSystem.DotNet;
    
    using Microsoft.Extensions.DependencyInjection;
    
    using Serilog;
    
    namespace QuickStart
    {
        class Program
        {
            static async Task Main(string[] args)
            {
                // Configure Serilog
                Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Verbose()
                    .Enrich.FromLogContext()
                    .WriteTo.Console()
                    .CreateLogger();
    
                // Setup dependency injection
                var services = new ServiceCollection();
    
                // Add Serilog as logger provider
                services.AddLogging(lb => lb.AddSerilog());
    
                // use %TEMP%/TestFtpServer as root folder
                services.Configure<DotNetFileSystemOptions>(opt => opt
                    .RootPath = Path.Combine(Path.GetTempPath(), "TestFtpServer"));
    
                // Add FTP server services
                // DotNetFileSystemProvider = Use the .NET file system functionality
                // AnonymousMembershipProvider = allow only anonymous logins
                services.AddFtpServer(builder => builder
                    .UseDotNetFileSystem() // Use the .NET file system functionality
                    .EnableAnonymousAuthentication()); // allow anonymous logins
    
                // Configure the FTP server
                services.Configure<FtpServerOptions>(opt => opt.ServerAddress = "127.0.0.1");
    
                // Build the service provider
                using (var serviceProvider = services.BuildServiceProvider())
                {
                    // Initialize the FTP server
                    var ftpServerHost = serviceProvider.GetRequiredService<IFtpServerHost>();
    
                    // Start the FTP server
                    await ftpServerHost.StartAsync();
    
                    Console.WriteLine("Press ENTER/RETURN to close the test application.");
                    Console.ReadLine();
    
                    // Stop the FTP server
                    await ftpServerHost.StopAsync();
                }
            }
        }
    }
    

    Now you can see all the log messages from the FTP server.

    Example: Using NLog

    Adding NLog to the project

    Go to the quickstart project created during the Quickstart tutorial and add the following NuGet package:

    # Add NLog
    dotnet add package NLog.Extensions.Logging
    

    Add the NLog configuration

    Now add a file called nlog.config with the following contents:

    <?xml version="1.0" encoding="utf-8" ?>
    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
          autoReload="true"
          throwExceptions="false">
    
      <targets>
        <target xsi:type="ColoredConsole" name="console" layout="${longdate} ${uppercase:${level}} ${mdlc:item=RemoteAddress} ${message} ${exception:format=tostring}"/>
      </targets>
    
      <rules>
        <logger name="*" minlevel="Trace" writeTo="console" />
      </rules>
    </nlog>
    

    Add the configuration to the project

    Change the csproj file by adding the following lines:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.2</TargetFramework>
        <RootNamespace>QuickStart</RootNamespace>
      </PropertyGroup>
    
      <ItemGroup>
        <ProjectReference Include="..\..\..\src\FubarDev.FtpServer\FubarDev.FtpServer.csproj" />
        <ProjectReference Include="..\..\..\src\FubarDev.FtpServer.FileSystem.DotNet\FubarDev.FtpServer.FileSystem.DotNet.csproj" />
      </ItemGroup>
    
      <ItemGroup>
        <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />
        <PackageReference Include="NLog.Extensions.Logging" Version="1.1.0" />
      </ItemGroup>
    
      <ItemGroup>
        <Content Include="nlog.config">
          <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
        </Content>
      </ItemGroup>
    
    </Project>
    

    This ensures that the nlog.config file gets copied into the build output folder and is available for the application.

    Registering NLog in Program.cs

    using System;
    using System.IO;
    
    using FubarDev.FtpServer;
    using FubarDev.FtpServer.FileSystem.DotNet;
    
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    
    using NLog.Extensions.Logging;
    
    namespace QuickStart
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Setup dependency injection
                var services = new ServiceCollection();
    
                // Add logging
                services.AddLogging(lb => lb.SetMinimumLevel(LogLevel.Trace));
    
                // use %TEMP%/TestFtpServer as root folder
                services.Configure<DotNetFileSystemOptions>(opt => opt
                    .RootPath = Path.Combine(Path.GetTempPath(), "TestFtpServer"));
    
                // Add FTP server services
                // DotNetFileSystemProvider = Use the .NET file system functionality
                // AnonymousMembershipProvider = allow only anonymous logins
                services.AddFtpServer(builder => builder
                    .UseDotNetFileSystem() // Use the .NET file system functionality
                    .EnableAnonymousAuthentication()); // allow anonymous logins
    
                // Configure the FTP server
                services.Configure<FtpServerOptions>(opt => opt.ServerAddress = "127.0.0.1");
    
                // Build the service provider
                using (var serviceProvider = services.BuildServiceProvider())
                {
                    var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
    
                    //configure NLog
                    loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
                    NLog.LogManager.LoadConfiguration("nlog.config");
    
                    // Initialize the FTP server
                    var ftpServerHost = serviceProvider.GetRequiredService<IFtpServerHost>();
    
                    // Start the FTP server
                    ftpServerHost.StartAsync().Wait();
    
                    Console.WriteLine("Press ENTER/RETURN to close the test application.");
                    Console.ReadLine();
    
                    // Stop the FTP server
                    ftpServerHost.StopAsync().Wait();
                }
            }
        }
    }
    

    Now you can see all the log messages from the FTP server.

    • Improve this Doc
    Back to top
    Copyright © 2018 Fubar Development Junker
    Generated by DocFX
    Creative Commons License
    FluentMigrator Documentation by FluentMigrator Project is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.