Commit 6389849b by huangzhihong

扩展

parent 03525d7b

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.136
# Visual Studio Version 16
VisualStudioVersion = 16.0.29911.84
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{07C552B5-C967-4525-8819-D0EDAEC102C8}"
EndProject
......@@ -19,6 +19,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Bailun.ServiceFabric.Trace.
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleApi.Downstream", "samples\SimpleApi.Downstream\SimpleApi.Downstream.csproj", "{30463913-0CCF-41D3-A31B-14F90A87CD88}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "abp", "abp", "{126164A9-F53A-4624-A6A8-EFEEC5A2754E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -99,6 +101,7 @@ Global
{5E99AC45-94C4-4CC6-A05C-CA503372CFBE} = {FD9374AC-E69B-454E-8B69-9F8FCD474C0E}
{EC66F103-DF1E-455F-A710-AFE102585382} = {74B6D8C3-1975-4853-A9CB-7236D9157BAB}
{30463913-0CCF-41D3-A31B-14F90A87CD88} = {FD9374AC-E69B-454E-8B69-9F8FCD474C0E}
{126164A9-F53A-4624-A6A8-EFEEC5A2754E} = {FD9374AC-E69B-454E-8B69-9F8FCD474C0E}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {94C0DA2C-CCCB-4314-93A2-9809B5DD0583}
......
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Bailun.ServiceFabric.Trace;
using Microsoft.Extensions.DependencyInjection;
namespace SimpleApi.Downstream
{
......@@ -23,7 +13,6 @@ namespace SimpleApi.Downstream
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureServices(services=> services.AddSkyApmAspnetCoreDiagnostic())
.UseSerilog(false, true);
.UseBailunTrace(true, true);
}
}
......@@ -11,7 +11,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="SkyAPM.Agent.AspNetCore" Version="0.9.0" />
</ItemGroup>
<ItemGroup>
......
......@@ -34,7 +34,7 @@ namespace SimpleApi.Downstream
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSerilogTraceLogging();
app.UseBailunRequestLogging();
app.UseMvc();
}
}
......
......@@ -23,12 +23,14 @@ namespace SimpleApi.Controllers
[HttpGet]
public IEnumerable<string> Get([FromServices] IUserApi userApi)
{
_logger.LogInformation("Microsoft Logger ....");
_logger.SetModule("MicroLogger").LogInformation("Mircrosoft Logger ....");
Log.Logger.SetModule("Test").Information("{BusinessId} ......");
Log.Logger.SetModule("Test2").SetBussinessId("b1").Information("{BusinessId} ......");
Log.Logger.SetModule("Test2").Information("{BusinessId} ......");
Log.Logger.SetModule("Test3").SetBussinessId("b2").Information("{BusinessId} ......");
//_logger.LogInformation("Microsoft Logger ....");
//_logger.SetModule("MicroLogger").LogInformation("Mircrosoft Logger ....");
//Log.Logger.SetModule("Test").Information("{BusinessId} ......");
//Log.Logger.SetModule("Test2").SetBussinessId("b1").Information("{BusinessId} ......");
//Log.Logger.SetModule("Test2").Information("{BusinessId} ......");
Log.Logger.SetModule("Test3").SetBussinessId("b2").Information("【api1】...{BusinessId} ......");
return userApi.GetAsync("dafadfdsfafd").InvokeAsync().GetAwaiter().GetResult();
}
......
......@@ -12,13 +12,11 @@ namespace SampleApi.MicroServices
public interface IUserApi : IHttpApi
{
[HttpGet("api/values")]
[TraceIntercept]
ITask<IEnumerable<string>> GetAsync(string account);
[HttpPost("api/values")]
[TraceIntercept]
ITask<string> PostAsync([FormContent] string v1, [FormContent] string v2);
}
}
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Serilog;
using Bailun.ServiceFabric.Trace;
using System.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
namespace SimpleApi
{
......@@ -18,7 +15,6 @@ namespace SimpleApi
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureServices(services => services.AddSkyApmAspnetCoreDiagnostic())
.UseSerilog(false, true);
.UseBailunTrace(true, true);
}
}
......@@ -11,7 +11,6 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="SkyAPM.Agent.AspNetCore" Version="0.9.0" />
</ItemGroup>
<ItemGroup>
......
......@@ -29,11 +29,10 @@ namespace SimpleApi
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddHttpApi<IUserApi>(opt =>
{
opt.HttpHost = new Uri("http://localhost:5001/");
}).ConfigureTraceHttpClient();
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
......@@ -41,7 +40,7 @@ namespace SimpleApi
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSerilogTraceLogging();
app.UseBailunRequestLogging();
app.UseMvc();
}
......
......@@ -9,13 +9,11 @@ namespace SimpleConsole.MicroServices
public interface IUserApi : IHttpApi
{
[HttpGet("api/values")]
//[TraceIntercept]
ITask<IEnumerable<string>> GetAsync(string account);
[HttpPost("api/values")]
//[TraceIntercept]
ITask<string> PostAsync([FormContent] string v1, [FormContent] string v2);
}
}
......@@ -47,7 +47,6 @@ namespace SimpleConsole
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
})
.AddSkyAPM()
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
......@@ -55,10 +54,8 @@ namespace SimpleConsole
{
opt.HttpHost = new Uri("http://localhost:5000/");
});
services.Replace(ServiceDescriptor.Singleton<ITracingDiagnosticProcessor, HttpClientTracingDiagnosticProcessor>());
})
.UseSerilog(false, true)
.UseBailunTrace(true, true)
.Build();
}
......
......@@ -9,7 +9,6 @@
<PackageReference Include="Microsoft.Extensions.Configuration.CommandLine" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="2.1.1" />
<PackageReference Include="SkyAPM.Agent.GeneralHost" Version="0.9.0" />
</ItemGroup>
<ItemGroup>
......
......@@ -23,11 +23,11 @@ namespace SimpleConsole
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Delay(3000);
await Task.Delay(3000); //延迟确保skywalking agent 已初始化成功
var index = 1;
while (!stoppingToken.IsCancellationRequested && index < 5)
{
var context = _tracingContext.CreateEntrySegmentContext(nameof(ExecuteAsync), new TextCarrierHeaderCollection(new Dictionary<string, string>()));
var context = _tracingContext.CreateEntrySegmentContext(nameof(Worker), new TextCarrierHeaderCollection(new Dictionary<string, string>()));
Log.Logger.SetTraceId(context.TraceId.ToString());
......@@ -35,12 +35,16 @@ namespace SimpleConsole
//todo ҵ߼
//**************************TODO:业务逻辑**************************
await _userApi.GetAsync(index.ToString());
Log.Logger.Information($"{index}ε............... ");
index++;
Log.Logger.Information($"【console】...第{index}次调用............... ");
//**************************TODO:业务逻辑**************************
index++;
context.Span.AddLog(LogEvent.Message($"Worker running at: {DateTime.Now}"));
_tracingContext.Release(context);
......
......@@ -15,7 +15,8 @@
<PackageReference Include="Microsoft.Extensions.Http" Version="2.1.1" />
<PackageReference Include="Serilog" Version="2.9.0" />
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<PackageReference Include="SkyAPM.Utilities.DependencyInjection" Version="0.9.0" />
<PackageReference Include="SkyAPM.Agent.AspNetCore" Version="0.9.0" />
<PackageReference Include="SkyAPM.Agent.GeneralHost" Version="0.9.0" />
<!--<PackageReference Include="SkyAPM.Utilities.DependencyInjection" Version="0.9.0" />-->
<PackageReference Include="WebApiClient.JIT" Version="1.1.3" />
</ItemGroup>
......
/*
* Licensed to the SkyAPM under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The SkyAPM licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Newtonsoft.Json;
using SkyApm;
using SkyApm.Common;
using SkyApm.Diagnostics;
using SkyApm.Diagnostics.AspNetCore;
using SkyApm.Tracing;
using SkyApm.Tracing.Segments;
using System;
using System.IO;
using System.Text;
namespace SkyApm.AspNetCore.Diagnostics
namespace Bailun.Diagnostics.AspNetCore
{
public class HostingTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{
......
/*
* Licensed to the SkyAPM under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The SkyAPM licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace SkyApm.AspNetCore.Diagnostics
namespace Bailun.Diagnostics.AspNetCore
{
internal static class HttpContextDiagnosticStrings
{
......
/*
* Licensed to the SkyAPM under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The SkyAPM licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using SkyApm.Tracing;
namespace SkyApm.AspNetCore.Diagnostics
namespace Bailun.Diagnostics.AspNetCore
{
public class HttpRequestCarrierHeaderCollection : ICarrierHeaderCollection
{
......@@ -42,7 +24,7 @@ namespace SkyApm.AspNetCore.Diagnostics
{
return _headers.GetEnumerator();
}
public void Add(string key, string value)
{
throw new System.NotImplementedException();
......
/*
* Licensed to the SkyAPM under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The SkyAPM licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using Microsoft.Extensions.DependencyInjection;
using SkyApm;
using SkyApm.Utilities.DependencyInjection;
namespace SkyApm.AspNetCore.Diagnostics
namespace Bailun.Diagnostics.AspNetCore
{
public static class SkyWalkingBuilderExtensions
{
public static SkyApmExtensions AddAspNetCoreHosting(this SkyApmExtensions extensions)
{
extensions.Services.AddSingleton<ITracingDiagnosticProcessor, HostingTracingDiagnosticProcessor>();
return extensions;
}
}
......
namespace SkyApm.Diagnostics.AspNetCore
namespace Bailun.Diagnostics.AspNetCore
{
internal static class TagsExtension
{
......
/*
* Licensed to the SkyAPM under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The SkyAPM licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json;
using SkyApm;
using SkyApm.Common;
using SkyApm.Diagnostics;
using SkyApm.Diagnostics.HttpClient;
using SkyApm.Tracing;
using SkyApm.Tracing.Segments;
namespace SkyApm.Diagnostics.HttpClient
{
public class HttpClientTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{
public string ListenerName { get; } = "HttpHandlerDiagnosticListener";
//private readonly IContextCarrierFactory _contextCarrierFactory;
private readonly ITracingContext _tracingContext;
private readonly IExitSegmentContextAccessor _contextAccessor;
private SegmentContext _segmentContext;
public HttpClientTracingDiagnosticProcessor(ITracingContext tracingContext,
IExitSegmentContextAccessor contextAccessor)
{
_tracingContext = tracingContext;
_contextAccessor = contextAccessor;
}
[DiagnosticName("System.Net.Http.Request")]
public void HttpRequest([Property(Name = "Request")] HttpRequestMessage request)
{
_segmentContext = _tracingContext.CreateExitSegmentContext(request.RequestUri.ToString(),
$"{request.RequestUri.Host}:{request.RequestUri.Port}",
new HttpClientICarrierHeaderCollection(request));
var context = _segmentContext;
if (request.Content != null)
{
var requestStr = request.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
context.Span.AddTag(TagsExtension.REQUEST, requestStr);
}
context.Span.SpanLayer = SpanLayer.HTTP;
context.Span.Component = Components.HTTPCLIENT;
context.Span.AddTag(Tags.URL, request.RequestUri.ToString());
context.Span.AddTag(Tags.HTTP_METHOD, request.Method.ToString());
context.Span.AddTag(TagsExtension.HEADERS, JsonConvert.SerializeObject(request.Headers));
}
[DiagnosticName("System.Net.Http.Response")]
public void HttpResponse([Property(Name = "Response")] HttpResponseMessage response)
{
var context = _segmentContext;
if (context == null)
{
return;
}
if (response != null)
{
var statusCode = (int)response.StatusCode;
if (statusCode >= 400)
{
context.Span.ErrorOccurred();
}
if (response.Content != null)
{
var responseStr = response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
context.Span.AddTag(TagsExtension.RESPONSE, responseStr);
}
context.Span.AddTag(Tags.STATUS_CODE, statusCode);
}
_tracingContext.Release(context);
}
[DiagnosticName("System.Net.Http.Exception")]
public void HttpException([Property(Name = "Request")] HttpRequestMessage request,
[Property(Name = "Exception")] Exception exception)
{
_segmentContext?.Span?.ErrorOccurred(exception);
}
}
}
using System;
using System.Net.Http;
namespace Bailun.Diagnostics.HttpClient
{
......
/*
* Licensed to the SkyAPM under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The SkyAPM licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using SkyApm.Tracing;
namespace SkyApm.Diagnostics.HttpClient
namespace Bailun.Diagnostics.HttpClient
{
public class HttpClientICarrierHeaderCollection : ICarrierHeaderCollection
{
......
/*
* Licensed to the SkyAPM under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The SkyAPM licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System;
using Microsoft.Extensions.DependencyInjection;
using SkyApm;
using SkyApm.Utilities.DependencyInjection;
namespace SkyApm.Diagnostics.HttpClient
namespace Bailun.Diagnostics.HttpClient
{
public static class SkyWalkingBuilderExtensions
{
......
namespace SkyApm.Diagnostics.HttpClient
namespace Bailun.Diagnostics.HttpClient
{
internal static class TagsExtension
{
......
using Microsoft.AspNetCore.Hosting;
using Bailun.Diagnostics.HttpClient;
using Bailun.ServiceFabric.Trace;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Serilog;
using SkyApm;
using SkyApm.Agent.GeneralHost;
using System;
using Bailun.ServiceFabric.Trace;
using Microsoft.Extensions.Hosting;
namespace Serilog
namespace Microsoft.Extensions.Hosting
{
public static class GenericHostBuilderExtensions
{
......@@ -16,7 +20,7 @@ namespace Serilog
/// <param name="writeToConsole">是否写到控制台</param>
/// <param name="configureLogger">扩展配置</param>
/// <returns></returns>
public static IHostBuilder UseSerilog(this IHostBuilder builder, bool writeToExceptionless = false, bool writeToConsole = false, Action<LoggerConfiguration> configureLogger = null)
public static IHostBuilder UseBailunTrace(this IHostBuilder builder, bool writeToExceptionless = false, bool writeToConsole = false, Action<LoggerConfiguration> configureLogger = null)
{
Action<HostBuilderContext, LoggerConfiguration> configure = (hostingContext, loggerConfiguration) =>
......@@ -46,7 +50,13 @@ namespace Serilog
.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {TraceId:l} {Message:lj} {NewLine}{Exception}");
}
};
return builder.UseSerilog(configure);
return builder.UseSerilog(configure)
.AddSkyAPM()
.ConfigureServices((hostCtx, services) =>
{
services.Replace(ServiceDescriptor.Singleton<ITracingDiagnosticProcessor, HttpClientTracingDiagnosticProcessor>());
});
}
}
}
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration;
using System;
using Bailun.ServiceFabric.Trace;
using Serilog;
using Microsoft.Extensions.DependencyInjection;
using SkyApm;
using Bailun.Diagnostics.AspNetCore;
using Bailun.Diagnostics.HttpClient;
namespace Serilog
namespace Microsoft.AspNetCore.Hosting
{
public static class WebHostBuilderExtensions
{
......@@ -15,7 +19,7 @@ namespace Serilog
/// <param name="writeToConsole">是否写到控制台</param>
/// <param name="configureLogger">扩展配置</param>
/// <returns></returns>
public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, bool writeToExceptionless = false, bool writeToConsole = false, Action<LoggerConfiguration> configureLogger = null)
public static IWebHostBuilder UseBailunTrace(this IWebHostBuilder builder, bool writeToExceptionless = false, bool writeToConsole = false, Action<LoggerConfiguration> configureLogger = null)
{
Action<WebHostBuilderContext, LoggerConfiguration> configure = (hostingContext, loggerConfiguration) =>
......@@ -45,7 +49,12 @@ namespace Serilog
.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {TraceId:l} {Message:lj} {NewLine}{Exception}");
}
};
return builder.UseSerilog(configure);
return builder.UseSerilog(configure)
.ConfigureServices(services =>
{
services.AddSingleton<ITracingDiagnosticProcessor, HostingTracingDiagnosticProcessor>();
services.AddSingleton<ITracingDiagnosticProcessor, HttpClientTracingDiagnosticProcessor>();
});
}
}
}
using Bailun.ServiceFabric.Trace;
using Microsoft.AspNetCore.Http;
using SkyApm.Tracing;
namespace Microsoft.Extensions.DependencyInjection
{
public static class HttpClientBuilderExtensions
{
/// <summary>
/// HttpClient配置扩展TraceId
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static IHttpClientBuilder ConfigureTraceHttpClient(this IHttpClientBuilder builder)
{
return builder.ConfigureHttpClient((sp, httpclient) =>
{
var ctx = sp.GetService<IHttpContextAccessor>()?.HttpContext;
if (ctx != null)
{
if (ctx.Items.ContainsKey(Constants.TraceIdPropertyName))
{
httpclient.DefaultRequestHeaders.Add(
Constants.TraceIdPropertyName,
ctx.Items[Constants.TraceIdPropertyName].ToString());
}
}
});
}
}
}
......@@ -8,7 +8,7 @@ using System.IO;
using System.Text;
using Microsoft.AspNetCore.Http.Internal;
namespace Bailun.ServiceFabric.Trace
namespace Microsoft.AspNetCore.Builder
{
public static class ApplicationBuilderExtensions
{
......@@ -27,10 +27,10 @@ namespace Bailun.ServiceFabric.Trace
/// added by ASP.NET Core, and names of properties added to the <see cref="IDiagnosticContext"/>.
/// </param>
/// <returns>The application builder.</returns>
public static IApplicationBuilder UseSerilogTraceLogging(
public static IApplicationBuilder UseBailunRequestLogging(
this IApplicationBuilder app,
string messageTemplate)
=> app.UseSerilogTraceLogging(opts => opts.MessageTemplate = messageTemplate);
=> app.UseBailunRequestLogging(opts => opts.MessageTemplate = messageTemplate);
/// <summary>
/// Adds middleware for streamlined request logging. Instead of writing HTTP request information
......@@ -42,7 +42,7 @@ namespace Bailun.ServiceFabric.Trace
/// <param name="app">The application builder.</param>
/// <param name="configureOptions">A <see cref="System.Action{T}" /> to configure the provided <see cref="RequestLoggingOptions" />.</param>
/// <returns>The application builder.</returns>
public static IApplicationBuilder UseSerilogTraceLogging(
public static IApplicationBuilder UseBailunRequestLogging(
this IApplicationBuilder app,
Action<RequestLoggingOptions> configureOptions = null)
{
......@@ -64,25 +64,4 @@ namespace Bailun.ServiceFabric.Trace
.UseSerilogRequestLogging(configureOptions);
}
}
internal static class StringExtension
{
public static string GetBodyString(this HttpRequest request)
{
var body = "";
if (request.ContentLength == null || !(request.ContentLength > 0))
return body;
request.EnableBuffering();
request.Body.Seek(0, SeekOrigin.Begin);
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
request.Body.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false).GetAwaiter();
body = Encoding.UTF8.GetString(buffer);
request.Body.Seek(0, SeekOrigin.Begin);
return body;
}
}
}
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using SkyApm.Tracing;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace Bailun.ServiceFabric.Trace.Middlewares
{
......@@ -21,45 +19,22 @@ namespace Bailun.ServiceFabric.Trace.Middlewares
{
if (httpContext == null) throw new ArgumentNullException(nameof(httpContext));
var uid = string.Empty;
if (httpContext.Request.Headers.ContainsKey(Constants.TraceIdPropertyName))
{
uid = httpContext.Request.Headers[Constants.TraceIdPropertyName];
}
else
{
var entrySegmentContextAccessor = httpContext.RequestServices.GetService<IEntrySegmentContextAccessor>();
string uid;
if (entrySegmentContextAccessor?.Context != null)
{
uid = entrySegmentContextAccessor.Context.TraceId.ToString();
}
else
{
uid = Guid.NewGuid().ToString("N");
}
}
var entrySegmentContextAccessor = httpContext.RequestServices.GetService<IEntrySegmentContextAccessor>();
if (httpContext.Items.ContainsKey(Constants.TraceIdPropertyName))
if (entrySegmentContextAccessor?.Context != null)
{
httpContext.Items[Constants.TraceIdPropertyName] = uid;
uid = entrySegmentContextAccessor.Context.TraceId.ToString();
}
else
{
httpContext.Items.Add(Constants.TraceIdPropertyName, uid);
uid = Guid.NewGuid().ToString("N");
}
Serilog.Log.Logger.SetTraceId(uid);
await _next(httpContext);
////认证通过
//if (httpContext.User.Identity.IsAuthenticated && httpContext.User?.Claims != null && httpContext.User.Claims.Any())
//{
// Serilog.Log.Logger.SetIdentity(
// httpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value,
// httpContext.User.Identity.Name);
//}
}
}
}
using SkyApm.AspNetCore.Diagnostics;
using SkyApm.Diagnostics.HttpClient;
using SkyApm.Utilities.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddSkyApmAspnetCoreDiagnostic(this IServiceCollection services)
{
services.AddSkyApmExtensions()
.AddAspNetCoreHosting()
.AddHttpClient();
return services;
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment