Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Producer and Consumer Trace Class #238

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ dist: trusty
mono:
- latest
dotnet: 2.0.0
os:
os:
- linux
script:
- ./build.sh
Expand Down
83 changes: 83 additions & 0 deletions Examples/async.spans/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Basic example showing how to record async spans between PRODUCER and CONSUMER applications

This document will show how to implement basic PRODUCER and CONSUMER spans using zipkin4net library.

## Implementation Overview

We have 3 applications to produce example PRODUCER and CONSUMER spans.

- `example.message.center` - Stores and pops messages. The messages contain trace information.
- `example.message.producer` - Creates a message with trace information and stores it to `example.message.center`. Logs PRODUCER span to zipkin server.
- `example.message.consumer` - Fetches the message from `example.message.center`. Logs CONSUMER span to zipkin server.

## Pre-requisites

- To build the example, you need to install at least [dotnet 2.2](https://dotnet.microsoft.com/download/dotnet-core/2.2)
- To run the examples, you need a live zipkin server.

## Running the example

1. Run `example.message.center` app
- On a command line, navigate to `Examples\async.spans\example.message.center`
- Run `dotnet run`
![example.message.center](images/run-example.message.center.PNG)

2. Run `example.message.producer` app
- On a command line, navigate to `Examples\async.spans\example.message.producer`
- Run `dotnet run <base url of live zipkin server>`
![example.message.producer](images/run-example.message.producer.PNG)

3. Run `example.message.consumer` app
- On a command line, navigate to `Examples\async.spans\example.message.consumer`
- Run `dotnet run <base url of live zipkin server>`
![example.message.consumer](images/run-example.message.consumer.PNG)

4. Check the output
- Go to zipkin UI
- Search for `message.producer` or `message.consumer` as serviceName
- Click one of the search result, it should show the PRODUCER and CONSUMER spans
![example-output](images/run-example-output.PNG)

## What to take note on how to create/use PRODUCER and CONSUMER spans

### PRODUCER spans

- To make a PRODUCER span, you need to use `ProducerTrace` class
- Example code from [example.message.producer](example.message.producer/Program.cs)
```csharp
using (var messageProducerTrace = new ProducerTrace("<Application name>", "<RPC here>"))
{
// TracedActionAsync extension method logs error annotation if exception occurs
await messageProducerTrace.TracedActionAsync(ProduceMessage(messageProducerTrace.Trace.CurrentSpan, text));
messageProducerTrace.AddAnnotation(Annotations.Tag("sampleProducerTag", "success!"));
}
```
- `TracedActionAsync` is used to run the process that is measured to log error annotation in your zipkin trace if exception is thrown.
- Make a way that trace information is passed to the consumer. So in the example, the trace information is part of the message which will be parsed by the consumer application to create CONSUMER spans.
- Also, custom annotations can be added using the ProducerTrace object method `AddAnnotation`.

### CONSUMER spans

- To make a CONSUMER span, you need to use `ConsumerTrace` class
- Example code from [example.message.consumer](example.message.consumer/Program.cs)
```csharp
static async Task ProcessMessage(Message message)
{
// need to supply trace information from producer
using (var messageConsumerTrace = new ConsumerTrace(
serviceName: "<Application name>",
rpc: "<RPC here>",
encodedTraceId: message.TraceId,
encodedSpanId: message.SpanId,
encodedParentSpanId: message.ParentId,
sampledStr: message.Sampled,
flagsStr: message.Flags.ToString(CultureInfo.InvariantCulture)))
{
await messageConsumerTrace.TracedActionAsync(Task.Delay(600)); // Test delay for mock processing
messageConsumerTrace.AddAnnotation(Annotations.Tag("sampleConsumerTag", "success!"));
}
}
```
- In the example PRODUCER application passed the trace information through the `message` object. Using the trace information, CONSUMER span is created.
- `TracedActionAsync` is used to run the process that is measured to log error annotation in your zipkin trace if exception is thrown.
- Also, custom annotations can be added using the ConsumerTrace object method `AddAnnotation`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using System.Collections.Generic;
using System.Linq;
using example.message.common;
using Microsoft.AspNetCore.Mvc;

namespace example.message.center.Controllers
{
[ApiController]
[Route("[controller]")]
public class MessagesController : ControllerBase
{
private static readonly Stack<Message> Messages = new Stack<Message>();

[HttpPost]
[Route("pop")]
public Message GetOneMessage()
{
if (!Messages.Any())
return null;

return Messages.Pop();
}

[HttpPost]
[Route("push")]
public string SaveMessage([FromBody]Message message)
{
Messages.Push(message);

return "Ok";
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Mvc;

namespace example.message.center.Controllers
{
[ApiController]
[Route("[controller]")]
public class WelcomeController : ControllerBase
{
[HttpGet]
public string Welcome()
{
return "Welcome to Message center!";
}
}
}
17 changes: 17 additions & 0 deletions Examples/async.spans/example.message.center/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace example.message.center
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:51589",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "welcome",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"example.message.center": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "welcome",
"applicationUrl": "http://localhost:51589",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
46 changes: 46 additions & 0 deletions Examples/async.spans/example.message.center/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Serialization;

namespace example.message.center
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddJsonOptions(options => {
// send back a ISO date
var settings = options.SerializerSettings;
settings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
// dont mess with case of properties
var resolver = options.SerializerSettings.ContractResolver as DefaultContractResolver;
resolver.NamingStrategy = null;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseMvc();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
8 changes: 8 additions & 0 deletions Examples/async.spans/example.message.center/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.4" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\example.message.common\example.message.common.csproj" />
</ItemGroup>

</Project>
26 changes: 26 additions & 0 deletions Examples/async.spans/example.message.common/Message.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Runtime.Serialization;

namespace example.message.common
{
[DataContract(Name = "message")]
public class Message
{
[DataMember(Name = "text")]
public string Text { get; set; }

[DataMember(Name = "trace_id")]
public string TraceId { get; set; }

[DataMember(Name = "parent_id")]
public string ParentId { get; set; }

[DataMember(Name = "span_id")]
public string SpanId { get; set; }

[DataMember(Name = "sampled")]
public string Sampled { get; set; }

[DataMember(Name = "flags")]
public long Flags { get; set; }
}
}
23 changes: 23 additions & 0 deletions Examples/async.spans/example.message.common/ZipkinConsoleLogger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using zipkin4net;

namespace example.message.common
{
public class ZipkinConsoleLogger : ILogger
{
public void LogError(string message)
{
Console.WriteLine(message);
}

public void LogInformation(string message)
{
Console.WriteLine(message);
}

public void LogWarning(string message)
{
Console.WriteLine(message);
}
}
}
23 changes: 23 additions & 0 deletions Examples/async.spans/example.message.common/ZipkinHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using zipkin4net;
using zipkin4net.Tracers.Zipkin;
using zipkin4net.Transport.Http;

namespace example.message.common
{
public static class ZipkinHelper
{
public static void StartZipkin(string zipkinServer)
{
TraceManager.SamplingRate = 1.0f;
var httpSender = new HttpZipkinSender(zipkinServer, "application/json");
var tracer = new ZipkinTracer(httpSender, new JSONSpanSerializer());
TraceManager.RegisterTracer(tracer);
TraceManager.Start(new ZipkinConsoleLogger());
}

public static void StopZipkin()
{
TraceManager.Stop();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\Src\zipkin4net\Src\zipkin4net.csproj" />
</ItemGroup>

</Project>
Loading