diff --git a/Directory.Packages.props b/Directory.Packages.props index 8e8ded37..9995d65c 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -4,6 +4,8 @@ + + \ No newline at end of file diff --git a/common/HostBuilderExtensions.cs b/common/HostBuilderExtensions.cs new file mode 100644 index 00000000..f79307ca --- /dev/null +++ b/common/HostBuilderExtensions.cs @@ -0,0 +1,17 @@ +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Dapr.Tests.Common; + +public static class HostBuilderExtensions +{ + public static IHostBuilder ConfigureTestInfraLogging(this IHostBuilder builder) + { + return builder.ConfigureLogging( + (hostingContext, config) => + { + config.ClearProviders(); + config.AddJsonConsole(); + }); + } +} diff --git a/common/common.csproj b/common/common.csproj index 3aa4964c..8dc5516a 100644 --- a/common/common.csproj +++ b/common/common.csproj @@ -12,6 +12,8 @@ + + diff --git a/feed-generator/Program.cs b/feed-generator/Program.cs index 9a19c238..c801fb37 100644 --- a/feed-generator/Program.cs +++ b/feed-generator/Program.cs @@ -9,7 +9,9 @@ namespace FeedGenerator using Dapr.Tests.Common; using Dapr.Tests.Common.Models; using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging; using Prometheus; using System; using System.Threading.Tasks; @@ -31,22 +33,26 @@ public class Program /// Arguments. public static void Main(string[] args) { + ObservabilityUtils.StartMetricsServer(); + + IHost host = CreateHostBuilder(args) + .ConfigureTestInfraLogging() + .Build(); + + var logger = host.Services.GetRequiredService>(); + int delayInMilliseconds = 10000; if (args.Length != 0 && args[0] != "%LAUNCHER_ARGS%") { if (int.TryParse(args[0], out delayInMilliseconds) == false) { string msg = "Could not parse delay"; - Console.WriteLine(msg); + logger.LogError(msg); throw new InvalidOperationException(msg); } } - ObservabilityUtils.StartMetricsServer(); - - IHost host = CreateHostBuilder(args).Build(); - - Task.Run(() => StartMessageGeneratorAsync(delayInMilliseconds)); + Task.Run(() => StartMessageGeneratorAsync(delayInMilliseconds, logger)); host.Run(); } @@ -63,7 +69,7 @@ public static IHostBuilder CreateHostBuilder(string[] args) => webBuilder.UseStartup(); }); - static internal async void StartMessageGeneratorAsync(int delayInMilliseconds) + static internal async void StartMessageGeneratorAsync(int delayInMilliseconds, ILogger logger) { // the name of the component and the topic happen to be the same here... const string PubsubComponentName = "receivemediapost"; @@ -80,7 +86,7 @@ static internal async void StartMessageGeneratorAsync(int delayInMilliseconds) try { - Console.WriteLine("Publishing"); + logger.LogInformation("Publishing"); using (PublishCallTime.NewTimer()) { await client.PublishEventAsync(PubsubComponentName, PubsubTopicName, message); @@ -88,7 +94,7 @@ static internal async void StartMessageGeneratorAsync(int delayInMilliseconds) } catch (Exception e) { - Console.WriteLine("Caught {0}", e.ToString()); + logger.LogError(e, "Caught {Exception}", e); PublishFailureCount.Inc(); } diff --git a/hashtag-actor/Actors/HashTagActor.cs b/hashtag-actor/Actors/HashTagActor.cs index d80d4803..48fb35b0 100644 --- a/hashtag-actor/Actors/HashTagActor.cs +++ b/hashtag-actor/Actors/HashTagActor.cs @@ -20,20 +20,10 @@ public class HashTagActor : Actor, IHashTagActor /// Initializes a new instance of the class. /// /// Actor Service hosting the actor. - public HashTagActor(ActorHost host) + public HashTagActor(ActorHost host, ILogger logger) : base(host) { - // TODO: ActorHost may need to have IHostBuilder reference to allow user to interact web host. - // For example, getting logger factory given by WebHost - var loggerFactory = LoggerFactory.Create(builder => - { - builder - .AddFilter("Microsoft", LogLevel.Warning) - .AddFilter("System", LogLevel.Warning) - .AddConsole(); - }); - - this.logger = loggerFactory.CreateLogger(); + this.logger = logger; } /// @@ -47,13 +37,13 @@ public async Task Increment(string hashtagAndSentiment) } catch (KeyNotFoundException) { - this.logger.LogDebug($"{hashtagAndSentiment} does not exist. {hashtagAndSentiment} will be initialized to 0."); + this.logger.LogDebug("{HashtagAndSentiment} does not exist. {HashtagAndSentiment} will be initialized to 0.", hashtagAndSentiment); } - this.logger.LogDebug($"{hashtagAndSentiment} = {count}"); + this.logger.LogDebug("{HashtagAndSentiment} = {Count}", hashtagAndSentiment, count); count++; await this.StateManager.SetStateAsync(hashtagAndSentiment, count); - this.logger.LogInformation($"Incremented {hashtagAndSentiment}."); + this.logger.LogInformation("Incremented {HashtagAndSentiment}.", hashtagAndSentiment); } public async Task GetCount(string hashtagAndSentiment) @@ -62,11 +52,11 @@ public async Task GetCount(string hashtagAndSentiment) try { count = await this.StateManager.GetStateAsync(hashtagAndSentiment); - this.logger.LogInformation($"GetCount for {hashtagAndSentiment} found and it is {count}."); + this.logger.LogInformation("GetCount for {HashtagAndSentiment} found and it is {Count}.", hashtagAndSentiment, count); } catch (KeyNotFoundException) { - this.logger.LogInformation($"{hashtagAndSentiment} does not exist."); + this.logger.LogInformation("{HashtagAndSentiment} does not exist.", hashtagAndSentiment); } return count; diff --git a/hashtag-actor/Program.cs b/hashtag-actor/Program.cs index 93e79814..eb6ce49d 100644 --- a/hashtag-actor/Program.cs +++ b/hashtag-actor/Program.cs @@ -24,12 +24,7 @@ public static void Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) { var hostBuilder = Host.CreateDefaultBuilder(args) - .ConfigureLogging((hostingContext, config) => - { - config.ClearProviders(); - config.AddConsole(); - - }) + .ConfigureTestInfraLogging() .ConfigureWebHostDefaults(webBuilder => { var appSettings = new ConfigurationBuilder() diff --git a/hashtag-actor/Startup.cs b/hashtag-actor/Startup.cs index ad927458..3f3b5727 100644 --- a/hashtag-actor/Startup.cs +++ b/hashtag-actor/Startup.cs @@ -33,7 +33,6 @@ public void ConfigureServices(IServiceCollection services) // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { - Console.WriteLine("Configure"); if (env.EnvironmentName.Contains(".dev")) { app.UseDeveloperExceptionPage(); diff --git a/hashtag-counter/Controllers/HashTagController.cs b/hashtag-counter/Controllers/HashTagController.cs index a801d90c..cb25f7d7 100644 --- a/hashtag-counter/Controllers/HashTagController.cs +++ b/hashtag-counter/Controllers/HashTagController.cs @@ -28,21 +28,23 @@ public class HashTagController : ControllerBase private readonly IConfiguration configuration; - public HashTagController(IConfiguration config) + private readonly ILogger logger; + + public HashTagController(IConfiguration config, ILogger logger) { - Console.WriteLine("ctor."); this.configuration = config; + this.logger = logger; } [HttpPost("messagebinding")] public async Task PostMessageBinding([FromBody]SocialMediaMessage message) { - Console.WriteLine("enter messagebinding"); + this.logger.LogDebug("enter messagebinding"); var duration = DateTime.UtcNow - message.PreviousAppTimestamp; BindingDuration.Set(duration.TotalSeconds); - Console.WriteLine($"{message.CreationDate}, {message.CorrelationId}, {message.MessageId}, {message.Message}, {message.Sentiment}"); + this.logger.LogInformation("{CreationDate}, {CorrelationId}, {MessageId}, {Message}, {Sentiment}", message.CreationDate, message.CorrelationId, message.MessageId, message.Message, message.Sentiment); int indexOfHash = message.Message.LastIndexOf('#'); string hashTag = message.Message.Substring(indexOfHash + 1); @@ -51,16 +53,16 @@ public async Task PostMessageBinding([FromBody]SocialMediaMessage var actorId = new ActorId(key); var proxy = ActorProxy.Create(actorId, "HashTagActor"); - Console.WriteLine($"Increasing {key}."); + this.logger.LogInformation("Increasing {Key}.", key); Exception ex = null; try { await proxy.Increment(key); - Console.WriteLine($"Increasing {key} successful."); + this.logger.LogInformation("Increasing {Key} successful.", key); } catch (Exception e) { - Console.WriteLine($"Increasing {key} failed with {e}"); + this.logger.LogError(e, "Increasing {Key} failed with {Exception}", key, e); ex = e; ActorMethodFailureCount.Inc(); } diff --git a/hashtag-counter/Program.cs b/hashtag-counter/Program.cs index b3b805ea..8ba74360 100644 --- a/hashtag-counter/Program.cs +++ b/hashtag-counter/Program.cs @@ -24,12 +24,7 @@ public static void Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) { var hostBuilder = Host.CreateDefaultBuilder(args) - .ConfigureLogging((hostingContext, config) => - { - config.ClearProviders(); - config.AddConsole(); - - }) + .ConfigureTestInfraLogging() .ConfigureWebHostDefaults(webBuilder => { var appSettings = new ConfigurationBuilder() diff --git a/hashtag-counter/Startup.cs b/hashtag-counter/Startup.cs index 6f0efc67..2ae494c6 100644 --- a/hashtag-counter/Startup.cs +++ b/hashtag-counter/Startup.cs @@ -27,7 +27,6 @@ public Startup(IConfiguration configuration) // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - Console.WriteLine("ConfigureServices()"); services.AddControllers(); } @@ -35,7 +34,6 @@ public void ConfigureServices(IServiceCollection services) // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { - Console.WriteLine("Configure"); if (env.EnvironmentName.Contains(".dev")) { app.UseDeveloperExceptionPage(); diff --git a/message-analyzer/Program.cs b/message-analyzer/Program.cs index 04f667d4..e323a5e6 100644 --- a/message-analyzer/Program.cs +++ b/message-analyzer/Program.cs @@ -29,8 +29,6 @@ public class MessageAnalyzer /// Arguments. public static void Main(string[] args) { - Console.WriteLine("Enter main"); - ObservabilityUtils.StartMetricsServer(); CreateHostBuilder(args).Build().Run(); @@ -43,12 +41,7 @@ public static void Main(string[] args) /// Returns IHostbuilder. public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) - .ConfigureLogging((hostingContext, config) => - { - config.ClearProviders(); - config.AddConsole(); - - }) + .ConfigureTestInfraLogging() .ConfigureWebHostDefaults(webBuilder => { var appSettings = new ConfigurationBuilder() diff --git a/message-analyzer/Startup.cs b/message-analyzer/Startup.cs index d91180c5..b6f6a495 100644 --- a/message-analyzer/Startup.cs +++ b/message-analyzer/Startup.cs @@ -14,6 +14,7 @@ namespace MessageAnalyzer using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging; using Prometheus; using System; using System.Text.Json; @@ -108,9 +109,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, JsonSeri }); // Receive a "Post" object from the previous app in the pipeline. - async Task ReceiveMediaPost(HttpContext context) + async Task ReceiveMediaPost(HttpContext context, ILogger logger) { - Console.WriteLine("Enter ReceiveMediaPost"); + logger.LogDebug("Enter ReceiveMediaPost"); var client = context.RequestServices.GetRequiredService(); var message = await JsonSerializer.DeserializeAsync(context.Request.Body, serializerOptions); @@ -121,7 +122,7 @@ async Task ReceiveMediaPost(HttpContext context) // update with a sentiment message.Sentiment = GenerateRandomSentiment(); - Console.WriteLine($"....Invoking binding {BindingName} with message {message.Message} and sentiment {message.Sentiment}"); + logger.LogInformation("....Invoking binding {BindingName} with message {Message} and sentiment {Sentiment}", BindingName, message.Message, message.Sentiment); // overwrite the timestamp so the next app can use it message.PreviousAppTimestamp = DateTime.UtcNow; @@ -131,12 +132,12 @@ async Task ReceiveMediaPost(HttpContext context) using (OutputBindingCallTime.NewTimer()) { await client.InvokeBindingAsync(BindingName, "create", message); - Console.WriteLine("Invoke binding \"create\" completed successfully"); + logger.LogInformation("Invoke binding \"create\" completed successfully"); } } catch (Exception e) { - Console.WriteLine("Caught {0}", e); + logger.LogError(e, "Caught {Exception}", e); BindingApiFailureCount.Inc(); } } diff --git a/pubsub-workflow/Controllers/PubsubController.cs b/pubsub-workflow/Controllers/PubsubController.cs index 980e530d..d62c41e0 100644 --- a/pubsub-workflow/Controllers/PubsubController.cs +++ b/pubsub-workflow/Controllers/PubsubController.cs @@ -6,6 +6,7 @@ using Dapr; using Dapr.Client; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; @@ -19,12 +20,19 @@ public class PubsubController : ControllerBase internal static DateTime lastSlowCall = DateTime.Now; internal static DateTime lastGlacialCall = DateTime.Now; + private readonly ILogger logger; + + public PubsubController(ILogger logger) + { + this.logger = logger; + } + [Topic("longhaul-sb-rapid", "rapidtopic")] [HttpPost("rapidMessage")] public IActionResult RapidMessageHandler() { var lastHit = lastRapidCall; lastRapidCall = DateTime.Now; - Console.WriteLine($"Rapid subscription hit at {lastRapidCall}, previous hit at {lastHit}"); + this.logger.LogInformation("Rapid subscription hit at {LastRapidCall}, previous hit at {LastHit}", lastRapidCall, lastHit); return Ok(); } @@ -33,7 +41,7 @@ public IActionResult RapidMessageHandler() { public IActionResult MediumMessageHandler() { var lastHit = lastMediumCall; lastMediumCall = DateTime.Now; - Console.WriteLine($"Medium subscription hit at {lastMediumCall}, previous hit at {lastHit}"); + this.logger.LogInformation("Medium subscription hit at {LastMediumCall}, previous hit at {LastHit}", lastMediumCall, lastHit); return Ok(); } @@ -42,7 +50,7 @@ public IActionResult MediumMessageHandler() { public IActionResult SlowMessageHandler() { var lastHit = lastSlowCall; lastSlowCall = DateTime.Now; - Console.WriteLine($"Slow subscription hit at {lastSlowCall}, previous hit at {lastHit}"); + this.logger.LogInformation("Slow subscription hit at {LastSlowCall}, previous hit at {LastHit}", lastSlowCall, lastHit); return Ok(); } @@ -51,7 +59,7 @@ public IActionResult SlowMessageHandler() { public IActionResult GlacialMessageHandler() { var lastHit = lastGlacialCall; lastGlacialCall = DateTime.Now; - Console.WriteLine($"Glacial subscription hit at {lastGlacialCall}, previous hit at {lastHit}"); + this.logger.LogInformation("Glacial subscription hit at {LastGlacialCall}, previous hit at {LastHit}", lastGlacialCall, lastHit); return Ok(); } } diff --git a/pubsub-workflow/Program.cs b/pubsub-workflow/Program.cs index ebccdefb..5c75443e 100644 --- a/pubsub-workflow/Program.cs +++ b/pubsub-workflow/Program.cs @@ -7,6 +7,7 @@ using Dapr.Tests.Common; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; @@ -26,12 +27,14 @@ class PubsubWorkflow static void Main(string[] args) { - Console.WriteLine("Starting Pubsub Workflow"); - ObservabilityUtils.StartMetricsServer(); var host = CreateHostBuilder(args).Build(); + var logger = host.Services.GetRequiredService>(); + + logger.LogInformation("Starting Pubsub Workflow"); + var rapidTimer = StartPublishingMessages(10, rapidPubsubName, "rapidtopic"); var mediumTimer = StartPublishingMessages(300, mediumPubsubName, "mediumtopic"); var slowTimer = StartPublishingMessages(3600, slowPubsubName, "slowtopic"); @@ -39,7 +42,7 @@ static void Main(string[] args) host.Run(); - Console.WriteLine("Exiting Pubsub Workflow"); + logger.LogInformation("Exiting Pubsub Workflow"); rapidTimer.Dispose(); mediumTimer.Dispose(); @@ -49,23 +52,18 @@ static void Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) - .ConfigureLogging((hostingContext, config) => - { - config.ClearProviders(); - config.AddConsole(); - - }) - .ConfigureWebHostDefaults(webBuilder => - { - var appSettings = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true) - .AddCommandLine(args) - .Build(); + .ConfigureTestInfraLogging() + .ConfigureWebHostDefaults(webBuilder => + { + var appSettings = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile($"appsettings.json", optional: true, reloadOnChange: true) + .AddCommandLine(args) + .Build(); - webBuilder.UseStartup() - .UseUrls(urls: $"http://*:{appSettings["DaprHTTPAppPort"]}"); - }); + webBuilder.UseStartup() + .UseUrls(urls: $"http://*:{appSettings["DaprHTTPAppPort"]}"); + }); static internal Timer StartPublishingMessages(int periodInSeconds, string pubsubName, string topic) { diff --git a/snapshot/Controllers/HashTagController.cs b/snapshot/Controllers/HashTagController.cs index 2c5c754a..fed28592 100644 --- a/snapshot/Controllers/HashTagController.cs +++ b/snapshot/Controllers/HashTagController.cs @@ -8,6 +8,7 @@ namespace Dapr.Tests.Snapshot.Controllers using Dapr.Client; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Net.Mime; @@ -18,17 +19,18 @@ namespace Dapr.Tests.Snapshot.Controllers public class HashTagController : ControllerBase { private readonly IConfiguration configuration; + private readonly ILogger logger; - public HashTagController(IConfiguration config) + public HashTagController(IConfiguration config, ILogger logger) { - Console.WriteLine("ctor."); this.configuration = config; + this.logger = logger; } [HttpGet("hashtagdata")] public async Task> GetHashTagData([FromServices]DaprClient daprClient) { - Console.WriteLine("enter GetHashTagData"); + this.logger.LogDebug("enter GetHashTagData"); var stats = await daprClient.GetStateAsync>("statestore", "statskey"); return stats; diff --git a/snapshot/Program.cs b/snapshot/Program.cs index ec2d7aa7..3b2f09e7 100644 --- a/snapshot/Program.cs +++ b/snapshot/Program.cs @@ -13,6 +13,7 @@ namespace Dapr.Tests.Snapshot using Dapr.Tests.HashTagApp.Actors; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; + using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Prometheus; @@ -32,6 +33,12 @@ public class Program public static void Main(string[] args) { + ObservabilityUtils.StartMetricsServer(); + + var host = CreateHostBuilder(args).Build(); + + var logger = host.Services.GetRequiredService>(); + int delayInMilliseconds = 5000; var delay = Environment.GetEnvironmentVariable("DELAY_IN_MS"); if (delay != null) @@ -39,13 +46,9 @@ public static void Main(string[] args) delayInMilliseconds = int.Parse(delay); } - Console.WriteLine("Configured delayInMilliseconds={0}", delayInMilliseconds); + logger.LogDebug("Configured delayInMilliseconds={DelayInMilliseconds}", delayInMilliseconds); - ObservabilityUtils.StartMetricsServer(); - - var host = CreateHostBuilder(args).Build(); - - Task.Run(() => StartQueryLoopAsync(delayInMilliseconds)); + Task.Run(() => StartQueryLoopAsync(delayInMilliseconds, logger)); host.Run(); } @@ -53,12 +56,7 @@ public static void Main(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) { var hostBuilder = Host.CreateDefaultBuilder(args) - .ConfigureLogging((hostingContext, config) => - { - config.ClearProviders(); - config.AddConsole(); - - }) + .ConfigureTestInfraLogging() .ConfigureWebHostDefaults(webBuilder => { var appSettings = new ConfigurationBuilder() @@ -74,9 +72,9 @@ public static IHostBuilder CreateHostBuilder(string[] args) return hostBuilder; } - static internal async void StartQueryLoopAsync(int delayInMilliseconds) + static internal async void StartQueryLoopAsync(int delayInMilliseconds, ILogger logger) { - Console.WriteLine("Starting query loop"); + logger.LogDebug("Starting query loop"); TimeSpan delay = TimeSpan.FromMilliseconds(delayInMilliseconds); @@ -86,7 +84,7 @@ static internal async void StartQueryLoopAsync(int delayInMilliseconds) DateTime lastSnapshotTime = DateTime.MinValue; while (true) { - Console.WriteLine("Sleeping '{0}' ms", delayInMilliseconds); + logger.LogInformation("Sleeping '{DelayInMilliseconds}' ms", delayInMilliseconds); await Task.Delay(delay); Dictionary stats = new Dictionary(); @@ -103,7 +101,7 @@ static internal async void StartQueryLoopAsync(int delayInMilliseconds) var actorId = new ActorId(key); var proxy = ActorProxy.Create(actorId, "HashTagActor"); - Console.WriteLine($"GetCount on {key}."); + logger.LogInformation("GetCount on {Key}.", key); int count = -1; try { @@ -113,11 +111,11 @@ static internal async void StartQueryLoopAsync(int delayInMilliseconds) } stats.Add(key, count); - Console.WriteLine($"key={key}, value={count}."); + logger.LogInformation("key={Key}, value={Count}.", key, count); } catch (Exception e) { - Console.WriteLine($"{e}"); + logger.LogError(e, "{Exception}", e); ActorMethodFailureCount.Inc(); throw; } diff --git a/snapshot/Startup.cs b/snapshot/Startup.cs index 482c3661..950a6aaa 100644 --- a/snapshot/Startup.cs +++ b/snapshot/Startup.cs @@ -23,7 +23,6 @@ public Startup(IConfiguration configuration) // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { - Console.WriteLine("ConfigureServices()"); services.AddDaprClient(); services.AddControllers(); } @@ -31,7 +30,6 @@ public void ConfigureServices(IServiceCollection services) // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { - Console.WriteLine("Configure"); if (env.EnvironmentName.Contains(".dev")) { app.UseDeveloperExceptionPage(); diff --git a/validation-worker/Program.cs b/validation-worker/Program.cs index 7e60b90b..c22dbdf7 100644 --- a/validation-worker/Program.cs +++ b/validation-worker/Program.cs @@ -6,8 +6,11 @@ namespace ValidationWorker { using Dapr.Client; + using Dapr.Tests.Common; using Microsoft.AspNetCore.Hosting; + using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; + using Microsoft.Extensions.Logging; using Prometheus; using System; using System.Collections.Generic; @@ -41,9 +44,13 @@ public static void Main(string[] args) var server = new MetricServer(port: 9988); server.Start(); - IHost host = CreateHostBuilder(args).Build(); + IHost host = CreateHostBuilder(args) + .ConfigureTestInfraLogging() + .Build(); - Task.Run(() => StartValidationLoopAsync(delayInSeconds)); + var logger = host.Services.GetRequiredService>(); + + Task.Run(() => StartValidationLoopAsync(delayInSeconds, logger)); host.Run(); } @@ -60,7 +67,7 @@ public static IHostBuilder CreateHostBuilder(string[] args) => webBuilder.UseStartup(); }); - static internal async void StartValidationLoopAsync(int delayInSeconds) + static internal async void StartValidationLoopAsync(int delayInSeconds, ILogger logger) { const string SnapshotAppName = "snapshot"; TimeSpan delay = TimeSpan.FromSeconds(delayInSeconds); @@ -73,7 +80,7 @@ static internal async void StartValidationLoopAsync(int delayInSeconds) while (true) { - Console.WriteLine("Checking stats in {0} seconds", delayInSeconds); + logger.LogInformation("Checking stats in {DelayInSeconds} seconds", delayInSeconds); await Task.Delay(delay); try @@ -88,7 +95,7 @@ static internal async void StartValidationLoopAsync(int delayInSeconds) } catch (Exception e) { - Console.WriteLine("Caught {0}", e.ToString()); + logger.LogError(e, "Caught {Exception}", e); ServiceInvocationFailureCount.Inc(); continue; } @@ -106,10 +113,10 @@ static internal async void StartValidationLoopAsync(int delayInSeconds) } } - Console.WriteLine("Number changed is {0}", changed); + logger.LogInformation("Number changed is {Changed}", changed); if (changed == 0) { - LogStats(prevStats, stats); + LogStats(prevStats, stats, logger); UnchangedStatsMetric.IncTo(1); } else @@ -122,19 +129,19 @@ static internal async void StartValidationLoopAsync(int delayInSeconds) } } - static internal void LogStats(Dictionary prevStats, Dictionary stats) + static internal void LogStats(Dictionary prevStats, Dictionary stats, ILogger logger) { - Console.WriteLine("The stats from the snapshot app did not change reporting error metric, logging previous and current:"); - Console.WriteLine("Previous:"); + logger.LogInformation("The stats from the snapshot app did not change reporting error metric, logging previous and current:"); + logger.LogInformation("Previous:"); foreach (var kv in prevStats) { - Console.WriteLine("{0} - {1}", kv.Key, kv.Value); + logger.LogInformation("{Key} - {Value}", kv.Key, kv.Value); } - Console.WriteLine("Current:"); + logger.LogInformation("Current:"); foreach (var kv in stats) { - Console.WriteLine("{0} - {1}", kv.Key, kv.Value); + logger.LogInformation("{Key} - {Value}", kv.Key, kv.Value); } } } diff --git a/validation-worker/validation-worker.csproj b/validation-worker/validation-worker.csproj index 696a9a4a..67bf60b4 100644 --- a/validation-worker/validation-worker.csproj +++ b/validation-worker/validation-worker.csproj @@ -6,6 +6,10 @@ ..\docker-compose.dcproj + + + + diff --git a/workflow-gen/Activities/UpdateInventoryActivity.cs b/workflow-gen/Activities/UpdateInventoryActivity.cs index 57a8fb9e..61f86ee6 100644 --- a/workflow-gen/Activities/UpdateInventoryActivity.cs +++ b/workflow-gen/Activities/UpdateInventoryActivity.cs @@ -23,7 +23,7 @@ public UpdateInventoryActivity(ILoggerFactory loggerFactory, DaprClient client) public override async Task RunAsync(WorkflowActivityContext context, PaymentRequest req) { this.logger.LogInformation( - "Checking Inventory for: Order# {requestId} for {amount} {item}", + "Checking Inventory for: Order# {RequestId} for {Amount} {Item}", req.RequestId, req.Amount, req.ItemBeingPruchased); @@ -36,13 +36,13 @@ public override async Task RunAsync(WorkflowActivityContext context, Pay if (newQuantity < 0) { this.logger.LogInformation( - "Payment for request ID '{requestId}' could not be processed. Insufficient inventory.", + "Payment for request ID '{RequestId}' could not be processed. Insufficient inventory.", req.RequestId); throw new InvalidOperationException(); } await client.SaveStateAsync(storeName, req.ItemBeingPruchased, new OrderPayload(Name: req.ItemBeingPruchased, TotalCost: req.Currency, Quantity: newQuantity)); - this.logger.LogInformation($"There are now: {newQuantity} {original.Name} left in stock"); + this.logger.LogInformation("There are now: {NewQuantity} {OriginalName} left in stock", newQuantity, original.Name); return null; } diff --git a/workflow-gen/Program.cs b/workflow-gen/Program.cs index 971a2dd4..72fb8f7f 100644 --- a/workflow-gen/Program.cs +++ b/workflow-gen/Program.cs @@ -9,6 +9,7 @@ using Dapr.Workflow; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; @@ -35,34 +36,38 @@ public static void Main(string[] args) { ObservabilityUtils.StartMetricsServer(); - var builder = Host.CreateDefaultBuilder(args).ConfigureServices(services => - { - services.AddDaprWorkflow(options => + var builder = Host.CreateDefaultBuilder(args) + .ConfigureTestInfraLogging() + .ConfigureServices(services => { - options.RegisterWorkflow(); - options.RegisterActivity(); - options.RegisterActivity(); - options.RegisterActivity(); - options.RegisterActivity(); + services.AddDaprWorkflow(options => + { + options.RegisterWorkflow(); + options.RegisterActivity(); + options.RegisterActivity(); + options.RegisterActivity(); + options.RegisterActivity(); + }); }); - }); - var wTimer = StartExecutingWorkflows(30); using var host = builder.Build(); + + var logger = host.Services.GetRequiredService>(); + + var wTimer = StartExecutingWorkflows(30, logger); host.Run(); wTimer.Dispose(); } - static internal Timer StartExecutingWorkflows(int periodInSeconds) + static internal Timer StartExecutingWorkflows(int periodInSeconds, ILogger logger) { DaprClientBuilder daprClientBuilder = new DaprClientBuilder(); var client = new DaprClientBuilder().Build(); var counter = 0; - var workflowRunner = new WorkflowRunner(client, counter); + var workflowRunner = new WorkflowRunner(client, counter, logger); return new Timer(workflowRunner.Execute, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(periodInSeconds)); } - } } diff --git a/workflow-gen/WorkflowRunner.cs b/workflow-gen/WorkflowRunner.cs index 3a8e1c35..ed40d490 100644 --- a/workflow-gen/WorkflowRunner.cs +++ b/workflow-gen/WorkflowRunner.cs @@ -30,19 +30,11 @@ public class WorkflowRunner private readonly ILogger logger; - public WorkflowRunner([FromServices] DaprClient client, int counter) + public WorkflowRunner([FromServices] DaprClient client, int counter, ILogger logger) { this.Client = client; this.Counter = counter; - var loggerFactory = LoggerFactory.Create(builder => - { - builder - .AddFilter("Microsoft", LogLevel.Warning) - .AddFilter("System", LogLevel.Warning) - .AddConsole(); - }); - - this.logger = loggerFactory.CreateLogger(); + this.logger = logger; } internal async void Execute(Object stateInfo) @@ -71,18 +63,18 @@ await Client.StartWorkflowAsync( instanceId: orderId, workflowComponent: DaprWorkflowComponent); - this.logger.LogInformation("Your workflow has started. Here is the status of the workflow: {0}", state.RuntimeStatus); + this.logger.LogInformation("Your workflow has started. Here is the status of the workflow: {Status}", state.RuntimeStatus); state = await Client.WaitForWorkflowCompletionAsync( instanceId: orderId, workflowComponent: DaprWorkflowComponent); - this.logger.LogInformation("Workflow Status: {0}", state.RuntimeStatus); + this.logger.LogInformation("Workflow Status: {Status}", state.RuntimeStatus); } catch (Exception ex) { - this.logger.LogError("Caught {0}", ex.ToString()); + this.logger.LogError(ex, "Caught {Exception}", ex); ExecutionFailureCount.Inc(); } }