1. 程式人生 > >動手造輪子:寫一個日誌框架

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

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

Intro

日誌框架有很多,比如 log4net / nlog / serilog / microsoft.extensions.logging 等,如何在切換日誌框架的時候做到不用修改程式碼,只需要切換不同的 loggingProvider 就可以了,最低成本的降低切換日誌框架的成本,處於這個考慮自己寫了一個日誌框架,為不同的日誌框架寫一個適配,需要用到什麼日誌框架,配置一下就可以了,業務程式碼無需變動。

V0

最初的日誌強依賴於 log4net,log4net 是我使用的第一個日誌框架,所以很長一段時間都在使用它來做日誌記錄,但是由於是強依賴,在想換日誌框架時就會很難受,大量程式碼要改動,不符合開放封閉的基本原則,於是就有了第一個版本的日誌。

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 等方法,擴充套件定義如下:

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 即可,但是從功能性上來說還是很弱的

如果想要某些日誌不記錄,比如說,Debug 級別的日誌不記錄,比如說某一個 Logger 下只記錄 Error 級別的日誌,現在是有些吃力,只能通過 log4net 的配置來限制了,於是就有了第二個版本,增加了 LoggingFilter 可以針對 Provider/Logger/LogLevel/Exception 來設定 filter,過濾不需要記錄的日誌,這也是參考了微軟的日誌框架的 Filter,但是實現不太一樣,有興趣的小夥伴可以自己深入研究一下。

V2

V2 版,在 ILogFactory 的介面上增加了 AddFilter 的方法,定義如下:

/// <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-periodicbatching

    /// <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

  • https://github.com/serilog/serilog
  • https://github.com/serilog/serilog-sinks-periodicbatching
  • https://github.com/aspnet/Logging
  • https://github.com/aspnet/Extensions/tree/master/src/Logging
  • https://github.com/WeihanLi/WeihanLi.Common/tree/dev/src/WeihanLi.Common/Logging