By default, there is no logging enabled. You may use any loggin you want, using the Microsoft builder pattern:
var builder = CommandHostBuilder.Create(commandline);
builder.ConfigureServices(services =>
{
services.AddLogging(loggingBuilder =>
{ ...
How to enable logging with NLog
Personally, I am using NLog for many years. So, lets demo how to use NLog.
Preparation
Create a nlog.config
file and
cadd it to your project (see Demo5)
Set Copy to Output directory
Fix your Main()
and add logging
services.AddLogging(loggingBuilder =>
{
loggingBuilder.ClearProviders();
loggingBuilder.AddNLog();
});
Use logging in your Commands
Logging is injected into your Command using dependency injection.
As defined in nlog.config
DEBUG messages go to the log file logs\demo5.log, while
INFO messages are printed on the Console.
public Mult2Command(
IServiceProvider serviceProvider,
ILogger<Mult2Command> logger) : base(serviceProvider)
{
_logger = logger;
}
protected override void Execute()
{
_logger.LogDebug($"Serialized Context='{JsonSerializer.Serialize(Context)}'");
decimal result = this.Context.Factor1 * this.Context.Factor2;
_logger.LogInformation($"{this.Context.Factor1} * {this.Context.Factor2} = {result}");
}
Console logging
> demo5app MATH MULT2 /f1=5,43 /f2=7,54
Demo05 - Logging and Printing
Mult2Command : 5,43 * 7,54 = 40,9422
File Log
The file log is configured to save all DEBUG messages, which include MSPro.CLArgs.
messages
2022-08-24 15:40:55.0750|DEBUG| 5|MSPro.CLArgs.CommandHost|'MATH.MULT2'->Mult2Command|
2022-08-24 15:40:55.0940|DEBUG| 5|MSPro.CLArgs.CommandHost|Verb:MATH|
2022-08-24 15:40:55.0940|DEBUG| 5|MSPro.CLArgs.CommandHost|Verb:MULT2|
2022-08-24 15:40:55.0940|DEBUG| 5|MSPro.CLArgs.CommandHost|Option:f1=5,43|
2022-08-24 15:40:55.0940|DEBUG| 5|MSPro.CLArgs.CommandHost|Option:f2=7,54|
2022-08-24 15:40:55.0940|DEBUG| 5|MSPro.CLArgs.CommandHost|Target:|
2022-08-24 15:40:55.1832|DEBUG| 5|Mult2Command |Serialized Context='{"Factor1":5.43,"Factor2":7.54}'|
2022-08-24 15:40:55.1832|INFO | 5|Mult2Command |5,43 * 7,54 = 40,9422|