From 9704c7d9565175711de51c3606ca76d587c909f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Kie=C5=82kowicz?= Date: Thu, 31 Aug 2023 09:18:53 +0200 Subject: [PATCH] [cartservice] Support for Logs --- CHANGELOG.md | 2 ++ src/cartservice/src/Program.cs | 27 +++++++++++++----- src/cartservice/src/cartservice.csproj | 3 +- src/cartservice/src/cartstore/ICartStore.cs | 2 +- .../src/cartstore/RedisCartStore.cs | 28 ++++++++++--------- src/cartservice/src/services/CartService.cs | 7 +++-- 6 files changed, 44 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b17d41cdb2..f1e946e034 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,6 +77,8 @@ release. ([#1054](https://github.com/open-telemetry/opentelemetry-demo/pull/1054)) * [frontendproxy] Fix typo URL endpoint for FrontendProxy ([#1075](https://github.com/open-telemetry/opentelemetry-demo/pull/1075)) +* [cartservice] Support for logs + ([#1086](https://github.com/open-telemetry/opentelemetry-demo/pull/1086)) ## 1.4.0 diff --git a/src/cartservice/src/Program.cs b/src/cartservice/src/Program.cs index 24ea5bf7f0..6c7c612391 100644 --- a/src/cartservice/src/Program.cs +++ b/src/cartservice/src/Program.cs @@ -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; @@ -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(x=> +{ + var store = new RedisCartStore(x.GetRequiredService>(), redisAddress); + store.Initialize(); + return store; +}); -builder.Services.AddSingleton(cartStore); builder.Services.AddSingleton(); +builder.Services.AddSingleton(x => new CartService(x.GetRequiredService(), + new RedisCartStore(x.GetRequiredService>(), "badhost:1234"), + x.GetRequiredService())); + // see https://opentelemetry.io/docs/instrumentation/net/getting-started/ @@ -42,7 +53,6 @@ .ConfigureResource(appResourceBuilder) .WithTracing(tracerBuilder => tracerBuilder .AddRedisInstrumentation( - cartStore.GetConnection(), options => options.SetVerboseDatabaseStatements = true) .AddAspNetCoreInstrumentation() .AddGrpcClientInstrumentation() @@ -59,6 +69,9 @@ var app = builder.Build(); +var redisCartStore = (RedisCartStore) app.Services.GetRequiredService(); +app.Services.GetRequiredService().AddConnection(redisCartStore.GetConnection()); + app.MapGrpcService(); app.MapGrpcHealthChecksService(); diff --git a/src/cartservice/src/cartservice.csproj b/src/cartservice/src/cartservice.csproj index 38b1e95760..f437bbf492 100644 --- a/src/cartservice/src/cartservice.csproj +++ b/src/cartservice/src/cartservice.csproj @@ -9,7 +9,7 @@ - + @@ -18,6 +18,7 @@ + diff --git a/src/cartservice/src/cartstore/ICartStore.cs b/src/cartservice/src/cartstore/ICartStore.cs index 21d0e65fc4..fe85b175de 100644 --- a/src/cartservice/src/cartstore/ICartStore.cs +++ b/src/cartservice/src/cartstore/ICartStore.cs @@ -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); diff --git a/src/cartservice/src/cartstore/RedisCartStore.cs b/src/cartservice/src/cartstore/RedisCartStore.cs index bccfce7b5f..b9f54bcca0 100644 --- a/src/cartservice/src/cartstore/RedisCartStore.cs +++ b/src/cartservice/src/cartstore/RedisCartStore.cs @@ -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; @@ -23,8 +25,9 @@ public class RedisCartStore : ICartStore private readonly ConfigurationOptions _redisConnectionOptions; - public RedisCartStore(string redisAddress) + public RedisCartStore(ILogger logger, string redisAddress) { + _logger = logger; // Serialize empty cart into byte array. var cart = new Oteldemo.Cart(); _emptyCartBytes = cart.ToByteArray(); @@ -45,10 +48,9 @@ public ConnectionMultiplexer GetConnection() return _redis; } - public Task InitializeAsync() + public void Initialize() { EnsureRedisConnected(); - return Task.CompletedTask; } private void EnsureRedisConnected() @@ -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; }; @@ -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 { @@ -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 { @@ -167,7 +169,7 @@ public async Task EmptyCartAsync(string userId) public async Task GetCartAsync(string userId) { - Console.WriteLine($"GetCartAsync called with userId={userId}"); + _logger.LogInformation("GetCartAsync called with userId={userId}", userId); try { diff --git a/src/cartservice/src/services/CartService.cs b/src/cartservice/src/services/CartService.cs index 244042ddf3..87b8c4ce1e 100644 --- a/src/cartservice/src/services/CartService.cs +++ b/src/cartservice/src/services/CartService.cs @@ -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; } @@ -61,7 +62,7 @@ public override async Task EmptyCart(EmptyCartRequest request, ServerCall { if (await _featureFlagHelper.GenerateCartError()) { - await BadCartStore.EmptyCartAsync(request.UserId); + await _badCartStore.EmptyCartAsync(request.UserId); } else {