示例#1
0
        public Task PublishCumulativeTelemetryAsync()
        {
            try
            {
                lock (publishLockNode)
                {
                    var ciEvent = new CustomerIntelligenceEvent
                    {
                        Area       = Area,
                        Feature    = CumulativeTelemetryFeatureName,
                        Properties = _properties.ToDictionary(entry => entry.Key, entry => entry.Value)
                    };

                    // This is to ensure that the single ci event is never fired more than once.
                    _properties.Clear();

                    return(_httpClient.PublishEventsAsync(new[] { ciEvent }));
                }
            }
            catch (Exception e)
            {
                _logger.Verbose($"TelemetryDataCollector : PublishCumulativeTelemetryAsync : Failed to publish telemtry due to {e}");
            }

            return(Task.CompletedTask);
        }
示例#2
0
        public async Task TransitionToState(IState state)
        {
            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }
            _traceLogger.Verbose($"Entering '{state.Id}' state.");
            await _inner.TransitionToState(state).ConfigureAwait(false);

            _traceLogger.Verbose($"Entered '{state.Id}' state.");
        }
示例#3
0
            public async Task UpdateProjection()
            {
                // Fake update the projection
                _traceLogger.Verbose("Refreshing projection...");
                await Task.Delay(_updateDuration).ConfigureAwait(false);

                foreach (var department in _projection)
                {
                    department.ProjectionTime = _systemClock.UtcNow;
                }
                _refreshCount++;
                _traceLogger.Verbose($"Refreshed projection for the {RefreshCount}th time.");
            }
示例#4
0
        private void CommandsSource_OnLogMessageCommand(Shared.Execution.ILogContext logContext, Shared.Extensibility.Commands.CommandArgs.LogMessageCommandArgs args)
        {
            var rootScope = Context.Current.Log.Root;

            TraceLogger.Verbose($"Handling log message for {rootScope.GetHashCode()} root scope...");

            var logScope = args.LogScope;

            if (_outputHelperMap.TryGetValue(rootScope, out ITestOutputHelper output))
            {
                var logRequest = args.LogMessage.ConvertToRequest();

                var sharedLogMessage = new AddLogCommunicationMessage
                {
                    ParentScopeId = logScope?.Id,
                    Level         = logRequest.Level,
                    Time          = logRequest.Time,
                    Text          = logRequest.Text
                };

                if (logRequest.Attach != null)
                {
                    sharedLogMessage.Attach = new Attach(logRequest.Attach.MimeType, logRequest.Attach.Data);
                }

                NotifyAgent(output, Client.Converters.ModelSerializer.Serialize <AddLogCommunicationMessage>(sharedLogMessage));
            }
        }
示例#5
0
        public override Task <Empty> NotifyExecutionStarting(ExecutionStartingRequest request, ServerCallContext context)
        {
            try
            {
                TraceLogger.Info($"{nameof(NotifyExecutionStarting)} received");
                TraceLogger.Verbose(System.Text.Json.JsonSerializer.Serialize(request));

                if (request.SuiteResult != null)
                {
                    _sender.StartLaunch(request);
                }
            }
            catch (Exception exp)
            {
                TraceLogger.Error(exp.ToString());
            }

            return(Task.FromResult(new Empty()));
        }
示例#6
0
        public ReportPortalLogger()
        {
            var testLoggerDirectory = Path.GetDirectoryName(new Uri(typeof(ReportPortalLogger).Assembly.CodeBase).LocalPath);

            TraceLogger = TraceLogManager.Instance.WithBaseDir(testLoggerDirectory).GetLogger(typeof(ReportPortalLogger));

            TraceLogger.Verbose($"This test logger base directory: {testLoggerDirectory}");

            // Seems Visual Studio Test Host  for net core uses built-in vstestconsole for netcoreapp1.0
            System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12;

            var jsonPath = Path.Combine(testLoggerDirectory, "ReportPortal.config.json");

            _configBuilder = new ConfigurationBuilder().AddJsonFile(jsonPath).AddEnvironmentVariables();

            _statusMap[TestOutcome.Passed]   = Status.Passed;
            _statusMap[TestOutcome.Failed]   = Status.Failed;
            _statusMap[TestOutcome.Skipped]  = Status.Skipped;
            _statusMap[TestOutcome.NotFound] = Status.Skipped;
        }
