Skip to content

Commit

Permalink
Updating samples to showcase opentracing
Browse files Browse the repository at this point in the history
  • Loading branch information
borkke committed Jan 8, 2019
1 parent d5e715e commit e27b752
Show file tree
Hide file tree
Showing 84 changed files with 24,832 additions and 36 deletions.
29 changes: 25 additions & 4 deletions samples/Samples.Console/Program.cs
@@ -1,6 +1,11 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;
using OpenTracing;
using OpenTracing.Tag;
using OpenTracing.Util;
using Samples.Shared;

Expand All @@ -25,9 +30,25 @@ static void Main(string[] args)
Color = "Red"
});

var doughnuts = doughnutCollection.Find(a => true).ToList();

doughnutCollection.FindOneAndDelete(a => a.Id == ObjectId.GenerateNewId());
using (var scope = tracer.BuildSpan("custom-span").StartActive(finishSpanOnDispose: true))
{
try
{
var doughnuts = doughnutCollection.Find(a => true).ToList();
doughnutCollection.FindOneAndDelete(a => a.Id == ObjectId.GenerateNewId());
throw new Exception("Some exception");
}
catch (Exception e)
{
scope.Span.SetTag(Tags.Error, true);
scope.Span.Log(new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("message", e.Message),
new KeyValuePair<string, object>("stack.trace", e.StackTrace),
new KeyValuePair<string, object>("source", e.Source)
});
}
}

System.Console.ReadKey();
}
Expand Down
@@ -1,35 +1,36 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using OpenTracing;
using OpenTracing.Util;
using Samples.RestApi.Services;
using Microsoft.Extensions.Logging;
using Samples.DoughnutApi.Services;
using Samples.Shared;

namespace Samples.RestApi.Controllers
namespace Samples.DoughnutApi.Controllers
{
[Route("api/doughnut")]
[ApiController]
public class DoughnutController : ControllerBase
{
private readonly ILogger<DoughnutController> _logger;
private readonly DoughnutService _doughnutService;
private readonly ITracer _tracer;

public DoughnutController()
public DoughnutController(ILogger<DoughnutController> logger)
{
_logger = logger;
_doughnutService = new DoughnutService();
_tracer = GlobalTracer.Instance;
}

[HttpGet]
public ActionResult<List<Doughnut>> Get()
{
_logger.LogInformation("Getting all doughnuts.");
var doughnuts = _doughnutService.Get();
return Ok(doughnuts);
}

[HttpGet("{id}")]
public ActionResult<Doughnut> GetById(string id)
{
_logger.LogInformation("Getting doughnut by {id}.", id);
var doughnuts = _doughnutService.GetById(id);
return Ok(doughnuts);
}
Expand Down
22 changes: 22 additions & 0 deletions samples/Samples.DoughnutApi/Program.cs
@@ -0,0 +1,22 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;

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

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConsole();
});
}
}
Expand Up @@ -19,12 +19,12 @@
},
"Samples.RestApi": {
"commandName": "Project",
"launchBrowser": true,
"launchBrowser": false,
"launchUrl": "api/values",
"applicationUrl": "http://localhost:5000",
"applicationUrl": "http://localhost:5001",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
}
@@ -1,10 +1,9 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Driver;
using Samples.Shared;

namespace Samples.RestApi.Services
namespace Samples.DoughnutApi.Services
{
public class DoughnutService
{
Expand Down Expand Up @@ -36,7 +35,8 @@ public void Update(Doughnut doughnut, string id)
Builders<Doughnut>.Filter.Eq("_id", new ObjectId(id)),
Builders<Doughnut>.Update
.Set(a => a.Color, doughnut.Color)
.Set(a => a.Price, doughnut.Price));
.Set(a => a.Price, doughnut.Price)
.Set(a => a.OwnerId, doughnut.OwnerId));
}

public void Delete(string id)
Expand Down
Expand Up @@ -4,11 +4,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenTracing;
using OpenTracing.Util;
using Samples.Shared;

