【.NET】WebApiThrottle限流框架(13)——限流的请求日志
·
如果你想记录限流后的请求日志,可以实现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)
});
更多推荐
所有评论(0)