如何提供ASP.Net Core Logging额外参数

时间:2017-01-10 17:34:07

标签: c# asp.net asp.net-core error-logging

我正在关注this示例以自定义核心日志记录以将我的日志保存到DB。我得到了大部分工作,但只有一个问题:我需要在DBLogger类中以一种干净的方式传递更多参数的Log方法。它目前有这个签名:

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)

我希望能够包含其他一些领域。我想我可以将它们添加到由管道分隔的“状态”字段中以便稍后分解,但这种方式看起来很难看。

以下是代码的主要部分:

// DBLoggerExtensions
public static class DBLoggerExtensions
{
    public static ILoggerFactory AddContext(
        this ILoggerFactory factory,
        Func<string, LogLevel, bool> filter = null
        )
    {
        factory.AddProvider(new DBLoggerProvider(filter));
        return factory;
    }

    public static ILoggerFactory AddContext(this ILoggerFactory factory, LogLevel minLevel)
    {
        return AddContext(
            factory,
            (_, logLevel) => logLevel >= minLevel);
    }
}

//LoggerProvider
public class DBLoggerProvider : ILoggerProvider 
{ 
    private readonly Func<string, LogLevel, bool> _filter; 

    public DBLoggerProvider(Func<string, LogLevel, bool> filter) 
    { 
        _filter = filter; 
    } 
    public ILogger CreateLogger(string categoryName) 
    { 
        return new DBLogger(categoryName, _filter); 
    } 

    public void Dispose() 
    { 

    } 
} 
//DBLogger:
public class DBLogger : ILogger 
{ 
    private string _categoryName; 
    private Func<string, LogLevel, bool> _filter; 
    private CustomLoggerDBContext _context; 
    private bool _selfException = false; 

    public DBLogger(string categoryName, Func<string, LogLevel, bool> filter) 
    { 
        _categoryName = categoryName; 
        _filter = filter; 
        _context = new CustomLoggerDBContext(); 
    } 

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) 
    { 
        if (!IsEnabled(logLevel)) 
        { 
            return; 
        } 
        if (_selfException) 
        { 
            _selfException = false; 
            return; 
        } 
        _selfException = true; 
        if (formatter == null) 
        { 
            throw new ArgumentNullException(nameof(formatter)); 
        } 
        var message = formatter(state, exception); 
        if (string.IsNullOrEmpty(message)) 
        { 
            return; 
        } 

        if (exception != null) 
        { 
            message += "\n"+ exception.ToString(); 
        } 
        try 
        { 
            message = message.Length > CustomLoggerDBContext.MessageMaxLength ? 
                message.Substring(0,CustomLoggerDBContext.MessageMaxLength):message; 
            _context.EventLog.Add(new EventLog { 
                Message = message, 
                EventId = eventId.Id, 
                LogLevel = logLevel.ToString(), 
                CreatedTime = DateTime.UtcNow }); 
            _context.SaveChanges(); 
            _selfException = false; 
        } 
        catch { } 
    } 

    public bool IsEnabled(LogLevel logLevel) 
    { 
        return (_filter == null || _filter(_categoryName, logLevel)); 
    } 

    public IDisposable BeginScope<TState>(TState state) 
    { 
        return null; 
    } 
} 

欣赏它。

1 个答案:

答案 0 :(得分:0)

您没有得到这些参数。它们用于格式化。请参见以格式添加参数的示例

var usuario = "marcelo";
var endereco = "Rua A, número 123";
logger.LogInformation("Erro: Usuario: {usuario}, Enderço: {Endereco}", usuario, endereco);
//Func<TState, Exception, string> formatter => "Erro: Usuario: marcelo, Enderço: Rua A, número 123"