Use Ilogger with . Net Core 2

Asked

Viewed 1,131 times

1

I am studying . Net Core 2 and I have a question. I am wanting to log error in my Repository layer and only saw example in Controller. Some specific reason for this?

Follows my codes:

appsettings.json

{
   "ConnectionStrings": {
   "DefaultConnection": "Server=FAYOL\\SQLEXPRESS;Database=Pagamento;Trusted_Connection=True;MultipleActiveResultSets=true"
      },
      "Logging": {
        "IncludeScopes": false,
        "Debug": {
          "LogLevel": {
            "Default": "Warning"
          }
        },
        "Console": {
          "LogLevel": {
            "Default": "Warning"
          }
        }
      }
    }

Program.Cs

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}


public static IWebHost BuildWebHost(string[] args) =>
  WebHost.CreateDefaultBuilder(args)
     .UseStartup<Startup>()
     .ConfigureLogging((hostingContext, logging) =>
     {
                        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                        logging.AddConsole();
                        logging.AddDebug();
     })
     .Build();

Lojarepository.Cs

private readonly Contexto _context;
private readonly ILogger _logger;

public LojaRepository(Contexto context, ILogger<LojaRepository> logger)
{
   _context = context;
   _logger = logger;
}

public void Salvar(Loja loja)
{
    _logger.LogInformation("Teste de log para salvar");
}

Where I tell you what file name and where to save?

Thank you

  • You have to install a package that is a type of Provider that saves the logs of your application to a txt file: https://github.com/fulviocanducci/serilog-extensions-logging-file take a look at this link!

1 answer

1


You can use Serilog. With it you have several options where to register your log.

Install the following Nuget packages: Serilog.AspNetCore, Serilog.Sinks.Console and Serilog.Sinks.File

Configure Serilog in Program.Cs file:

public class Program
{
    public static void Main(string[] args)
    {
        // Configure Serilog for logging
        Log.Logger = new LoggerConfiguration()
       .MinimumLevel.Debug()
       .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
       .Enrich.FromLogContext()
       .WriteTo.Console()
       .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)
       .CreateLogger();

        try
        {
            Log.Information("Starting Amplifier web host");
            BuildWebHost(args).Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
        }
        finally
        {
            Log.CloseAndFlush();
        }            
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseSerilog() // Replace the default logging provider
            .Build();
}

Note that in the configuration we put the log to be saved in a file called log.txt in the logs folder and to print the log in the console.

After configured just use:

public class TestController : Controller
{
    private readonly ILogger _logger;

    public TestController(ILogger logger)
    {
        _logger = logger;
    }

    public IActionResult Register()
    {
        //Some controller logic...

        _logger.LogInformation("User named {0} created with id: {1}", user.Name, user.Id);
    }
}

For more details you can see the post I did about it on my blog

Browser other questions tagged

You are not signed in. Login or sign up in order to post.