Steeltoe里的分布式追蹤功能與Spring Cloud Sleuth一樣,支持在日志中記錄追蹤數據,或者上傳到遠端的服務,比如Zipkin。
Logging
在Steeltoe中使用日志時需要引入其特有的日志包Steeltoe.Extensions.Logging.DynamicLogger
。
之后還需在應用程序啟動時加入日志提供器。
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().ConfigureLogging((builderContext, loggingBuilder) =>
{
loggingBuilder.AddConfiguration(builderContext.Configuration.GetSection("Logging"));
// Add Steeltoe Dynamic Logging provider
loggingBuilder.AddDynamicConsole();
});
接下來,引入追蹤包Steeltoe.Management.TracingCore
。
然后在Startup類中加入追蹤服務。
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedTracing(Configuration);
services.AddMvc();
}
最后在Action方法里添加日志錨點。
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly ILogger _logger;
public ValuesController(ILogger<ValuesController> logger)
{
_logger = logger;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
_logger.LogWarning("Hello log");
return new string[] { "value1", "value2" };
}
}
並在appsettings.json文件確認如下配置:
"Logging": {
"LogLevel": {
"Default": "Warning"
}
}
這樣啟動程序后,可以在輸出窗口內看到兩條日志,這是因為Steeltoe的日志提供器是對ASP.NET Core自身日志器的進一步封裝,其在原始數據基礎上增加了如Spring Cloud Sleuth中一樣的額外信息。
Exporting
如果想要把追蹤數據發送到Zipkin服務中,還需額外引入新的包Steeltoe.Management.ExporterCore
。
並在Startup類中增加新的服務。
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedTracing(Configuration);
services.AddZipkinExporter(Configuration);
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
app.UseTracingExporter();
}
appsettings.json文件里加上上文中Zipkin的服務地址。
"management": {
"tracing": {
"alwaysSample": true,
"egressIgnorePattern": "/api/v2/spans|/v2/apps/.*/permissions|/eureka/.*|/oauth/.*",
"exporter": {
"zipkin": {
"endpoint": "http://localhost:10000/api/v2/spans",
"validateCertificates": false
}
}
}
}
再次啟動程序,首先可以看到exportable字段的值已從false變為了true。
然后,再到Zipkin服務中查看,追蹤數據確實已經傳入到其中。