Ingress-nginx工作原理和实践 (2)

① 定义 NLog Render

/// <summary> /// Represent a unique identifier to represent a request from the request HTTP header X-Request-Id. /// </summary> [LayoutRenderer("x_request_id")] public class XRequestIdLayoutRender : HttpContextLayoutRendererBase { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var identityName = HttpContextAccessor.HttpContext?.Request?.Headers?["X-Request-Id"].FirstOrDefault(); builder.Append(identityName); } } /// <summary> /// Represent a http context layout renderer to access the current http context. /// </summary> public abstract class HttpContextLayoutRendererBase : LayoutRenderer { private IHttpContextAccessor _httpContextAccessor; /// <summary> /// Gets the <see cref="IHttpContextAccessor"/>. /// </summary> protected IHttpContextAccessor HttpContextAccessor { get { return _httpContextAccessor ?? (_httpContextAccessor = ServiceLocator.ServiceProvider.GetService<IHttpContextAccessor>()); } } } internal sealed class ServiceLocator { public static IServiceProvider ServiceProvider { get; set; } }

② 从请求中获取 X-Request-Id 依赖 IHttpContextAccessor 组件
这里使用 依赖查找的方式获取该组件, 故请在 Startup ConfigureService 中生成服务

public void ConfigureServices(IServiceCollection services) { // ...... ServiceLocator.ServiceProvider = services.BuildServiceProvider(); }

③ 最后在 Program 中注册这个 NLog Render:

public static void Main(string[] args) { LayoutRenderer.Register<XRequestIdLayoutRender>("x_request_id"); CreateHostBuilder(args).Build().Run(); }

这样从 Ingress-Nginx 产生的request_id,将会流转到 Backend App, 并在日志分析中起到巨大作用,也便于划清运维/开发的故障责任。

总结

了解了Ingress在应用层工作,根据Host和Path暴露k8s服务

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyyygf.html