示例#7
0
        static async Task Main(string[] args)
        {
            var gaugeProjectRoot = Environment.GetEnvironmentVariable("GAUGE_PROJECT_ROOT") ?? Environment.CurrentDirectory;
            var gaugeLogsDir     = Environment.GetEnvironmentVariable("logs_directory") ?? "";

            var internalTraceLogginDir = Path.Combine(gaugeProjectRoot, gaugeLogsDir);

            TraceLogger = TraceLogManager.Instance.WithBaseDir(internalTraceLogginDir).GetLogger <Program>();

            var envVariables = Environment.GetEnvironmentVariables();

            foreach (var envVariableKey in envVariables.Keys)
            {
                TraceLogger.Verbose($"{envVariableKey}: {envVariables[envVariableKey]}");
            }

            using (var host = CreateHostBuilder(args).Build())
            {
                await host.StartAsync();

                await host.WaitForShutdownAsync(ShutDownCancelationSource.Token);
            }
        }
示例#8
0
        static async Task Main(string[] args)
        {
            var gaugeProjectRoot = Environment.GetEnvironmentVariable("GAUGE_PROJECT_ROOT");
            var gaugeLogsDir     = Environment.GetEnvironmentVariable("logs_directory");

            var internalTraceLogginDir = Path.Combine(gaugeProjectRoot, gaugeLogsDir);

            TraceLogger = TraceLogManager.Instance.WithBaseDir(internalTraceLogginDir).GetLogger <Program>();

            var envVariables = Environment.GetEnvironmentVariables();

            foreach (var envVariableKey in envVariables.Keys)
            {
                TraceLogger.Verbose($"{envVariableKey}: {envVariables[envVariableKey]}");
            }

            var configuration = new ConfigurationBuilder()
                                .Add(new EnvironmentVariablesConfigurationProvider("RP_", "_", EnvironmentVariableTarget.Process))
                                .Build();

            var rpUri            = configuration.GetValue <string>("Uri");
            var rpProject        = configuration.GetValue <string>("Project");
            var rpApiToken       = configuration.GetValue <string>("Uuid");
            var apiClientService = new Service(new Uri(rpUri), rpProject, rpApiToken);

            var sender = new Sender(apiClientService, configuration);

            var channelOptions = new List <ChannelOption> {
                new ChannelOption(ChannelOptions.MaxReceiveMessageLength, -1)
            };

            var server = new Server(channelOptions);

            ServerServiceDefinition messagesHandlerService;

            if (configuration.GetValue("Enabled", true))
            {
                messagesHandlerService = Reporter.BindService(new ReportMessagesHandler(server, sender));
            }
            else
            {
                messagesHandlerService = Reporter.BindService(new EmptyMessagesHandler(server));
            }
            server.Services.Add(messagesHandlerService);

            var gaugePort = server.Ports.Add(new ServerPort("localhost", 0, ServerCredentials.Insecure));

            server.Start();

            Console.Write($"Listening on port:{gaugePort}");

            TraceLogger.Info("Server has started.");

            await server.ShutdownTask;



            //var rpUri = new Uri(Config.GetValue<string>("Uri"));
            //var rpProject = Config.GetValue<string>("Project");
            //var rpUuid = Config.GetValue<string>("Uuid");

            //var service = new Service(rpUri, rpProject, rpUuid);
            //var launchReporter = new LaunchReporter(service, Config, null);

            //var tcpClientWrapper = new TcpClientWrapper(Gauge.CSharp.Core.Utils.GaugeApiPort);
            //using (var gaugeConnection = new GaugeConnection(tcpClientWrapper))
            //{
            //    while (gaugeConnection.Connected)
            //    {
            //        try
            //        {
            //            TraceLogger.Verbose($"Reading message...");

            //            var messageBytes = gaugeConnection.ReadBytes();
            //            TraceLogger.Verbose($"Read message. Length: {messageBytes.Count()}");

            //            var message = Message.Parser.ParseFrom(messageBytes.ToArray());
            //            TraceLogger.Verbose($"Received event {message.MessageType}");

            //            //if (message.MessageType == Message.Types.MessageType.SuiteExecutionResult)
            //            //{
            //            //    var suiteExecutionResult = message.SuiteExecutionResult.SuiteResult;

            //            //    var launchStartDateTime = DateTime.UtcNow.AddMilliseconds(-suiteExecutionResult.ExecutionTime);
            //            //    launchReporter.Start(new Client.Requests.StartLaunchRequest
            //            //    {
            //            //        Name = Config.GetValue("Launch:Name", suiteExecutionResult.ProjectName),
            //            //        Description = Config.GetValue("Launch:Description", string.Empty),
            //            //        Tags = Config.GetValues("Launch:Tags", new List<string>()).ToList(),
            //            //        StartTime = launchStartDateTime
            //            //    });

            //            //    foreach (var specResult in suiteExecutionResult.SpecResults)
            //            //    {
            //            //        var specStartTime = launchStartDateTime;
            //            //        var specReporter = launchReporter.StartChildTestReporter(new Client.Requests.StartTestItemRequest
            //            //        {
            //            //            Type = Client.Models.TestItemType.Suite,
            //            //            Name = specResult.ProtoSpec.SpecHeading,
            //            //            Description = string.Join("", specResult.ProtoSpec.Items.Where(i => i.ItemType == ProtoItem.Types.ItemType.Comment).Select(c => c.Comment.Text)),
            //            //            StartTime = specStartTime,
            //            //            Tags = specResult.ProtoSpec.Tags.Select(t => t.ToString()).ToList()
            //            //        });

            //            //        foreach (var scenarioResult in specResult.ProtoSpec.Items.Where(i => i.ItemType == ProtoItem.Types.ItemType.Scenario || i.ItemType == ProtoItem.Types.ItemType.TableDrivenScenario))
            //            //        {
            //            //            ProtoScenario scenario;

            //            //            switch (scenarioResult.ItemType)
            //            //            {
            //            //                case ProtoItem.Types.ItemType.Scenario:
            //            //                    scenario = scenarioResult.Scenario;
            //            //                    break;
            //            //                case ProtoItem.Types.ItemType.TableDrivenScenario:
            //            //                    scenario = scenarioResult.TableDrivenScenario.Scenario;
            //            //                    break;
            //            //                default:
            //            //                    scenario = scenarioResult.Scenario;
            //            //                    break;
            //            //            }

            //            //            var scenarioStartTime = specStartTime;
            //            //            var scenarioReporter = specReporter.StartChildTestReporter(new Client.Requests.StartTestItemRequest
            //            //            {
            //            //                Type = Client.Models.TestItemType.Step,
            //            //                StartTime = scenarioStartTime,
            //            //                Name = scenario.ScenarioHeading,
            //            //                Description = string.Join("", scenario.ScenarioItems.Where(i => i.ItemType == ProtoItem.Types.ItemType.Comment).Select(c => c.Comment.Text)),
            //            //                Tags = scenario.Tags.Select(t => t.ToString()).ToList()
            //            //            });

            //            //            // internal log ("rp_log_enabled" property)
            //            //            if (Config.GetValue("log:enabled", false))
            //            //            {
            //            //                scenarioReporter.Log(new Client.Requests.AddLogItemRequest
            //            //                {
            //            //                    Text = "Spec Result Proto",
            //            //                    Level = Client.Models.LogLevel.Trace,
            //            //                    Time = DateTime.UtcNow,
            //            //                    Attach = new Client.Models.Attach("Spec", "application/json", System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(specResult)))
            //            //                });
            //            //                scenarioReporter.Log(new Client.Requests.AddLogItemRequest
            //            //                {
            //            //                    Text = "Scenario Result Proto",
            //            //                    Level = Client.Models.LogLevel.Trace,
            //            //                    Time = DateTime.UtcNow,
            //            //                    Attach = new Client.Models.Attach("Scenario", "application/json", System.Text.Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(scenarioResult)))
            //            //                });
            //            //            }

            //            //            var lastStepStartTime = scenarioStartTime;
            //            //            if (scenario.ScenarioItems != null)
            //            //            {
            //            //                foreach (var stepResult in scenario.ScenarioItems.Where(i => i.ItemType == ProtoItem.Types.ItemType.Step))
            //            //                {
            //            //                    var text = "!!!MARKDOWN_MODE!!!" + stepResult.Step.ActualText;
            //            //                    var stepLogLevel = stepResult.Step.StepExecutionResult.ExecutionResult.Failed ? Client.Models.LogLevel.Error : Client.Models.LogLevel.Info;

            //            //                    // if step argument is table
            //            //                    var tableParameter = stepResult.Step.Fragments.FirstOrDefault(f => f.Parameter?.Table != null)?.Parameter.Table;
            //            //                    if (tableParameter != null)
            //            //                    {
            //            //                        text += Environment.NewLine + Environment.NewLine + "| " + string.Join(" | ", tableParameter.Headers.Cells.ToArray()) + " |";
            //            //                        text += Environment.NewLine + "| " + string.Join(" | ", tableParameter.Headers.Cells.Select(c => "---")) + " |";

            //            //                        foreach (var tableRow in tableParameter.Rows)
            //            //                        {
            //            //                            text += Environment.NewLine + "| " + string.Join(" | ", tableRow.Cells.ToArray()) + " |";
            //            //                        }
            //            //                    }

            //            //                    // if dynamic arguments
            //            //                    var dynamicParameteres = stepResult.Step.Fragments.Where(f => f.FragmentType == Fragment.Types.FragmentType.Parameter && f.Parameter.ParameterType == Parameter.Types.ParameterType.Dynamic).Select(f => f.Parameter);
            //            //                    if (dynamicParameteres.Count() != 0)
            //            //                    {
            //            //                        text += Environment.NewLine;

            //            //                        foreach (var dynamicParameter in dynamicParameteres)
            //            //                        {
            //            //                            text += $"{Environment.NewLine}{dynamicParameter.Name}: {dynamicParameter.Value}";
            //            //                        }
            //            //                    }

            //            //                    if (stepResult.Step.StepExecutionResult.ExecutionResult.Failed)
            //            //                    {
            //            //                        text += $"{Environment.NewLine}{Environment.NewLine}{stepResult.Step.StepExecutionResult.ExecutionResult.ErrorMessage}{Environment.NewLine}{stepResult.Step.StepExecutionResult.ExecutionResult.StackTrace}";
            //            //                    }

            //            //                    scenarioReporter.Log(new Client.Requests.AddLogItemRequest
            //            //                    {
            //            //                        Level = stepLogLevel,
            //            //                        Time = lastStepStartTime,
            //            //                        Text = text
            //            //                    });

            //            //                    if (stepResult.Step.StepExecutionResult.ExecutionResult.ScreenShot?.Length != 0)
            //            //                    {
            //            //                        scenarioReporter.Log(new Client.Requests.AddLogItemRequest
            //            //                        {
            //            //                            Level = Client.Models.LogLevel.Debug,
            //            //                            Time = lastStepStartTime,
            //            //                            Text = "Screenshot",
            //            //                            Attach = new Client.Models.Attach("Screenshot", "image/png", stepResult.Step.StepExecutionResult.ExecutionResult.ScreenShot.ToByteArray())
            //            //                        });
            //            //                    }

            //            //                    lastStepStartTime = lastStepStartTime.AddMilliseconds(stepResult.Step.StepExecutionResult.ExecutionResult.ExecutionTime);
            //            //                }
            //            //            }

            //            //            scenarioReporter.Finish(new Client.Requests.FinishTestItemRequest
            //            //            {
            //            //                EndTime = scenarioStartTime.AddMilliseconds(scenario.ExecutionTime),
            //            //                Status = _statusMap[scenario.ExecutionStatus]
            //            //            });
            //            //        }

            //            //        var specFinishStatus = specResult.Failed ? Client.Models.Status.Failed : Client.Models.Status.Passed;
            //            //        specReporter.Finish(new Client.Requests.FinishTestItemRequest
            //            //        {
            //            //            Status = specFinishStatus,
            //            //            EndTime = specStartTime.AddMilliseconds(specResult.ExecutionTime)
            //            //        });
            //            //    }

            //            //    launchReporter.Finish(new Client.Requests.FinishLaunchRequest
            //            //    {
            //            //        EndTime = DateTime.UtcNow
            //            //    });
            //            //}

            //            if (message.MessageType == Message.Types.MessageType.KillProcessRequest)
            //            {
            //                Console.Write("Finishing to send results to Report Portal... ");
            //                var sw = Stopwatch.StartNew();
            //                launchReporter.Sync();

            //                Console.WriteLine($"Elapsed: {sw.Elapsed}");

            //                return;
            //            }
            //        }
            //        catch (Exception exp)
            //        {
            //            TraceLogger.Error($"Unhandler error: {exp}");
            //        }
            //    }
            //}
        }
