using System; using System.Diagnostics; using System.Threading.Tasks; namespace Sony.Filtr.Utility.Logging { public static class LogActionWrapper { public static async Task Execute(Func> action, ILogger logger, string actionName, string parameters = null) { if (logger == null) { throw new ArgumentNullException(nameof(logger)); } string correlationId = Guid.NewGuid().ToString().ToUpperInvariant(); string args = "Not presented"; try { if(parameters != null) args = parameters.ToString(); } catch (Exception) { //Nothing to do because we need to continue app working } var stopwatch = new Stopwatch(); stopwatch.Start(); bool completedWithError = false; try { await logger.LogInformation($"Calling {actionName}.\nCorrelation Id: {correlationId}.\nParams: {args}."); TResult result = await action(); return result; } catch (Exception ex) { completedWithError = true; await logger.LogException($"Calling Error {actionName}.\nCorrelation Id: {correlationId}.\nParams: {args}.\nExecution time: {stopwatch.Elapsed.TotalSeconds} sec.", ex); throw; } finally { string errorExist = completedWithError ? "with errors." : "without errors."; await logger.LogInformation($"Calling completed {actionName} {errorExist}.\nCorrelation Id: {correlationId}.\nParams: {args}.\nExecution time: {stopwatch.Elapsed.TotalSeconds} sec."); } } } }