- Built-in providers let you send logs to one or more destinations, and you can plug in a third-party logging framework.
- If your data store is slow, write the log messages to a fast store first, then move them to a slow store later.
public class TodoController : Controller
{
private readonly ILogger _logger;
public TodoController(ILogger<TodoController> logger)
{
_logger = logger;
}
}
- To use a logger provider, add their service in the
ConfigureService
method.
public static void Main(string[] args)
{
var webHost = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>()
.Build();
webHost.Run();
}
- The default project template enables logging with the
CreateDefaultBuilder
method:
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
Log Factory and Log Category
- A category is included with each log that you create. You specify the category when you create an
ILogger
object.
- The category may be any string, but a convention is to use the fully qualified name of the class from which the logs are written.
- You can specify the category as a string or use an extension method that derives the category from the type.
- To specify the category as a string, call
CreateLogger
on an ILoggerFactory
instance.
- This is equivalent to calling
CreateLogger
with the fully qualified type name of T
.
public class TodoController : Controller
{
private readonly ILogger _logger;
public TodoController(ILoggerFactory logger)
{
_logger = logger.CreateLogger("TodoApi.Controllers.TodoController");
}
}
Log Levels
- The log level indicates the degree of severity or importance.
- You might write an
Information
log when a method ends normally, a Warning
log when a method returns a 404 return code, and an Error
log when you catch an unexpected exception.
Trace = 0
- For information that's valuable only to a developer debugging an issue.