DotNETCore 学习笔记 日志

Logging
---------------------------------------------------------------------------------------
Implementing Logging in your Application

var logger = loggerFactory.CreateLogger("Catchall Endpoint");
logger.LogInformation("No endpoint found for request {path}", context.Request.Path);


[Route("api/[controller]")]
public class TodoController : Controller
{
    private readonly ITodoRepository _todoRepository;
    private readonly ILogger<TodoController> _logger;

    public TodoController(ITodoRepository todoRepository, 
        ILogger<TodoController> logger)
    {
        _todoRepository = todoRepository;
        _logger = logger;
    }

    [HttpGet]
    public IEnumerable<TodoItem> GetAll()
    {
        _logger.LogInformation(LoggingEvents.LIST_ITEMS, "Listing all items");
        EnsureItems();
        return _todoRepository.GetAll();
    }


Logging Verbosity Levels

Trace
Used for the most detailed log messages, typically only valuable to a developer debugging an issue. These 

messages may contain sensitive application data and so should not be enabled in a production environment. 

Disabled by default. Example: Credentials: {"User":"someuser", "Password":"P@ssword"}

Debug
These messages have short-term usefulness during development. They contain information that may be useful 

for debugging, but have no long-term value. This is the default most verbose level of logging. Example: 

Entering method Configure with flag set to true

Information
These messages are used to track the general flow of the application. These logs should have some long term 

value, as opposed to Verbose level messages, which do not. Example: Request received for path /foo

Warning
The Warning level should be used for abnormal or unexpected events in the application flow. These may 

include errors or other conditions that do not cause the application to stop, but which may need to be 

investigated in the future. Handled exceptions are a common place to use the Warning log level. Examples: 

Login failed for IP 127.0.0.1 or FileNotFoundException for file foo.txt

Error
An error should be logged when the current flow of the application must stop due to some failure, such as an 

exception that cannot be handled or recovered from. These messages should indicate a failure in the current 

activity or operation (such as the current HTTP request), not an application-wide failure. Example: Cannot 

insert record due to duplicate key violation

Critical
A critical log level should be reserved for unrecoverable application or system crashes, or catastrophic 

failure that requires immediate attention. Examples: data loss scenarios, out of disk space


 _logger.LogInformation(LoggingEvents.LIST_ITEMS, "Listing all items");
 _logger.LogInformation(LoggingEvents.GET_ITEM, "Getting item {0}", id);

Log Level        Prefix
Critical         crit 
Error             fail 
Warning         warn 
Information         info 
Debug             dbug 
Trace             trce 

loggerFactory
    .WithFilter(new FilterLoggerSettings
    {
        { "Microsoft", LogLevel.Warning },
        { "System", LogLevel.Warning },
        { "ToDoApi", LogLevel.Debug }
    })
    .AddConsole();



"Microsoft.AspNetCore.Mvc": "1.0.0",
  "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
  "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
  "Microsoft.AspNetCore.StaticFiles": "1.0.0",
  "Microsoft.Extensions.Logging": "1.0.0",
  "Microsoft.Extensions.Logging.Console": "1.0.0",
  "Microsoft.Extensions.Logging.Filter": "1.0.0",
  "Microsoft.Extensions.Logging.TraceSource": "1.0.0"
},
"tools": {
  "Microsoft.AspNetCore.Server.IISIntegration.Tools": {


// add Trace Source logging
var testSwitch = new SourceSwitch("sourceSwitch", "Logging Sample");
testSwitch.Level = SourceLevels.Warning;
loggerFactory.AddTraceSource(testSwitch,
    new TextWriterTraceListener(writer: Console.Out));

[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)
{
    _logger.LogInformation(LoggingEvents.GET_ITEM, "Getting item {0}", id);
    var item = _todoRepository.Find(id);
    if (item == null)
    {
        _logger.LogWarning(LoggingEvents.GET_ITEM_NOTFOUND, "GetById({0}) NOT FOUND", id);
        return NotFound();
    }
    return new ObjectResult(item);
}

 

posted @ 2016-05-14 14:02  自然去留  阅读(477)  评论(0编辑  收藏  举报