動手造輪子:寫一個日誌框架

動手造輪子:寫一個日誌框架

Intro

日誌框架有不少,好比 log4net / nlog / serilog / microsoft.extensions.logging 等,如何在切換日誌框架的時候作到不用修改代碼,只須要切換不一樣的 loggingProvider 就能夠了,最低成本的下降切換日誌框架的成本,處於這個考慮本身寫了一個日誌框架,爲不一樣的日誌框架寫一個適配,須要用到什麼日誌框架,配置一下就能夠了,業務代碼無需變更。git

V0

最初的日誌強依賴於 log4net,log4net 是我使用的第一個日誌框架,因此很長一段時間都在使用它來作日誌記錄,可是因爲是強依賴,在想換日誌框架時就會很難受,大量代碼要改動,不符合開放封閉的基本原則,因而就有了第一個版本的日誌。github

V1

初版的日誌參考了微軟的日誌框架的實現,大概結構以下:框架

public interface ILogHelperLogFactory
{
    ILogger CreateLogger(string categoryName);
    
    bool AddProvider(ILogHelperProvider provider);
}
public interface ILogHelperLogger
{
    bool IsEnabled(LogHelperLogLevel logLevel);
    void Log(LogHelperLogLevel logLevel, Exception exception, string message);
}
public enum LogHelperLogLevel
{
    /// <summary>
    /// All logging levels
    /// </summary>
    All = 0,

    /// <summary>
    /// A trace logging level
    /// </summary>
    Trace = 1,

    /// <summary>
    /// A debug logging level
    /// </summary>
    Debug = 2,

    /// <summary>
    /// A info logging level
    /// </summary>
    Info = 4,

    /// <summary>
    /// A warn logging level
    /// </summary>
    Warn = 8,

    /// <summary>
    /// An error logging level
    /// </summary>
    Error = 16,

    /// <summary>
    /// A fatal logging level
    /// </summary>
    Fatal = 32,

    /// <summary>
    /// None
    /// </summary>
    None = 64
}
public interface ILogHelperProvider
{
    ILogHelperLogger CreateLogger(string categoryName);
}

爲了方便 Logger 的使用,定義了一些擴展方法,使得能夠直接使用 logger.Info/logger.Error 等方法,擴展定義以下:ide

public static void Log(this ILogHelperLogger logger, LogHelperLevel loggerLevel, string msg) => logger.Log(loggerLevel, null, msg);

#region Info

    public static void Info(this ILogHelperLogger logger, string msg, params object[] parameters)
{
    if (parameters == null || parameters.Length == 0)
    {
        logger.Log(LogHelperLevel.Info, msg);
    }
    else
    {
        logger.Log(LogHelperLevel.Info, null, msg.FormatWith(parameters));
    }
}

public static void Info(this ILogHelperLogger logger, Exception ex, string msg) => logger.Log(LogHelperLevel.Info, ex, msg);

public static void Info(this ILogHelperLogger logger, Exception ex) => logger.Log(LogHelperLevel.Info, ex, ex?.Message);

#endregion Info
// ...其餘的相似,這裏就不詳細展開了

若是要自定義的日誌記錄的話,就實現一個 ILogHelperProvider 便可,實現一個 ILogHelperProvider 就要實現一個 ILogHelperLogger ,本來強依賴的 log4net 能夠實現一個 Log4NetLogHelperProvider,這樣換別的日誌框架的時候只須要實現對應的 ILogHelperProvider 便可,可是從功能性上來講仍是很弱的ui

若是想要某些日誌不記錄,好比說,Debug 級別的日誌不記錄,好比說某一個 Logger 下只記錄 Error 級別的日誌,如今是有些吃力,只能經過 log4net 的配置來限制了,因而就有了第二個版本,增長了 LoggingFilter 能夠針對 Provider/Logger/LogLevel/Exception 來設置 filter,過濾不須要記錄的日誌,這也是參考了微軟的日誌框架的 Filter,可是實現不太同樣,有興趣的小夥伴能夠本身深刻研究一下。this

V2