namespace Samples.RestApi
namespace Samples.DoughnutApi
{
public class Startup
{
Expand All @@ -25,8 +24,7 @@ public void ConfigureServices(IServiceCollection services)
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

var loggerFactory = new LoggerFactory().AddConsole();
var logger = loggerFactory.CreateLogger<Program>();
var tracer = JaegerTracer.CreateTracer("rest-api", loggerFactory);
var tracer = JaegerTracer.CreateTracer("doughnuts-api", loggerFactory);
services.AddOpenTracing();
GlobalTracer.Register(tracer);
}
Expand Down
File renamed without changes.
1 change: 1 addition & 0 deletions samples/Samples.Shared/Doughnut.cs
Expand Up @@ -10,5 +10,6 @@ public class Doughnut
[BsonElement("color")]
public string Color { get; set; }
public int Price { get; set; }
public long OwnerId { get; set; }
}
}
2 changes: 1 addition & 1 deletion samples/Samples.Shared/Samples.Shared.csproj
Expand Up @@ -8,7 +8,7 @@
<PackageReference Include="Jaeger" Version="0.2.2" />
<PackageReference Include="MongoDB.Driver" Version="2.7.0" />
<PackageReference Include="OpenTracing" Version="0.12.0" />
<PackageReference Include="OpenTracing.Contrib.Mongo" Version="0.1.0-beta.4" />
<PackageReference Include="OpenTracing.Contrib.Mongo" Version="0.2.1" />
</ItemGroup>

</Project>
61 changes: 61 additions & 0 deletions samples/Samples.UsersApi/Controllers/UserController.cs
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Samples.UsersApi.Database;

namespace Samples.UsersApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly UserContext _db;
private readonly ILogger<UserController> _logger;

public UserController(UserContext db, ILogger<UserController> logger)
{
_db = db;
_logger = logger;
}

[HttpGet]
public ActionResult<List<User>> GetAll()
{
var allUsers = _db.Users.ToList();
return Ok(allUsers);
}

[HttpGet("{id}")]
public ActionResult<User> GetById(int id)
{
_logger.LogDebug("Getting user by {id}", id);

Thread.Sleep(TimeSpan.FromSeconds(1));

var user = _db.Users.FirstOrDefault(a => a.Id == id);

return Ok(user);
}

[HttpPost]
public ActionResult<User> Create(User user)
{
try
{
_logger.LogInformation("Creating user {first_name}", user.FirstName);

_db.Users.Add(user);
_db.SaveChanges();
return Ok(user);
}
catch (Exception e)
{
_logger.LogError(e, "Failed to create user with {first_name}", user.FirstName);
return BadRequest("Failed to create user");
}
}
}
}
22 changes: 22 additions & 0 deletions samples/Samples.UsersApi/Database/UserContext.cs
@@ -0,0 +1,22 @@
using System;
using Microsoft.EntityFrameworkCore;

namespace Samples.UsersApi.Database
{
public class UserContext : DbContext
{
public UserContext(DbContextOptions<UserContext> options)
: base(options)
{
}

public DbSet<User> Users { get; set; }
}

public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

@@ -0,0 +1,30 @@
using Microsoft.EntityFrameworkCore.Migrations;

namespace Samples.UsersApi.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
FirstName = table.Column<string>(nullable: true),
LastName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Users");
}
}
}
34 changes: 34 additions & 0 deletions samples/Samples.UsersApi/Migrations/UserContextModelSnapshot.cs
@@ -0,0 +1,34 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Samples.UsersApi.Database;

namespace Samples.UsersApi.Migrations
{
[DbContext(typeof(UserContext))]
partial class UserContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.4-rtm-31024");

modelBuilder.Entity("Samples.UsersApi.Database.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("FirstName");
b.Property<string>("LastName");
b.HasKey("Id");
b.ToTable("Users");
});
#pragma warning restore 612, 618
}
}
}
Expand Up @@ -7,9 +7,8 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Samples.Shared;

namespace Samples.RestApi
namespace Samples.UsersApi
{
public class Program
{
Expand All @@ -20,10 +19,6 @@ public static void Main(string[] args)

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConsole();
});
.UseStartup<Startup>();
}
}

0 comments on commit e27b752

Please sign in to comment.