AdsLoggerProvider Class
Logger provider class for ADS console logging. Implements the ILoggerProvider
Inheritance Hierarchy
SystemObject
TwinCAT.Ads.LoggingAdsLoggerProvider
Namespace: TwinCAT.Ads.Logging
Assembly: TwinCAT.Ads.ConfigurationProviders
(in TwinCAT.Ads.ConfigurationProviders.dll) Version:
7.0.0+e56d35ccc4675faac24789a4aab60071fc61d470
Syntax
C#
public class AdsLoggerProvider : ILoggerProvider,
IDisposableThe AdsLoggerProvider type exposes the following members.
Constructors
|
|
Name |
Description |
|---|---|---|
|
|
Initializes a new instance of the AdsLoggerProvider class. |
Methods
|
|
Name |
Description |
|---|---|---|
|
|
Creates a new AdsConsoleLogger instance that logs to the console. | |
|
|
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. | |
|
|
Determines whether the specified object is equal to the current
object. | |
|
|
Allows an object to try to free resources and perform other
cleanup operations before it is reclaimed by garbage
collection. | |
|
|
Serves as the default hash function. | |
|
|
Gets the Type of the current
instance. | |
|
|
Creates a shallow copy of the current Object. | |
|
|
Returns a string that represents the current object. |
Remarks
Represents a type that creates instances of the AdsConsoleLogger via the ILoggerProvider interface.
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
}
}
}