V2 版,在 ILogFactory 的接口上增長了 AddFilter 的方法,定義以下:debug

/// <summary>   
/// Add logs filter 
/// </summary>  
/// <param name="filterFunc">filterFunc, logProviderType/categoryName/Exception, whether to write log</param>   
bool AddFilter(Func<Type, string, LogHelperLogLevel, Exception, bool> filterFunc);

而後定義了一些擴展方法來方便使用:設計

public static ILogHelperFactory WithMinimumLevel(this ILogHelperFactory logHelperFactory, LogHelperLevel logLevel)
{
    return logHelperFactory.WithFilter(level => level >= logLevel);
}

public static ILogHelperFactory WithFilter(this ILogHelperFactory logHelperFactory, Func<LogHelperLevel, bool> filterFunc)
{
    logHelperFactory.AddFilter((type, categoryName, logLevel, exception) => filterFunc.Invoke(logLevel));
    return logHelperFactory;
}

public static ILogHelperFactory WithFilter(this ILogHelperFactory logHelperFactory, Func<string, LogHelperLevel, bool> filterFunc)
{
    logHelperFactory.AddFilter((type, categoryName, logLevel, exception) => filterFunc.Invoke(categoryName, logLevel));
    return logHelperFactory;
}

public static ILogHelperFactory WithFilter(this ILogHelperFactory logHelperFactory, Func<Type, string, LogHelperLevel, bool> filterFunc)
{
    logHelperFactory.AddFilter((type, categoryName, logLevel, exception) => filterFunc.Invoke(type, categoryName, logLevel));
    return logHelperFactory;
}

public static ILogHelperFactory WithFilter(this ILogHelperFactory logHelperFactory, Func<Type, string, LogHelperLevel, Exception, bool> filterFunc)
{
    logHelperFactory.AddFilter(filterFunc);
    return logHelperFactory;
}

這樣就方便了咱們只想定義針對 Logger 的 Filter 以及 Provider 的 Filter,沒必要全部參數都用到,logging filter 如今已經實現了,此時已經使用了 Serilog 作日誌記錄有一段時間,感受 Serilog 裏的一些設計很優秀,很優雅,因而想把 Serilog 裏的一些設計用在本身的日誌框架裏,好比說:日誌

  1. Serilog 的擴展叫作 Sink,日誌輸出的地方,Serilog 自定義一個 Sink,很簡單隻須要實現一個接口,不須要再實現一個 Logger,從這點來講,我以爲 Serilog 比微軟的日誌框架更加優秀,並且 LogEvent 使得日誌更方便的進行批量操做,有須要的能夠了解一下 SerilogPeriodBatching https://github.com/serilog/serilog-sinks-periodicbatchingcode

    /// <summary>
    /// A destination for log events.
    /// </summary>
    public interface ILogEventSink
    {
        /// <summary>
        /// Emit the provided log event to the sink.
        /// </summary>
        /// <param name="logEvent">The log event to write.</param>
        void Emit(LogEvent logEvent);
    }
  2. Serilog 能夠自定義一些 Enricher,以此來豐富記錄的日誌內容,好比日誌的請求上下文,日誌的環境等,也能夠是一些固定的屬性信息

  3. MessageTemplate,其實微軟的日誌框架中也有相似的概念,只不過很不明顯,用 Serilog 以前我也不多用,微軟的日誌框架能夠這樣用 logger.LogInfo("hello {name}", "world") 這樣的寫法其實就能夠把第一個參數看成是 MessageTemplate 或者它內部的叫法 Format

鑑於這麼多好處,因而打算將這些功能引入到個人日誌框架中

V3

引入 LoggingEvent

說幹就幹,首先要引入一個 LogHelperLoggingEvent,對應的 SerilogLogEvent,定義以下:

public class LogHelperLoggingEvent : ICloneable
{
    public string CategoryName { get; set; }

    public DateTimeOffset DateTime { get; set; }

    public string MessageTemplate { get; set; }

    public string Message { get; set; }

    public Exception Exception { get; set; }

    public LogHelperLogLevel LogLevel { get; set; }

    public Dictionary<string, object> Properties { get; set; }

