Files
ssh.net/docfx/logging.md
T
Bart Vries d40bc43ac1 Refactor logging to allow a loggerfactory per session (#1673)
* Refactor logging to allow a loggerfactory per session specified in the ConnectionInfo.

This commit introduces an `ILoggerFactory` to various classes, replacing the static logger factory with an instance-based approach for more flexible and session-specific logging. These changes improve the logging framework's flexibility and maintainability and allow unit testing of logging.

* Improvements bases on feedback. Fixed tests. Added documentation.

* Update src/Renci.SshNet/ConnectionInfo.cs

---------

Co-authored-by: Rob Hague <rob.hague00@gmail.com>
2025-07-26 21:24:48 +02:00

1.2 KiB

Logging

SSH.NET uses the Microsoft.Extensions.Logging API to log diagnostic messages.

It is possible to specify a logger in the ConnectionInfo, for example:

using Microsoft.Extensions.Logging;

ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
    builder.SetMinimumLevel(LogLevel.Debug);
    builder.AddConsole();
});

var connectionInfo = new ConnectionInfo("sftp.foo.com",
                                        "guest",
                                        new PasswordAuthenticationMethod("guest", "pwd"));
										
connectionInfo.LoggerFactory = loggerFactory;
using (var client = new SftpClient(connectionInfo))
{
    client.Connect();
}

You can also register an application-wide ILoggerFactory before using the SSH.NET APIs, this will be used as a fallback if the ConnectionInfo is not set, for example:

using Microsoft.Extensions.Logging;

ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
    builder.SetMinimumLevel(LogLevel.Debug);
    builder.AddConsole();
});

Renci.SshNet.SshNetLoggingConfiguration.InitializeLogging(loggerFactory);

All messages by SSH.NET are logged under the Renci.SshNet category.