1. 程式人生 > >[Abp vNext 原始碼分析] - 8. 審計日誌

[Abp vNext 原始碼分析] - 8. 審計日誌

一、簡要說明

ABP vNext 當中的審計模組早在 依賴注入與攔截器一文中有所提及,但沒有詳細的對其進行分析。

審計模組是 ABP vNext 框架的一個基本元件,它能夠提供一些實用日誌記錄。不過這裡的日誌不是說系統日誌,而是說介面每次呼叫之後的執行情況(執行時間、傳入引數、異常資訊、請求 IP)。

除了常規的日誌功能以外,關於 實體 和 聚合 的審計欄位介面也是存放在審計模組當中的。(建立人、建立時間、修改人、修改時間、刪除人、刪除時間)

二、原始碼分析

2.1. 審計日誌攔截器

2.1.1 審計日誌攔截器的註冊

Volo.Abp.Auditing 的模組定義十分簡單,主要是提供了 審計日誌攔截器 的註冊功能。下面程式碼即在元件註冊的時候,會呼叫 AuditingInterceptorRegistrar.RegisterIfNeeded

方法來判定是否為實現型別(ImplementationType) 注入審計日誌攔截器。

public class AbpAuditingModule : AbpModule
{
    public override void PreConfigureServices(ServiceConfigurationContext context)
    {
        context.Services.OnRegistred(AuditingInterceptorRegistrar.RegisterIfNeeded);
    }
}

跳轉到具體的實現,可以看到內部會結合三種類型進行判斷。分別是 AuditedAttribute

IAuditingEnabledDisableAuditingAttribute

前兩個作用是,只要型別標註了 AuditedAttribute 特性,或者是實現了 IAuditingEnable 介面,都會為該型別注入審計日誌攔截器。

DisableAuditingAttribute 型別則相反,只要型別上標註了該特性,就不會啟用審計日誌攔截器。某些介面需要 提升效能 的話,可以嘗試使用該特性禁用掉審計日誌功能。

public static class AuditingInterceptorRegistrar
{
    public static void RegisterIfNeeded(IOnServiceRegistredContext context)
    {
        // 滿足條件時,將會為該型別注入審計日誌攔截器。
        if (ShouldIntercept(context.ImplementationType))
        {
            context.Interceptors.TryAdd<AuditingInterceptor>();
        }
    }

    private static bool ShouldIntercept(Type type)
    {
        // 首先判斷型別上面是否使用了輔助型別。
        if (ShouldAuditTypeByDefault(type))
        {
            return true;
        }

        // 如果任意方法上面標註了 AuditedAttribute 特性,則仍然為該型別注入攔截器。
        if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true)))
        {
            return true;
        }

        return false;
    }

    //TODO: Move to a better place
    public static bool ShouldAuditTypeByDefault(Type type)
    {
        // 下面就是根據三種輔助型別進行判斷,是否為當前 type 注入審計日誌攔截器。
        if (type.IsDefined(typeof(AuditedAttribute), true))
        {
            return true;
        }

        if (type.IsDefined(typeof(DisableAuditingAttribute), true))
        {
            return false;
        }

        if (typeof(IAuditingEnabled).IsAssignableFrom(type))
        {
            return true;
        }

        return false;
    }
}

2.1.2 審計日誌攔截器的實現

審計日誌攔截器的內部實現,主要使用了三個型別進行協同工作。它們分別是負責管理審計日誌資訊的 IAuditingManager,負責建立審計日誌資訊的 IAuditingHelper,還有統計介面執行時常的 Stopwatch

整個審計日誌攔截器的大體流程如下:

  1. 首先是判定 MVC 審計日誌過濾器是否進行處理。
  2. 再次根據特性,和型別進行二次驗證是否應該建立審計日誌資訊。
  3. 根據呼叫資訊,建立 AuditLogInfoAuditLogActionInfo 審計日誌資訊。
  4. 呼叫 StopWatch 的計時方法,如果出現了異常則將異常資訊新增到剛才構建的 AuditLogInfo 物件中。
  5. 無論是否出現異常,都會進入 finally 語句塊,這個時候會呼叫 StopWatch 例項的停止方法,並統計完成執行時間。