    public LogHelperLoggingEvent Copy => (LogHelperLoggingEvent)Clone();

    public object Clone()
    {
        var newEvent = (LogHelperLoggingEvent)MemberwiseClone();
        if (Properties != null)
        {
            newEvent.Properties = new Dictionary<string, object>();
            foreach (var property in Properties)
            {
                newEvent.Properties[property.Key] = property.Value;
            }
        }
        return newEvent;
    }
}

Event 裏定義了一個 Properties 的字典用來豐富日誌的內容,另外實現了 ICloneable 接口,方便對對象的拷貝,爲了強類型,增長了一個 Copy 的方法,返回一個強類型的對象

改造 LogProvider

爲了減小擴展一個 ILogProvider 的複雜性,咱們要對 ILogProvider 作一個簡化,只須要像擴展 Serilog 的 Sink 同樣記錄日誌便可,不須要關心是否要建立 Logger

改造後的定義以下:

public interface ILogHelperProvider
{
    Task Log(LogHelperLoggingEvent loggingEvent);
}

(這裏返回了一個 Task,可能返回類型是 void 就足夠了,看本身的須要)

這樣在實現 LogProvider 的時候只須要實現這個接口就能夠了,不須要再實現一個 Logger 了

增長 Enricher

Enricher 定義:

public interface ILogHelperLoggingEnricher
{
    void Enrich(LogHelperLoggingEvent loggingEvent);
}

內置了一個 PropertyEnricher,方便添加一些簡單的屬性

internal class PropertyLoggingEnricher : ILogHelperLoggingEnricher
{
    private readonly string _propertyName;
    private readonly Func<LogHelperLoggingEvent, object> _propertyValueFactory;
    private readonly bool _overwrite;
    private readonly Func<LogHelperLoggingEvent, bool> _logPropertyPredict = null;

    public PropertyLoggingEnricher(string propertyName, object propertyValue, bool overwrite = false) : this(propertyName, (loggingEvent) => propertyValue, overwrite)
    {
    }

    public PropertyLoggingEnricher(string propertyName, Func<LogHelperLoggingEvent, object> propertyValueFactory,
                                   bool overwrite = false) : this(propertyName, propertyValueFactory, null, overwrite)
    {
    }

    public PropertyLoggingEnricher(string propertyName, Func<LogHelperLoggingEvent, object> propertyValueFactory, Func<LogHelperLoggingEvent, bool> logPropertyPredict,
                                   bool overwrite = false)
    {
        _propertyName = propertyName;
        _propertyValueFactory = propertyValueFactory;
        _logPropertyPredict = logPropertyPredict;
        _overwrite = overwrite;
    }

    public void Enrich(LogHelperLoggingEvent loggingEvent)
    {
        if (_logPropertyPredict?.Invoke(loggingEvent) != false)
        {
            loggingEvent.AddProperty(_propertyName, _propertyValueFactory, _overwrite);
        }
    }
}

ILogFactory 增長一個 AddEnricher 的方法

/// <summary>
/// add log enricher
/// </summary>
/// <param name="enricher">log enricher</param>
/// <returns></returns>
bool AddEnricher(ILogHelperLoggingEnricher enricher);

這樣咱們在記錄日誌的時候就能夠經過這些 Enricher 豐富 LoggingEvent 中的 Properties 了

爲了方便 Property 的操做,咱們增長了一些擴展方法:

public static ILogHelperFactory WithEnricher<TEnricher>(this ILogHelperFactory logHelperFactory,
                                                        TEnricher enricher) where TEnricher : ILogHelperLoggingEnricher
{
    logHelperFactory.AddEnricher(enricher);
    return logHelperFactory;
}

public static ILogHelperFactory WithEnricher<TEnricher>(this ILogHelperFactory logHelperFactory) where TEnricher : ILogHelperLoggingEnricher, new()
{
    logHelperFactory.AddEnricher(new TEnricher());
    return logHelperFactory;
}

