Hi,@mehmood tekfirst
Writting a log file was not provided by default,you could try with a third-part tool or try to create a custom IloggerProvider,
I tried as below:
public class CustomFileLogger : ILogger
{
private readonly string _name;
private readonly CustomFileLoggerConfiguration _config;
private LogLevel _logLevel;
public CustomFileLogger(string name, CustomFileLoggerConfiguration config)
{
_name = name;
_config = config;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel == _config.LogLevel;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
_logLevel = logLevel;
FileLog($"{DateTime.Now.ToString("yyyy-MM-dd hh:mm:fff")} - {logLevel.ToString()} - {_name} - {formatter(state, exception)}");
}
private async void FileLog(string strLog)
{
var sb = new StringBuilder(strLog);
sb.AppendLine();
var targetstr = sb.ToString();
string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "_" + _logLevel.ToString() + ".txt";
string filePath = _config.LogPath + "\\" + fileName;
File.AppendAllText(filePath, strLog);
await File.AppendAllTextAsync(filePath, targetstr);
}
}
public class CustomFileLoggerConfiguration
{
public LogLevel LogLevel { get; set; }
public string LogPath { get; set; }
}
public class CustomFileLoggerProvider : ILoggerProvider
{
private readonly CustomFileLoggerConfiguration _config;
public CustomFileLoggerProvider(CustomFileLoggerConfiguration config)
{
this._config = config;
}
public ILogger CreateLogger(string categoryName)
{
return new CustomFileLogger(categoryName, _config);
}
public void Dispose()
{
}
}
in program.cs:
builder.Logging.AddProvider(new CustomFileLoggerProvider(new CustomFileLoggerConfiguration
{
LogLevel = LogLevel.Information,
LogPath = builder.Configuration["FileLogPath:LogPath"]
}));
in appsettings:
{
...
"FileLogPath": {
"LogPath": "C:\\Users\\ruikaif\\Desktop"
},
...
}
in controller:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogInformation("hellow");
_logger.LogInformation("test");
return View();
}
}
The Result:
----------
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.
Best regards
RuikaiFeng