public override async Task InterceptAsync(IAbpMethodInvocation invocation)
{
    if (!ShouldIntercept(invocation, out var auditLog, out var auditLogAction))
    {
        await invocation.ProceedAsync();
        return;
    }

    // 開始進行計時操作。
    var stopwatch = Stopwatch.StartNew();

    try
    {
        await invocation.ProceedAsync();
    }
    catch (Exception ex)
    {
        // 如果出現了異常,一樣的將異常資訊新增到審計日誌結果中。
        auditLog.Exceptions.Add(ex);
        throw;
    }
    finally
    {
        // 統計完成,並將資訊加入到審計日誌結果中。
        stopwatch.Stop();
        auditLogAction.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
        auditLog.Actions.Add(auditLogAction);
    }
}

可以看到,只有當 ShouldIntercept() 方法返回 true 的時候,下面的統計等操作才會被執行。

protected virtual bool ShouldIntercept(
    IAbpMethodInvocation invocation, 
    out AuditLogInfo auditLog, 
    out AuditLogActionInfo auditLogAction)
{
    auditLog = null;
    auditLogAction = null;

    if (AbpCrossCuttingConcerns.IsApplied(invocation.TargetObject, AbpCrossCuttingConcerns.Auditing))
    {
        return false;
    }

    // 如果沒有獲取到 Scop,則返回 false。
    var auditLogScope = _auditingManager.Current;
    if (auditLogScope == null)
    {
        return false;
    }

    // 進行二次判斷是否需要儲存審計日誌。
    if (!_auditingHelper.ShouldSaveAudit(invocation.Method))
    {
        return false;
    }

    // 構建審計日誌資訊。
    auditLog = auditLogScope.Log;
    auditLogAction = _auditingHelper.CreateAuditLogAction(
        auditLog,
        invocation.TargetObject.GetType(),
        invocation.Method, 
        invocation.Arguments
    );

    return true;
}

2.2 審計日誌的持久化

大體流程和我們上面說的一樣,不過好像缺少了重要的一步,那就是 持久化操作。你可以在 Volo.Abp.Auditing 模組發現有 IAuditingStore 介面的定義,但是它的 SaveAsync() 方法卻沒有在攔截器內部被呼叫。同樣在 MVC 的審計日誌過濾器實現,你也會發現沒有呼叫持久化方法。

那麼我們的審計日誌是在什麼時候被持久化的呢?找到 SaveAsync() 被呼叫的地方,發現 ABP vNext 實現了一個審計日誌的 ASP.NET Core 中介軟體。

在這個中介軟體內部的實現比較簡單,首先通過一個判定方法,決定是否為本次請求執行 IAuditingManager.BeginScope() 方法。如果判定通過,則執行,否則不僅行任何操作。

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
    if (!ShouldWriteAuditLog(context))
    {
        await next(context);
        return;
    }

    using (var scope = _auditingManager.BeginScope())
    {
        try
        {
            await next(context);
        }
        finally
        {
            await scope.SaveAsync();
        }
    }
}

可以看到,在這裡 ABP vNext 使用 IAuditingManager 構建,呼叫其 BeginScope() 構建了一個 IAuditLogSaveHandle 物件,並使用其提供的 SaveAsync() 方法進行持久化操作。

2.2.1 巢狀的持久化操作

在構造出來的 IAuditLogSaveHandle 物件裡面,還是使用的 IAuditingManager 的預設實現 AuditingManager 所提供的 SaveAsync() 方法進行持久化。

閱讀原始碼之後,發現了下面兩個問題:

  1. IAuditingManager 沒有將持久化方法公開 出來,而是作為一個 protected 級別的方法。
  2. 為什麼還要藉助 IAuditLogSaveHandle 間接地呼叫 管理器的持久化方法。