public static ILogHelperFactory EnrichWithProperty(this ILogHelperFactory logHelperFactory, string propertyName, object value, bool overwrite = false)
{
    logHelperFactory.AddEnricher(new PropertyLoggingEnricher(propertyName, value, overwrite));
    return logHelperFactory;
}

public static ILogHelperFactory EnrichWithProperty(this ILogHelperFactory logHelperFactory, string propertyName, Func<LogHelperLoggingEvent> valueFactory, bool overwrite = false)
{
    logHelperFactory.AddEnricher(new PropertyLoggingEnricher(propertyName, valueFactory, overwrite));
    return logHelperFactory;
}

public static ILogHelperFactory EnrichWithProperty(this ILogHelperFactory logHelperFactory, string propertyName, object value, Func<LogHelperLoggingEvent, bool> predict, bool overwrite = false)
{
    logHelperFactory.AddEnricher(new PropertyLoggingEnricher(propertyName, e => value, predict, overwrite));
    return logHelperFactory;
}

public static ILogHelperFactory EnrichWithProperty(this ILogHelperFactory logHelperFactory, string propertyName, Func<LogHelperLoggingEvent, object> valueFactory, Func<LogHelperLoggingEvent, bool> predict, bool overwrite = false)
{
    logHelperFactory.AddEnricher(new PropertyLoggingEnricher(propertyName, valueFactory, predict, overwrite));
    return logHelperFactory;
}

MessageTemplate

從上面的 LoggingEvent 中已經增長了 MessageTemplate,因而咱們引入了微軟日誌框架中日誌的格式化,將 messageTemplate 和 parameters 轉換成 Message 和 Properties,具體參考 https://github.com/WeihanLi/WeihanLi.Common/blob/276cc49cfda511f9b7b3bb8344ee52441c4a3b23/src/WeihanLi.Common/Logging/LoggingFormatter.cs

internal struct FormattedLogValue
{
    public string Msg { get; set; }

    public Dictionary<string, object> Values { get; set; }

    public FormattedLogValue(string msg, Dictionary<string, object> values)
    {
        Msg = msg;
        Values = values;
    }
}

internal static class LoggingFormatter
{
    public static FormattedLogValue Format(string msgTemplate, object[] values)
    {
        if (values == null || values.Length == 0)
            return new FormattedLogValue(msgTemplate, null);

        var formatter = new LogValuesFormatter(msgTemplate);
        var msg = formatter.Format(values);
        var dic = formatter.GetValues(values)
            .ToDictionary(x => x.Key, x => x.Value);

        return new FormattedLogValue(msg, dic);
    }
}

這樣咱們就能夠支持 messageTemplate 了,而後來改造一下咱們的 Logger

public interface ILogHelperLogger
{
    void Log(LogHelperLogLevel logLevel, Exception exception, string messageTemplate, params object[] parameters);

    bool IsEnabled(LogHelperLogLevel logLevel);
}

與上面不一樣的是,咱們增長了 parameters

再來更新一下咱們的擴展方法,上面的擴展方法是直接使用 string.Format 的方式的格式化的,咱們這裏要更新一下

public static void Info(this ILogHelperLogger logger, string msg, params object[] parameters)
{
    logger.Log(LogHelperLogLevel.Info, null, msg, parameters);
}

public static void Info(this ILogHelperLogger logger, Exception ex, string msg) => logger.Log(LogHelperLogLevel.Info, ex, msg);

public static void Info(this ILogHelperLogger logger, Exception ex) => logger.Log(LogHelperLogLevel.Info, ex, ex?.Message);

至此,功能基本完成,可是從 API 的角度來講,感受如今的 ILogFactory過重了,這些 AddProvider/AddEnricher/AddFilter 都應該屬性 ILogFactory 的內部屬性,經過配置來完成,不該該成爲它的接口方法,因而就有了下一版

V4

這一版主要是引入了 LoggingBuilder, 經過 LoggingBuilder 來配置內部的 LogFactory 所須要的 Provider/Enricher/Filter,原來他們的配置方法和擴展方法均變成ILogHelperLoggingBuilder

