AdsConsoleLogger Class

Logger class that implements Console ADS logging. Implements the ILogger

Inheritance Hierarchy

SystemObject
  TwinCAT.Ads.LoggingAdsConsoleLogger

Namespace: TwinCAT.Ads.Logging
Assembly: TwinCAT.Ads.ConfigurationProviders (in TwinCAT.Ads.ConfigurationProviders.dll) Version: 7.0.0+e56d35ccc4675faac24789a4aab60071fc61d470

Syntax

C#

public class AdsConsoleLogger : ILogger

The AdsConsoleLogger type exposes the following members.

Constructors

 

Name

Description

AdsConsoleLogger

Initializes a new instance of the AdsConsoleLogger class.

Methods

 

Name

Description

BeginScopeTState

Begins a logical operation scope.

Equals

Determines whether the specified object is equal to the current object.
(Inherited from Object)

Finalize

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object)

GetHashCode

Serves as the default hash function.
(Inherited from Object)

GetType

Gets the Type of the current instance.
(Inherited from Object)

IsEnabled

Checks if the given logLevel is enabled.

LogTState

Writes a log entry.

MemberwiseClone

Creates a shallow copy of the current Object.
(Inherited from Object)

ToString

Returns a string that represents the current object.
(Inherited from Object)

Remarks

The AdsConsoleLogger class extends the standard logging information with timestamp and ThreadId information to track ADS communication in the Console. Logging functionality is included in all ADS (.NET) components and the AdsConsoleLogger class can be activated at the application host:

Example

Simple Logging approach with the AdsLoggerProvider

static async void Main(string[] args)
{
    CancellationTokenSource cancelSource = new CancellationTokenSource();
    CancellationToken cancel = cancelSource.Token;

    var address = new AmsAddress(AmsNetId.Local, AmsPort.SystemService);
    var sessionSettings = SessionSettings.Default;

    //https://learn.microsoft.com/en-us/dotnet/core/extensions/logging?tabs=command-line

    // Create a configuration for the custom logger
    var loggerConfig = new AdsLoggerConfiguration
    {
    LogLevel = LogLevel.Information,
    EventId = 0
    };

    // Create an ILoggerFactory and add the custom logger provider
    var loggerFactory = LoggerFactory.Create(builder =>
    {
    //builder.SetMinimumLevel(LogLevel.Information)
    builder.AddProvider(new AdsLoggerProvider(() => loggerConfig))
       .AddConsole(); // Adds the console
    });

    // Use AdsClient with custom logger
    using (AdsClient client = new AdsClient(loggerFactory))
    {
    // Connect
    client.Connect(address);
    }

    // Use AdsSession with custom logger
    using (AdsSession session = new AdsSession(address, sessionSettings, loggerFactory))
    {
    // Connect
    session.Connect();
    }
}

Enhanced Logging/Configuration approach with HostBuilder

class Program
{
    static ILogger s_logger = null;

    public static void Main(string[] args)
    {
    // Create Build and run a Host Builder that runs the ServerWorker Hosted Service
    CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args)
    {
    //https://learn.microsoft.com/en-us/dotnet/core/extensions/logging?tabs=command-line
    //https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration

    var hostBuilder = Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
        services.AddHostedService<ServerWorker>();
        })
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
        // Add Configuration providers here ...
        //config.Sources.Clear(); // Clear all default config sources 

        // Different options for configuration
        //config.AddEnvironmentVariables(); // Use Environment variables
        //config.AddCommandLine(args); // Use Command Line
        //config.AddJsonFile("appSettings.json"); // Use AppSettings configuration file as config
        //config.AddStaticRoutesXmlConfiguration(null); // Use configuration from StaticRoutes.Xml 
        })
    .ConfigureLogging((context, logging) =>
    {
        // Create specific Ads Logger configuration for formatted output
        AdsLoggerConfiguration loggerConfig = AdsLoggerConfiguration.CreateFromConfiguration(context.Configuration);
        // Overwrites the configured Loglevel programatically
        // loggerConfig.LogLevel = LogLevel.Debug;

        logging.ClearProviders();
        // Adding console logging here.
        logging.AddProvider(new AdsLoggerProvider(() => loggerConfig)); // Adds the AdsLoggerProvider to logging providers
        logging.SetMinimumLevel(LogLevel.Debug);
    });
    return hostBuilder;
    }

    public class ServerWorker : BackgroundService
    {
    private ILoggerFactory _loggerFactory;
    private ILogger<ServerWorker> _logger;
    private IConfiguration _configuration;

    public ServerWorker(ILoggerFactory loggerFactory, IConfiguration configuration)
    {
        // This is called by the Host (Dependency injection)
        _configuration = configuration;
        _loggerFactory = loggerFactory;

        if (_loggerFactory != null)
        {
        _logger = _loggerFactory.CreateLogger<ServerWorker>();
        }
    }

    protected override async Task ExecuteAsync(CancellationToken cancel)
    {
        AdsSampleServer server1 = new AdsSampleServer(666, "TestAdsServer1", _loggerFactory);
        AdsSampleServer server2 = new AdsSampleServer(999, "TestAdsServer2", _loggerFactory);

        Task[] serverTasks = new Task[2];

        serverTasks[0] = Task.Run(async () =>
        {
        await server1.ConnectServerAndWaitAsync(cancel);
        });

        serverTasks[1] = Task.Run(async () =>
        {
        await server2.ConnectServerAndWaitAsync(cancel);
        });

        Task shutdownTask = Task.Run(async () =>
        {
        await Task.WhenAll(serverTasks);
        _logger.LogInformation("All AdsServers closed down.!");
        });

        Console.WriteLine("Press enter to shutdown servers ...");
        Console.ReadLine();

        server1.Disconnect();
        server2.Disconnect();

        await shutdownTask; // Wait for Shutdown of both Servers
    }
    }
}

The configuration can be done via

Reference

TwinCAT.Ads.Logging Namespace AdsLoggerProvider AdsLoggerConfiguration ILogger

Other Resources

Configuration overview Logging overview

Beckhoff Automation GmbH & Co. KG 2001-2026