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

[cartservice] Support for Logs #1086

Merged
merged 4 commits into from
Sep 3, 2023
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: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ release.
([#1083](https://github.com/open-telemetry/opentelemetry-demo/pull/1083))
* Update Telemetry Components
([#1085](https://github.com/open-telemetry/opentelemetry-demo/pull/1085))
* [cartservice] Support for logs
([#1086](https://github.com/open-telemetry/opentelemetry-demo/pull/1086))

## 1.4.0

Expand Down
27 changes: 20 additions & 7 deletions src/cartservice/src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;

using Microsoft.Extensions.Logging;
using OpenTelemetry.Instrumentation.StackExchangeRedis;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.ResourceDetectors.Container;
using OpenTelemetry.Resources;
Expand All @@ -23,14 +25,23 @@
Console.WriteLine("REDIS_ADDR environment variable is required.");
Environment.Exit(1);
}
var cartStore = new RedisCartStore(redisAddress);

// Initialize the redis store
await cartStore.InitializeAsync();
Console.WriteLine("Initialization completed");
builder.Logging
.AddOpenTelemetry(options => options.AddOtlpExporter())
.AddConsole();

builder.Services.AddSingleton<ICartStore>(x=>
{
var store = new RedisCartStore(x.GetRequiredService<ILogger<RedisCartStore>>(), redisAddress);
store.Initialize();
return store;
});

builder.Services.AddSingleton<ICartStore>(cartStore);
builder.Services.AddSingleton<FeatureFlagHelper>();
builder.Services.AddSingleton(x => new CartService(x.GetRequiredService<ICartStore>(),
new RedisCartStore(x.GetRequiredService<ILogger<RedisCartStore>>(), "badhost:1234"),
julianocosta89 marked this conversation as resolved.
Show resolved Hide resolved
x.GetRequiredService<FeatureFlagHelper>()));


// see https://opentelemetry.io/docs/instrumentation/net/getting-started/

Expand All @@ -42,7 +53,6 @@
.ConfigureResource(appResourceBuilder)
.WithTracing(tracerBuilder => tracerBuilder
.AddRedisInstrumentation(
cartStore.GetConnection(),
options => options.SetVerboseDatabaseStatements = true)
.AddAspNetCoreInstrumentation()
.AddGrpcClientInstrumentation()
Expand All @@ -59,6 +69,9 @@

var app = builder.Build();

var redisCartStore = (RedisCartStore) app.Services.GetRequiredService<ICartStore>();
app.Services.GetRequiredService<StackExchangeRedisInstrumentation>().AddConnection(redisCartStore.GetConnection());

app.MapGrpcService<CartService>();
app.MapGrpcHealthChecksService();

Expand Down
3 changes: 2 additions & 1 deletion src/cartservice/src/cartservice.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.53.0" />
<PackageReference Include="Grpc.AspNetCore.HealthChecks" Version="2.53.0" />
<PackageReference Include="StackExchange.Redis" Version="2.6.122" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol.Logs" Version="1.5.0-rc.1" />
Kielek marked this conversation as resolved.
Show resolved Hide resolved
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.5.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.5.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.5.0-beta.1" />
Expand All @@ -18,6 +18,7 @@
<PackageReference Include="OpenTelemetry.Instrumentation.StackExchangeRedis" Version="1.0.0-rc9.10" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.5.0" />
<PackageReference Include="OpenTelemetry.ResourceDetectors.Container" Version="1.0.0-beta.4" />
<PackageReference Include="StackExchange.Redis" Version="2.6.122" />
</ItemGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/cartservice/src/cartstore/ICartStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace cartservice.cartstore;

public interface ICartStore
{
Task InitializeAsync();
void Initialize();

Task AddItemAsync(string userId, string productId, int quantity);
Task EmptyCartAsync(string userId);
Expand Down
28 changes: 15 additions & 13 deletions src/cartservice/src/cartstore/RedisCartStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
using Grpc.Core;
using StackExchange.Redis;
using Google.Protobuf;
using Microsoft.Extensions.Logging;

namespace cartservice.cartstore;

public class RedisCartStore : ICartStore
{
private readonly ILogger _logger;
private const string CartFieldName = "cart";
private const int RedisRetryNumber = 30;

Expand All @@ -23,8 +25,9 @@ public class RedisCartStore : ICartStore

private readonly ConfigurationOptions _redisConnectionOptions;

public RedisCartStore(string redisAddress)
public RedisCartStore(ILogger<RedisCartStore> logger, string redisAddress)
{
_logger = logger;
// Serialize empty cart into byte array.
var cart = new Oteldemo.Cart();
_emptyCartBytes = cart.ToByteArray();
Expand All @@ -45,10 +48,9 @@ public ConnectionMultiplexer GetConnection()
return _redis;
}

public Task InitializeAsync()
public void Initialize()
{
EnsureRedisConnected();
return Task.CompletedTask;
}

private void EnsureRedisConnected()
Expand All @@ -66,34 +68,34 @@ private void EnsureRedisConnected()
return;
}

Console.WriteLine("Connecting to Redis: " + _connectionString);
_logger.LogDebug("Connecting to Redis: {_connectionString}", _connectionString);
_redis = ConnectionMultiplexer.Connect(_redisConnectionOptions);

if (_redis == null || !_redis.IsConnected)
{
Console.WriteLine("Wasn't able to connect to redis");
_logger.LogError("Wasn't able to connect to redis");

// We weren't able to connect to Redis despite some retries with exponential backoff.
throw new ApplicationException("Wasn't able to connect to redis");
}

Console.WriteLine("Successfully connected to Redis");
_logger.LogInformation("Successfully connected to Redis");
var cache = _redis.GetDatabase();

Console.WriteLine("Performing small test");
_logger.LogDebug("Performing small test");
cache.StringSet("cart", "OK" );
object res = cache.StringGet("cart");
Console.WriteLine($"Small test result: {res}");
_logger.LogDebug("Small test result: {res}", res);

_redis.InternalError += (_, e) => { Console.WriteLine(e.Exception); };
_redis.ConnectionRestored += (_, _) =>
{
_isRedisConnectionOpened = true;
Console.WriteLine("Connection to redis was restored successfully.");
_logger.LogInformation("Connection to redis was restored successfully.");
};
_redis.ConnectionFailed += (_, _) =>
{
Console.WriteLine("Connection failed. Disposing the object");
_logger.LogInformation("Connection failed. Disposing the object");
_isRedisConnectionOpened = false;
};

Expand All @@ -103,7 +105,7 @@ private void EnsureRedisConnected()

public async Task AddItemAsync(string userId, string productId, int quantity)
{
Console.WriteLine($"AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}");
_logger.LogInformation("AddItemAsync called with userId={userId}, productId={productId}, quantity={quantity}", userId, productId, quantity);

try
{
Expand Down Expand Up @@ -148,7 +150,7 @@ public async Task AddItemAsync(string userId, string productId, int quantity)

public async Task EmptyCartAsync(string userId)
{
Console.WriteLine($"EmptyCartAsync called with userId={userId}");
_logger.LogInformation("EmptyCartAsync called with userId={userId}", userId);

try
{
Expand All @@ -167,7 +169,7 @@ public async Task EmptyCartAsync(string userId)

public async Task<Oteldemo.Cart> GetCartAsync(string userId)
{
Console.WriteLine($"GetCartAsync called with userId={userId}");
_logger.LogInformation("GetCartAsync called with userId={userId}", userId);

try
{
Expand Down
7 changes: 4 additions & 3 deletions src/cartservice/src/services/CartService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ namespace cartservice.services;
public class CartService : Oteldemo.CartService.CartServiceBase
{
private static readonly Empty Empty = new();
private static readonly ICartStore BadCartStore = new RedisCartStore("badhost:1234");
private readonly ICartStore _badCartStore;
private readonly ICartStore _cartStore;
private readonly FeatureFlagHelper _featureFlagHelper;

public CartService(ICartStore cartStore, FeatureFlagHelper featureFlagService)
public CartService(ICartStore cartStore, ICartStore badCartStore, FeatureFlagHelper featureFlagService)
{
_badCartStore = badCartStore;
_cartStore = cartStore;
_featureFlagHelper = featureFlagService;
}
Expand Down Expand Up @@ -61,7 +62,7 @@ public override async Task<Empty> EmptyCart(EmptyCartRequest request, ServerCall
{
if (await _featureFlagHelper.GenerateCartError())
{
await BadCartStore.EmptyCartAsync(request.UserId);
await _badCartStore.EmptyCartAsync(request.UserId);
}
else
{
Expand Down
Loading