這就要從中介軟體的程式碼說起了,可以看到它是構造出了一個可以被釋放的 IAuditLogSaveHandle 物件。ABP vNext 這樣做的目的,就是可以巢狀多個 Scope,即 只在某個範圍內 才將審計日誌記錄下來。這種特性類似於 工作單元 的用法,其底層實現是 之前文章 講過的 IAmbientScopeProvider 物件。

例如在某個應用服務內部,我可以這樣寫程式碼:

using (var scope = _auditingManager.BeginScope())
{
    await myAuditedObject1.DoItAsync(new InputObject { Value1 = "我是內部巢狀測試方法1。", Value2 = 5000 });
    using (var scope2 = _auditingManager.BeginScope())
    {
        await myAuditedObject1.DoItAsync(new InputObject {Value1 = "我是內部巢狀測試方法2。", Value2 = 10000});
        await scope2.SaveAsync();
    }
    await scope.SaveAsync();
}

想一下之前的程式碼,在攔截器內部,我們是通過 IAuditingManager.Current 拿到當前可用的 IAuditLogScope ,而這個 Scope 就是在呼叫 IAuditingManager.BeginScope() 之後生成的。

2.2.3 最終的持久化程式碼

通過上述的流程,我們得知最後的審計日誌資訊會通過 IAuditingStore 進行持久化。ABP vNext 為我們提供了一個預設的 SimpleLogAuditingStore 實現,其內部就是呼叫 ILogger 將資訊輸出。如果需要將審計日誌持久化到資料庫,你可以實現 IAUditingStore 介面,覆蓋原有實現 ,或者使用 ABP vNext 提供的 Volo.Abp.AuditLogging 模組。

2.3 審計日誌的序列化

審計日誌的序列化處理是在 IAuditingHelper 的預設實現內部被使用,可以看到構建審計日誌的方法內部,通過自定義的序列化器來將 Action 的引數進行序列化處理,方便儲存。

public virtual AuditLogActionInfo CreateAuditLogAction(
    AuditLogInfo auditLog,
    Type type, 
    MethodInfo method, 
    IDictionary<string, object> arguments)
{
    var actionInfo = new AuditLogActionInfo
    {
        ServiceName = type != null
            ? type.FullName
            : "",
        MethodName = method.Name,
        // 序列化引數資訊。
        Parameters = SerializeConvertArguments(arguments),
        ExecutionTime = Clock.Now
    };

    //TODO Execute contributors

    return actionInfo;
}

protected virtual string SerializeConvertArguments(IDictionary<string, object> arguments)
{
    try
    {
        if (arguments.IsNullOrEmpty())
        {
            return "{}";
        }

        var dictionary = new Dictionary<string, object>();

        foreach (var argument in arguments)
        {
            // 忽略的程式碼,主要作用是構建引數字典。
        }

        // 呼叫序列化器,序列化 Action 的呼叫引數。
        return AuditSerializer.Serialize(dictionary);
    }
    catch (Exception ex)
    {
        Logger.LogException(ex, LogLevel.Warning);
        return "{}";
    }
}

下面就是具體序列化器的程式碼:

public class JsonNetAuditSerializer : IAuditSerializer, ITransientDependency
{
    protected AbpAuditingOptions Options;

    public JsonNetAuditSerializer(IOptions<AbpAuditingOptions> options)
    {
        Options = options.Value;
    }

    public string Serialize(object obj)
    {
        // 使用 JSON.NET 進行序列化操作。
        return JsonConvert.SerializeObject(obj, GetSharedJsonSerializerSettings());
    }

    // ... 省略的程式碼。
}

2.4 審計日誌的配置引數

針對審計日誌相關的配置引數的定義,都存放在 AbpAuditingOptions 當中。下面我會針對各個引數的用途,對其進行詳細的說明。

public class AbpAuditingOptions
{
    //TODO: Consider to add an option to disable auditing for application service methods?

    // 該引數目前版本暫未使用,為保留引數。
    public bool HideErrors { get; set; }

    // 是否啟用審計日誌功能,預設值為 true。
    public bool IsEnabled { get; set; }