示例#9
0
        public void FormatLog(CreateLogItemRequest logRequest)
        {
            _traceLogger.Verbose("Received a log request to format.");

            var handled = false;

            var fullMessageBuilder = Config.GetValue("Extensions:SourceBack:WithMarkdownPrefix", false) ? new StringBuilder("!!!MARKDOWN_MODE!!!") : new StringBuilder();

            if (logRequest.Level == LogLevel.Error || logRequest.Level == LogLevel.Fatal)
            {
                _traceLogger.Info($"Parsing exception stacktrace in log message with {logRequest.Level} level...");

                foreach (var line in logRequest.Text.Split(new string[] { Environment.NewLine, "\n" }, StringSplitOptions.None))
                {
                    _traceLogger.Verbose("Parsing line as stacktrace frame:" + Environment.NewLine + line);

                    var lineWithoutMarkdown = line.Replace("`", @"\`").Replace("__", @"\__");

                    var match = Regex.Match(line, @"\s+\w+\s.*\s\w+\s(.*):\w+\s(\d+)");

                    if (match.Success)
                    {
                        var sourcePath = match.Groups[1].Value;
                        var lineIndex  = int.Parse(match.Groups[2].Value) - 1;

                        _traceLogger.Info($"It matches stacktrace. SourcePath: {sourcePath} - LineIndex: {lineIndex}");

                        var sectionBuilder = new StringBuilder();

                        try
                        {
                            lock (_pdbsLock)
                            {
                                if (_pdbs == null)
                                {
                                    _pdbs = new List <PdbFileInfo>();

                                    var currentDirectory = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)).FullName;

                                    _traceLogger.Verbose($"Exploring {currentDirectory} directory for PDB files");

                                    var pdbFilePaths = DirectoryScanner.FindPdbPaths(currentDirectory);

                                    foreach (var pdbFilePath in pdbFilePaths)
                                    {
                                        var pdbFileInfo = new PdbFileInfo(pdbFilePath);

                                        try
                                        {
                                            pdbFileInfo.LoadSourceLinks();
                                        }
                                        catch (NotSupportedException exp)
                                        {
                                            _traceLogger.Warn($"{pdbFilePath} format is not supported. Try to change it to 'portable' or 'embedded'. {Environment.NewLine}{exp}");
                                        }

                                        _pdbs.Add(pdbFileInfo);
                                    }
                                }
                            }

                            var pdb = _pdbs.FirstOrDefault(p => p.SourceLinks.ContainsKey(sourcePath));

                            // if defined
                            if (pdb != null)
                            {
                                var content = pdb.GetSourceLinkContent(sourcePath);

                                // if available
                                if (content != null)
                                {
                                    var contentLines = content.Replace("\r\n", "\n").Split(new string[] { "\n" }, StringSplitOptions.None);

                                    // up
                                    var offsetUp             = Config.GetValue("Extensions:SourceBack:OffsetUp", 4);
                                    var takeFromIndex        = lineIndex - offsetUp;
                                    var missingTopLinesCount = 0;
                                    if (takeFromIndex < 0)
                                    {
                                        missingTopLinesCount = Math.Abs(takeFromIndex);
                                        takeFromIndex        = 0;
                                    }

                                    // down
                                    var offsetDown  = Config.GetValue("Extensions:SourceBack:OffsetDown", 2);
                                    var takeToIndex = lineIndex + offsetDown;
                                    if (takeToIndex > contentLines.Length - 1)
                                    {
                                        takeToIndex = contentLines.Length - 1;
                                    }

                                    // and add whitespace to replace it with ►
                                    var frameContentLines = contentLines.Skip(takeFromIndex + 1).Take(takeToIndex - takeFromIndex).Select(l => " " + l).ToList();

                                    var hightlightFrameLineIndex = offsetUp - missingTopLinesCount - 1;
                                    frameContentLines[hightlightFrameLineIndex] = "►" + frameContentLines[hightlightFrameLineIndex].Remove(0, 1);
                                    var frameContent = string.Join(Environment.NewLine, frameContentLines);

                                    sectionBuilder.AppendLine($"```{Environment.NewLine}{frameContent}{Environment.NewLine}```");
                                }
                            }
                        }
                        catch (Exception exp)
                        {
                            sectionBuilder.AppendLine($"```{Environment.NewLine}SourceBack error: {exp}{Environment.NewLine}```");
                        }

                        handled = true;

                        if (!string.IsNullOrEmpty(sectionBuilder.ToString()))
                        {
                            var sourceFileName   = Path.GetFileName(sourcePath);
                            var lineWithEditLink = lineWithoutMarkdown.Replace("\\" + sourceFileName, $"\\\\**{sourceFileName}**");
                            lineWithEditLink = lineWithEditLink.Remove(lineWithEditLink.Length - match.Groups[2].Value.Length);

                            var openWith = Config.GetValue("Extensions:SourceBack:OpenWith", "vscode");
                            switch (openWith.ToLowerInvariant())
                            {
                            case "vscode":
                                lineWithEditLink += $"[{match.Groups[2].Value}](vscode://file/{sourcePath.Replace("\\", "/")}:{lineIndex + 1})";
                                break;
                            }

                            fullMessageBuilder.AppendLine($"{lineWithEditLink}{Environment.NewLine}{sectionBuilder}");
                        }
                        else
                        {
                            fullMessageBuilder.AppendLine(lineWithoutMarkdown);
                        }
                    }
                    else
                    {
                        fullMessageBuilder.AppendLine(lineWithoutMarkdown);
                    }
                }
            }

            if (handled)
            {
                logRequest.Text = fullMessageBuilder.ToString();
            }
        }