Class Log
The Log class provides centralized logging support for your application or library. It allows you to configure logging either through a JSON configuration file (appsettings.json) or by dynamically setting up a logger using the ConfigureLoggerFactory(Action<ILoggingBuilder>) method.
How to enable Logging:
There are two primary ways to enable logging:- 1. Add an
appsettings.json
to your project. - 2. Use the ConfigureLoggerFactory(Action<ILoggingBuilder>) method.
Option 1: Using appsettings.json
Place anappsettings.json
file in your project directory with the following structure:
{
"Logging": {
"LogLevel": {
"Yubico.Core": "Warning",
"Yubico.Yubikey": "Information"
}
}
}
Option 2: Using ConfigureLoggerFactory
Configure the logger dynamically in your code:// Optionally, clear previous loggers
Log.ConfigureLoggerFactory(builder => builder.ClearProviders());
// Add a console logger (added by default)
Log.ConfigureLoggerFactory(builder => builder.AddConsole());
// Add a Serilog logger
Log.ConfigureLoggerFactory(builder => builder.AddSerilog());
// Add both Console and Serilog loggers
Log.ConfigureLoggerFactory(builder => builder.AddConsole().AddSerilog());
Using the Logger
After configuring the logger, you can create log instances and log messages as follows:namespace Yubico;
public class ExampleClass
{
public ExampleClass()
{
// Logger with the class name as the category
ILogger typeNamedLogger = Log.GetLogger<ExampleClass>();
typeNamedLogger.LogInformation("Hello World");
// Output: Yubico.ExampleClass: Hello World
// Logger with a custom category name
ILogger categoryLogger = Log.GetLogger("SmartCard");
categoryLogger.LogInformation("Hello World");
// Output: SmartCard: Hello World
}
}
Note:
You can also directly set a custom logger factory using the Instance property, though it is not the recommended approach. Using ConfigureLoggerFactory(Action<ILoggingBuilder>) or the appsettings.json approach is preferred.public static class Log
- Inheritance
-
objectLog
Properties
Instance
Gets or sets the global ILoggerFactory instance used for logging throughout the application.
By default, it's instantiated by using the Logging-section
in your
appsettings.jsonfile.
Refer to the Log class for additional information.
public static ILoggerFactory Instance { get; set; }
Property Value
Methods
ConfigureLoggerFactory(Action<ILoggingBuilder>)
Logging.ConfigureLoggerFactory(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Trace));
With the default logging factory, you can load config using json.
public static void ConfigureLoggerFactory(Action<ILoggingBuilder> configure)
Parameters
configure
Action<ILoggingBuilder>
GetLogger(string)
Creates a new ILogger instance using the full name of the given type
.
public static ILogger GetLogger(string categoryName)
Parameters
categoryName
string
Returns
GetLogger<T>()
Creates a new ILogger instance using the full name of the given type.
public static ILogger GetLogger<T>()
Returns
Type Parameters
T
The type.