    // 審計日誌的應用程式名稱,預設值為 null,主要在構建 AuditingInfo 被使用。
    public string ApplicationName { get; set; }

    // 是否為匿名請求記錄審計日誌預設值 true。
    public bool IsEnabledForAnonymousUsers { get; set; }

    // 審計日誌功能的協作者集合,預設添加了 AspNetCoreAuditLogContributor 實現。
    public List<AuditLogContributor> Contributors { get; }

    // 預設的忽略型別,主要在序列化時使用。
    public List<Type> IgnoredTypes { get; }

    // 實體型別選擇器。
    public IEntityHistorySelectorList EntityHistorySelectors { get; }

    //TODO: Move this to asp.net core layer or convert it to a more dynamic strategy?
    // 是否為 Get 請求記錄審計日誌,預設值 false。
    public bool IsEnabledForGetRequests { get; set; }

    public AbpAuditingOptions()
    {
        IsEnabled = true;
        IsEnabledForAnonymousUsers = true;
        HideErrors = true;

        Contributors = new List<AuditLogContributor>();

        IgnoredTypes = new List<Type>
        {
            typeof(Stream),
            typeof(Expression)
        };

        EntityHistorySelectors = new EntityHistorySelectorList();
    }
}

2.4 實體相關的審計資訊

在文章開始就談到,除了對 HTTP 請求有審計日誌記錄以外,ABP vNext 還提供了實體審計資訊的記錄功能。所謂的實體的審計資訊,指的就是實體繼承了 ABP vNext 提供的介面之後,ABP vNext 會自動維護實現的介面欄位,不需要開發人員自己再進行處理。

這些介面包括建立實體操作的相關資訊 IHasCreationTimeIMayHaveCreatorICreationAuditedObject 以及刪除實體時,需要記錄的相關資訊介面 IHasDeletionTimeIDeletionAuditedObject 等。除了審計日誌模組定義的型別以外,在 Volo.Abp.Ddd.Domain 模組的 Auditing 裡面也有很多審計實體的預設實現。

我在這裡就不再一一列舉,下面僅快速講解一下 ABP vNext 是如何通過這些介面,實現對審計欄位的自動維護的。

在審計日誌模組的內部,我們看到一個介面名字叫做 IAuditPropertySetter,它提供了三個方法,分別是:

public interface IAuditPropertySetter
{
    void SetCreationProperties(object targetObject);

    void SetModificationProperties(object targetObject);

    void SetDeletionProperties(object targetObject);
}

所以,這幾個方法就是用於設定建立資訊、修改資訊、刪除資訊的。現在跳轉到預設實現 AuditPropertySetter,隨便找一個 SetCreationTime() 方法。該方法內部首先是判斷傳入的 object 是否實現了 IHasCreationTime 介面,如果實現了對其進行強制型別轉換,然後賦值即可。

private void SetCreationTime(object targetObject)
{
    if (!(targetObject is IHasCreationTime objectWithCreationTime))
    {
        return;
    }

    if (objectWithCreationTime.CreationTime == default)
    {
        objectWithCreationTime.CreationTime = Clock.Now;
    }
}

其他幾個 Set 方法大同小異,那我們看一下有哪些地方使用到了上述三個方法。

可以看到使用者就包含有 EF Core 模組和 MongoDB 模組,這裡我以 EF Core 模組為例,猜測應該是傳入了實體物件過來。

果不其然...檢視這個方法的呼叫鏈,發現是 DbContext 每次進行 SaveChanges/SaveChangesAsync 的時候,就會對實體進行審計欄位自動賦值操作。

三、總結

審計日誌是 ABP vNext 為我們提供的一個可選元件,當開啟審計日誌功能後,我們可以根據審計日誌資訊快速定位問題。但審計日誌的開啟,也會較大的影響效能,因為每次請求都會建立審計日誌資訊,之後再進行持久化。因此在使用審計日誌功能時,可以結合 DisableAuditingAttribute 特性和 IAuditingManager.BeginScope(),按需開啟審計日誌功能。

四、點選我跳轉到文章目