Hi @Kalpana , Welcome to Microsoft Q&A,
Most of the official examples are for Asp.net core. Do you currently have to use ILoggerFactory? There are currently six official examples of Console output. The link is: Logging in .NET sample source code
You need to create a .Net 7.0 project.
The official example outputs to the console.
You can use StreamWriter to create a txt file, and then Customize ILoggerProvider, writes logs to text file.
The sample code is as follows:
using Microsoft.Extensions.Logging;
class Program
{
static void Main(string[] args)
{
//Define the path to the text file
string logFilePath = "console_log.txt";
//Create a StreamWriter to write logs to a text file
using (StreamWriter logFileWriter = new StreamWriter(logFilePath, append: true))
{
//Create an ILoggerFactory
ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
//Add console output
builder.AddSimpleConsole(options =>
{
options.IncludeScopes = true;
options.SingleLine = true;
options.TimestampFormat = "HH:mm:ss ";
});
//Add a custom log provider to write logs to text files
builder.AddProvider(new CustomFileLoggerProvider(logFileWriter));
});
//Create an ILogger
ILogger<Program> logger = loggerFactory.CreateLogger<Program>();
// Output some text on the console
using (logger.BeginScope("[scope is enabled]"))
{
logger.LogInformation("Hello World!");
logger.LogInformation("Logs contain timestamp and log level.");
logger.LogInformation("Each log message is fit in a single line.");
}
}
//your application code
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
// Customized ILoggerProvider, writes logs to text files
public class CustomFileLoggerProvider : ILoggerProvider
{
private readonly StreamWriter _logFileWriter;
public CustomFileLoggerProvider(StreamWriter logFileWriter)
{
_logFileWriter = logFileWriter ?? throw new ArgumentNullException(nameof(logFileWriter));
}
public ILogger CreateLogger(string categoryName)
{
return new CustomFileLogger(categoryName, _logFileWriter);
}
public void Dispose()
{
_logFileWriter.Dispose();
}
}
// Customized ILogger, writes logs to text files
public class CustomFileLogger : ILogger
{
private readonly string _categoryName;
private readonly StreamWriter _logFileWriter;
public CustomFileLogger(string categoryName, StreamWriter logFileWriter)
{
_categoryName = categoryName;
_logFileWriter = logFileWriter;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
// Ensure that only information level and higher logs are recorded
return logLevel >= LogLevel.Information;
}
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception exception,
Func<TState, Exception, string> formatter)
{
// Ensure that only information level and higher logs are recorded
if (!IsEnabled(logLevel))
{
return;
}
// Get the formatted log message
var message = formatter(state, exception);
//Write log messages to text file
_logFileWriter.WriteLine($"[{logLevel}] [{_categoryName}] {message}");
_logFileWriter.Flush();
}
}
Best Regards,
Jiale
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.