Пример #1
0
        public static void UseSerilogRequestContextLogging(this IApplicationBuilder app, Action <RequestContextOptions> options = default)
        {
            var requestOptions = new RequestContextOptions();

            options?.Invoke(requestOptions);

            var addRequestId = requestOptions.RequestId?.Enable ?? false;

            app.UseSerilogRequestLogging(options =>
            {
                // Customize the message template
                options.MessageTemplate = IncludeRequestId(addRequestId, LogMessageTemplate);

                // Emit debug-level events instead of the defaults
                options.GetLevel = (httpContext, elapsed, ex) => requestOptions.LogLevel;

                // Attach additional properties to the request completion event
                options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
                {
                    diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
                    diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
                    diagnosticContext.Set("RequestMethod", httpContext.Request.Method);
                    diagnosticContext.Set("RequestPath", httpContext.Request.Path);

                    if (addRequestId)
                    {
                        diagnosticContext.Set("RequestId", httpContext.Request.Headers.ContainsKey("RequestId") ? httpContext.Request.Headers?["RequestId"].ToString() : string.Empty);
                    }
                };
            });
        }
Пример #2
0
        /// <summary>
        /// Creates a <see cref="RequestContext"/> with the specified options. 
        /// Do not use this overload except for unit tests! Misuse of nested
        /// contexts can result in cache corruption!
        /// </summary>
        /// <param name="options"></param>
        /// <returns></returns>
        /// <remarks>Do not use this overload except for unit tests! Misuse of nested
        /// contexts can result in cache corruption!</remarks>
        public static RequestContext Create(RequestContextOptions options)
        {
            if (Current != null)
            {
                if (options != RequestContextOptions.AllowNestedContext)
                {
                    throw new NestedContextUnexpectedException();
                }
            }

            ContextChain.Push(new RequestContext());
            return Current;
        }