I created custom Logger and LoggerProvider for writing logs in text file. This is my classes.
FileLogger:
public class FileLogger : ILogger
{
private string filePath;
private static object _lock = new object();
public FileLogger(string path)
{
filePath = path;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (formatter != null)
{
lock (_lock)
{
File.AppendAllText(filePath, formatter(state, exception) + Environment.NewLine);
}
}
}
}
FileLoggerProvider:
public class FileLoggerProvider : ILoggerProvider
{
private string path;
public FileLoggerProvider(string _path)
{
path = _path;
}
public ILogger CreateLogger(string categoryName)
{
return new FileLogger(path);
}
public void Dispose()
{
}
}
FileLoggerExtensions:
public static class FileLoggerExtensions
{
public static ILoggerFactory AddFile(this ILoggerFactory factory, string filePath)
{
factory.AddProvider(new FileLoggerProvider(filePath));
return factory;
}
}
And I want to log information in three different files. This is how I'm trying to do it:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
string logPath = CheckLogDir();
loggerFactory.AddFile(Path.Combine(logPath, "auction_log.txt"));
var auctionLogger = loggerFactory.CreateLogger("AuctionLogger");
loggerFactory.AddFile(Path.Combine(logPath, "requests_log.txt"));
var requestsLogger = loggerFactory.CreateLogger("RequestLogger");
loggerFactory.AddFile(Path.Combine(logPath, "error_log.txt"));
var errorLogger = loggerFactory.CreateLogger("ErrorLogger");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Then i call my loggers in controller like this:
public MainController(ILogger<MainController> auctionLogger, ILogger<MainController> requestLogger, ILogger<MainController> errorLogger, marketplaceContext context)
{
_auctionLogger = auctionLogger;
_requestLogger = requestLogger;
_errorLogger = errorLogger;
_db = context;
}
Then I'm trying to use them in different methods of controller and write different things. For example in GET method I'm using this:
_requestLogger.LogInformation("Processing request {0}", Request.Path);
But it writes this information to all three files, not only to requestLog.txt. What is my mistake? Help me please.