0

I want to log certain output in .net core webapi to a .txt file.

The Microsoft documentation says https://learn.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0&WT.mc_id=DT-MVP-5002040#console

 Call WebApplication.CreateBuilder, which adds the following logging providers:
 Console
 Debug
 EventSource
 EventLog: Windows only

There is no information on how to write to a .log file or a .txt file. It all says about console, debug and eventlog.

Am I missing something?

misterraj
  • 47
  • 1
  • 5
  • Does this answer your question? [Where does the log file get written to in .Net Core Logging](https://stackoverflow.com/questions/57614016/where-does-the-log-file-get-written-to-in-net-core-logging) – Robert Harvey Jun 30 '22 at 15:26

2 Answers2

0

In .NET logging has two parts - the ILoggerFactory which you inject into your code and use to write the logs, and a logging provider which handles the output.

When you call WebApplication.CreateBuilder it sets up the 4 output providers provided.

If you also want to log output to a text file you need to add a logging provider that writes text files. You can roll your own ILoggerProvider or just use an existing one.

If you add an ILoggerProvider that writes files to your DI services that will be used every time a log is written.

Keith
  • 150,284
  • 78
  • 298
  • 434
-3
public async Task<IActionResult> Login(AdminLoginViewModel admin)
{
  if (!ModelState.IsValid)
    return View();
    
  //AppUser user =await _userManager.FindByNameAsync(admin.UserName);
  AppUser user = await _userManager.Users.FirstOrDefaultAsync(x => x.IsAdmin && x.UserName == admin.UserName);
    
  if (user == null)
  {
    ModelState.AddModelError("", "UserName or Password is not correct!");
    return View();
  }
    
  var result = await _signInManager.PasswordSignInAsync(user, admin.PassWord, false, false);
    
  if (!result.Succeeded)
  {
    ModelState.AddModelError("", "UserName or Password is not correct!");
    return View();
  }
    
  return RedirectToAction("index", "dashboard");
}

layout/

@using Microsoft.AspNetCore.Identity
@inject UserManager<AppUser> _userManager
@{
  AppUser logged = null;
  if (User.Identity.IsAuthenticated)
    logged = await _userManager.FindByNameAsync(User.Identity.Name);
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Jhon
  • 1
  • 1
  • 1
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Jun 30 '22 at 00:08