public interface ILogHelperLoggingBuilder
{
    /// <summary>
    /// Adds an ILogHelperProvider to the logging system.
    /// </summary>
    /// <param name="provider">The ILogHelperProvider.</param>
    bool AddProvider(ILogHelperProvider provider);

    /// <summary>
    /// add log enricher
    /// </summary>
    /// <param name="enricher">log enricher</param>
    /// <returns></returns>
    bool AddEnricher(ILogHelperLoggingEnricher enricher);

    /// <summary>
    /// Add logs filter
    /// </summary>
    /// <param name="filterFunc">filterFunc, logProviderType/categoryName/Exception, whether to write log</param>
    bool AddFilter(Func<Type, string, LogHelperLogLevel, Exception, bool> filterFunc);

    ///// <summary>
    ///// config period batching
    ///// </summary>
    ///// <param name="period">period</param>
    ///// <param name="batchSize">batchSize</param>
    //void PeriodBatchingConfig(TimeSpan period, int batchSize);

    /// <summary>
    /// Build for LogFactory
    /// </summary>
    /// <returns></returns>
    ILogHelperFactory Build();
}

增長 logging 的配置:

public static class LogHelper
{
    private static ILogHelperFactory LogFactory { get; private set; } = NullLogHelperFactory.Instance;

    public static void ConfigureLogging(Action<ILogHelperLoggingBuilder> configureAction)
    {
        var loggingBuilder = new LogHelperLoggingBuilder();
        configureAction?.Invoke(loggingBuilder);
        LogFactory = loggingBuilder.Build();
    }

    public static ILogHelperLogger GetLogger<T>() => LogFactory.GetLogger(typeof(T));

    public static ILogHelperLogger GetLogger(Type type) => LogFactory.GetLogger(type);

    public static ILogHelperLogger GetLogger(string categoryName)
    {
        return LogFactory.CreateLogger(categoryName);
    }
}

最後的使用方式:

internal class LoggingTest
{
    private static readonly ILogHelperLogger Logger = LogHelper.GetLogger<LoggingTest>();

    public static void MainTest()
    {
        var abc = "1233";
        LogHelper.ConfigureLogging(builder =>
                                   {
                                       builder
                                           .AddLog4Net()
                                           //.AddSerilog(loggerConfig => loggerConfig.WriteTo.Console())
                                           .WithMinimumLevel(LogHelperLogLevel.Info)
                                           .WithFilter((category, level) => level > LogHelperLogLevel.Error && category.StartsWith("System"))
                                           .EnrichWithProperty("Entry0", ApplicationHelper.ApplicationName)
                                           .EnrichWithProperty("Entry1", ApplicationHelper.ApplicationName, e => e.LogLevel >= LogHelperLogLevel.Error)// 當 LogLevel 是 Error 及以上級別時才增長 Property
                                           ;
                                   });

        Logger.Debug("12333 {abc}", abc);
        Logger.Trace("122334334");
        Logger.Info($"122334334 {abc}");

        Logger.Warn("12333, err:{err}", "hahaha");
        Logger.Error("122334334");
        Logger.Fatal("12333");
    }
}

More

增長 LoggingEvent 還想作一個批量提交日誌,如上面定義的 PeriodBatchingConfig 同樣,批量同步到 Provider 可是實際使用下來,有些 provider 不支持設置日誌的時間,時間是內部記錄的,這樣一來日誌記錄的時間就不許了,並且大多都不支持批量寫日誌,因此後面放棄了,可是若是隻是用本身的擴展,不用 log4net 之類的外部的日誌框架的話,我以爲仍是能夠作的,能夠提升效率,目前主要用 Seriloglog4net,暫時不更新了,就先這樣吧

下一版本要解決的事情

  • ILogProvider 記錄日誌返回一個 Task 感受有些雞肋,沒太大意義,後面再改一下吧
  • Serilog 的 Filter 是基於 LogEvent 的,後面看是否須要改一下,基於 LogEvent 的話更簡潔,並且能夠根據 LogEvent 內的 Properties 作過濾,因此 AddFilter 的API 能夠更新一下 AddFilter(Func<LogHelperLoggingEvent, bool> filter)

Reference

相關文章
相關標籤/搜索