jxycms
5/6/2018 - 9:09 AM

Logging Error

see Entityframework core configuration for what config.json is

1. in config.json

{
  "ConnectionStrings": {
    "DutchConnectionString": "Data Source=OROCHI\\SQLEXPRESS;Initial Catalog=DutchTreat;Integrated Security=true;"
    //"DutchConnectionString": "server=(localdb)\\ProjectsV13;Database=DutchTreat;Integrated Security=true;"
  },

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning"
    }
  }
}

2. in repository file, add Ilogger in constructor

private readonly DutchContext context;
private readonly ILogger<DutchRepository> logger;

public DutchRepository(DutchContext context, ILogger<DutchRepository> logger) {
    this.context = context;
    this.logger = logger;
}

3. in the methods, use try catch to log errors in commandline
for example:
public IEnumerable<Product> GetAllProducts() {
    try {
        return this.context.Products
        .OrderBy(p => p.Title)
        .ToList();
    }
    catch (Exception ex) {
        this.logger.LogError($"File to get all products:{ex}");
        return null;
    }
    
}