Use ILogger with .Net Core 2

1

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

Here are 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();

ShopRepository.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 do I tell the file name and where to save it?

Thank you

    
asked by anonymous 27.05.2018 / 02:02

1 answer

1

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

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

Configure Serilog in the 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 start the log in the console.

Once 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 some more details you can see the post I made about this on my blog

    
01.06.2018 / 03:50