1. 程式人生 > >WebApiThrottle限流框架——限流的請求日誌

WebApiThrottle限流框架——限流的請求日誌

如果你想記錄限流後的請求日誌,可以實現IThrottleLogger介面,新增到ThrottlingHandler裡。

public interface IThrottleLogger
{
    void Log(ThrottleLogEntry entry);
}

實現ITraceWriter日誌記錄介面的例子

public class TracingThrottleLogger : IThrottleLogger
{
    private readonly ITraceWriter traceWriter;

    public TracingThrottleLogger(ITraceWriter traceWriter)
    {
        this.traceWriter = traceWriter;
    }

    public void Log(ThrottleLogEntry entry)
    {
        if (null != traceWriter)
        {
            traceWriter.Info(entry.Request, "WebApiThrottle",
                "{0} Request {1} from {2} has been throttled (blocked), quota {3}/{4} exceeded by {5}",
                entry.LogDate, entry.RequestId, entry.ClientIp, entry.RateLimit, entry.RateLimitPeriod, entry.TotalRequests);
        }
    }
}

用SystemDiagnosticsTraceWriter和ThrottlingHandler記錄日誌的使用例子:

var traceWriter = new SystemDiagnosticsTraceWriter()
{
    IsVerbose = true
};
config.Services.Replace(typeof(ITraceWriter), traceWriter);
config.EnableSystemDiagnosticsTracing();

config.MessageHandlers.Add(new ThrottlingHandler()
{
    Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30)
    {
        IpThrottling = true,
        ClientThrottling = true,
        EndpointThrottling = true
    },
    Repository = new CacheRepository(),
    Logger = new TracingThrottleLogger(traceWriter)
});