Exemplo n.º 1
0
        public void ConfigureServices(IServiceCollection services)
        {
            var traceConfig = TraceConfiguration.Create(GetSampleRate(), GetBufferOptions());

            services.AddGoogleTrace(_projectId, traceConfig);
            services.AddMvc();
        }
Exemplo n.º 2
0
        private static TraceConfiguration CreateConfiguration(string outputFilename)
        {
            // Setup the configuration values.
            uint circularBufferMB = 1024; // 1 GB
            uint level            = 5;    // Verbose

            // Create a new instance of EventPipeConfiguration.
            TraceConfiguration config = new TraceConfiguration(outputFilename, circularBufferMB);
            // Setup the provider values.
            // Public provider.
            string providerName = "e13c0d23-ccbc-4e12-931b-d9cc2eee27e4";
            UInt64 keywords     = 0x4c14fccbd;

            // Enable the provider.
            config.EnableProvider(providerName, keywords, level);

            // Private provider.
            providerName = "763fd754-7086-4dfe-95eb-c01a46faf4ca";
            keywords     = 0x4002000b;

            // Enable the provider.
            config.EnableProvider(providerName, keywords, level);

            // Sample profiler.
            providerName = "3c530d44-97ae-513a-1e6d-783e8f8e03a9";
            keywords     = 0x0;

            // Enable the provider.
            config.EnableProvider(providerName, keywords, level);

            return(config);
        }
Exemplo n.º 3
0
        public async Task <ILspLogger> CreateLoggerAsync(string serverTypeName, string?clientName, JsonRpc jsonRpc, CancellationToken cancellationToken)
        {
            var logName = $"Roslyn.{serverTypeName}.{clientName ?? "Default"}.{Interlocked.Increment(ref s_logHubSessionId)}";
            var logId   = new LogId(logName, new ServiceMoniker(typeof(LanguageServerTarget).FullName));

            var serviceContainer = await _asyncServiceProvider.GetServiceAsync <SVsBrokeredServiceContainer, IBrokeredServiceContainer>(_threadingContext.JoinableTaskFactory).ConfigureAwait(false);

            var service = serviceContainer.GetFullAccessServiceBroker();

            var configuration = await TraceConfiguration.CreateTraceConfigurationInstanceAsync(service, ownsServiceBroker : true, cancellationToken).ConfigureAwait(false);

            // Register the default log level as information.
            // Loghub will take care of cleaning up older logs from past sessions / current session
            // if it decides the log file sizes are too large.
            var loggingLevel = SourceLevels.ActivityTracing | SourceLevels.Information;

            var logOptions  = new RpcContracts.Logging.LoggerOptions(new LoggingLevelSettings(loggingLevel));
            var traceSource = await configuration.RegisterLogSourceAsync(logId, logOptions, cancellationToken).ConfigureAwait(false);

            // Associate this trace source with the jsonrpc conduit.  This ensures that we can associate logs we report
            // with our callers and the operations they are performing.
            jsonRpc.ActivityTracingStrategy = new CorrelationManagerTracingStrategy {
                TraceSource = traceSource
            };

            return(new LogHubLspLogger(configuration, traceSource));
        }
        private static async Task <LogHubLspLogger?> CreateLoggerAsync(
            VSShell.IAsyncServiceProvider?asyncServiceProvider,
            string serverTypeName,
            string?clientName,
            JsonRpc jsonRpc,
            CancellationToken cancellationToken)
        {
            if (asyncServiceProvider == null)
            {
                return(null);
            }

            var logName = $"Roslyn.{serverTypeName}.{clientName ?? "Default"}.{Interlocked.Increment(ref s_logHubSessionId)}";
            var logId   = new LogId(logName, new ServiceMoniker(typeof(LanguageServerTarget).FullName));

            var serviceContainer = await VSShell.ServiceExtensions.GetServiceAsync <SVsBrokeredServiceContainer, IBrokeredServiceContainer>(asyncServiceProvider).ConfigureAwait(false);

            var service = serviceContainer.GetFullAccessServiceBroker();

            var configuration = await TraceConfiguration.CreateTraceConfigurationInstanceAsync(service, cancellationToken).ConfigureAwait(false);

            var logOptions  = new RpcContracts.Logging.LoggerOptions(new LoggingLevelSettings(SourceLevels.ActivityTracing | SourceLevels.Information));
            var traceSource = await configuration.RegisterLogSourceAsync(logId, logOptions, cancellationToken).ConfigureAwait(false);

            // Associate this trace source with the jsonrpc conduit.  This ensures that we can associate logs we report
            // with our callers and the operations they are performing.
            jsonRpc.ActivityTracingStrategy = new CorrelationManagerTracingStrategy {
                TraceSource = traceSource
            };

            return(new LogHubLspLogger(configuration, traceSource));
        }
        /// <summary>
        /// Adds the needed services for Google Cloud Tracing. Used with <see cref="UseGoogleTrace"/>.
        /// </summary>
        /// <param name="services">The service collection. Cannot be null.</param>
        /// <param name="projectId">Optional if running on Google App Engine or Google Compute Engine.
        ///     The Google Cloud Platform project ID. If unspecified and running on GAE or GCE the project ID will be
        ///     detected from the platform.</param>
        /// <param name="config">Optional trace configuration, if unset the default will be used.</param>
        /// <param name="client">Optional Trace client, if unset the default will be used.</param>
        /// <param name="traceFallbackPredicate">Optional function to trace requests. If the trace header is not set
        ///     then this function will be called to determine if a given request should be traced.  This will
        ///     not override trace headers. If the function returns true the request will be traced, if false
        ///     is returned the trace will not be traced and if null is returned it will not affect the
        ///     trace decision.</param>
        public static void AddGoogleTrace(
            this IServiceCollection services, string projectId = null,
            TraceConfiguration config = null, TraceServiceClient client = null,
            Func <HttpRequest, bool?> traceFallbackPredicate = null)
        {
            GaxPreconditions.CheckNotNull(services, nameof(services));

            client = client ?? TraceServiceClient.Create();
            config = config ?? TraceConfiguration.Create();

            projectId = CommonUtils.GetAndCheckProjectId(projectId);

            var consumer = ConsumerFactory <TraceProto> .GetConsumer(
                new GrpcTraceConsumer(client), MessageSizer <TraceProto> .GetSize, config.BufferOptions);

            var tracerFactory = new ManagedTracerFactory(projectId, consumer,
                                                         RateLimitingTraceOptionsFactory.Create(config), TraceIdFactory.Create());

            services.AddScoped(CreateTraceHeaderContext);

            services.AddSingleton <IManagedTracerFactory>(tracerFactory);
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddSingleton(CreateManagedTracer);
            services.AddSingleton(CreateTraceHeaderPropagatingHandler);
            services.AddSingleton(new ShouldTraceRequest(traceFallbackPredicate));
        }
Exemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RazorViewEngine"/> class.
 /// </summary>
 /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 /// <param name="assemblyCatalog">An <see cref="IAssemblyCatalog"/> instance.</param>
 public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment, IAssemblyCatalog assemblyCatalog)
 {
     this.razorAssemblyProvider = new RazorAssemblyProvider(configuration, assemblyCatalog);
     this.viewRenderer = new CSharpRazorViewRenderer(this.razorAssemblyProvider);
     this.razorConfiguration = configuration;
     this.traceConfiguration = environment.GetValue<TraceConfiguration>();
     this.AddDefaultNameSpaces(this.viewRenderer.Host);
 }
Exemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RazorViewEngine"/> class.
 /// </summary>
 /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 /// <param name="assemblyCatalog">An <see cref="IAssemblyCatalog"/> instance.</param>
 public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment, IAssemblyCatalog assemblyCatalog)
 {
     this.razorAssemblyProvider = new RazorAssemblyProvider(configuration, assemblyCatalog);
     this.viewRenderer          = new CSharpRazorViewRenderer(this.razorAssemblyProvider);
     this.razorConfiguration    = configuration;
     this.traceConfiguration    = environment.GetValue <TraceConfiguration>();
     this.AddDefaultNameSpaces(this.viewRenderer.Host);
 }
        public CustomBootstrapper()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(RootPathProvider.GetRootPath())
                          .AddJsonFile("appsettings.json")
                          .AddEnvironmentVariables();
            var tracingConfig = new TraceConfiguration(true, true);

            Configuration = builder.Build();
        }
Exemplo n.º 9
0
        private void CreateOutputFilter(TraceConfiguration traceConfiguration)
        {
            #region Create an output condition

            // Create an output category to filter the trace results to only include
            // features with the "Service Point" category assigned
            traceConfiguration.OutputCondition = new CategoryComparison(CategoryOperator.IsEqual, "Service Point");

            #endregion
        }
Exemplo n.º 10
0
        private static async Task <TraceResultsSet> TraceAsync(Client c, string token)
        {
            TraceConfiguration   traceConfiguration = new TraceConfiguration();
            List <TraceLocation> tlList             = new List <TraceLocation>();

            tlList.Add(s_traceLocation);

            string traceLocationList = JsonConvert.SerializeObject(tlList);
            var    result            = c.TraceAsync(token, s_formatParam, s_versioSDE, "", "", s_traceType, traceLocationList, traceConfiguration.ToJson(), s_serverWebAdaptorName, s_utilityNetworkName);

            return(await result);
        }
Exemplo n.º 11
0
        /// <summary> Configures logging middleware to IApplicationBuilder instance </summary>
        /// <param name="app">IApplicationBuilder</param>
        /// <param name="configuration">IConfiguration</param>
        /// <returns>Same IApplicationBuilder instance after configuring LoggingMiddleware</returns>
        public static IApplicationBuilder UseLoggingServices(this IApplicationBuilder app, IHostingEnvironment environment, IConfiguration configuration,
                                                             Microsoft.Extensions.Logging.ILogger logger)
        {
            var traceConfiguration = new TraceConfiguration();

            configuration.Bind(SerilogTrace, traceConfiguration);

            logger.LogInformation(AddingLoggingMiddleware);
            app.UseMiddleware <LoggingMiddleware>(traceConfiguration);
            logger.LogInformation(LoggingMiddlewareAdded);

            return(app);
        }
Exemplo n.º 12
0
        private static TraceConfiguration EventPipeGetConfig(EventSource eventSource, EventKeywords keywords, string outputFile = "default.netperf")
        {
            // Setup the configuration values.
            uint circularBufferMB = 1024; // 1 GB
            uint level            = 5;

            // Create a new instance of EventPipeConfiguration.
            TraceConfiguration config = new TraceConfiguration(outputFile, circularBufferMB);

            // Enable the provider.
            config.EnableProvider(eventSource.Name, (ulong)keywords, level);

            return(config);
        }
Exemplo n.º 13
0
        public LogHubLogger([Import(typeof(SAsyncServiceProvider))] IAsyncServiceProvider2 asyncServiceProvider)
        {
            asyncServiceProvider.GetServiceAsync <SVsBrokeredServiceContainer, IBrokeredServiceContainer>(throwOnFailure: true).ContinueWith(async(t) => {
                var serviceBroker = t.Result.GetFullAccessServiceBroker();
                Assumes.NotNull(serviceBroker);

                // Setup logging using the log hub
                using TraceConfiguration config = await TraceConfiguration.CreateTraceConfigurationInstanceAsync(serviceBroker, false);
                SourceLevels sourceLevels       = SourceLevels.Information | SourceLevels.ActivityTracing;
                LoggerOptions logOptions        = new(
                    requestedLoggingLevel: new LoggingLevelSettings(sourceLevels),
                    privacySetting: PrivacyFlags.MayContainPersonallyIdentifibleInformation | PrivacyFlags.MayContainPrivateInformation);

                this._traceSource = await config.RegisterLogSourceAsync(new LogId("Microsoft.PythonTools", serviceId: null), logOptions, traceSource: null, isBootstrappedService: true, default);
            });
        }
Exemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RazorViewEngine"/> class.
        /// </summary>
        /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment)
        {
            this.viewRenderers = new List<IRazorViewRenderer>
            {
                new CSharpRazorViewRenderer(),
                new VisualBasicRazorViewRenderer()
            };

            this.razorConfiguration = configuration;
            this.traceConfiguration = environment.GetValue<TraceConfiguration>();

            foreach (var renderer in this.viewRenderers)
            {
                this.AddDefaultNameSpaces(renderer.Host);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultStatusCodeHandler"/> type.
        /// </summary>
        /// <param name="responseNegotiator">The response negotiator.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public DefaultStatusCodeHandler(IResponseNegotiator responseNegotiator, INancyEnvironment environment)
        {
            this.errorMessages = new Dictionary<HttpStatusCode, string>
            {
                { HttpStatusCode.NotFound, "The resource you have requested cannot be found." },
                { HttpStatusCode.InternalServerError, "Something went horribly, horribly wrong while servicing your request." }
            };

            this.errorPages = new Dictionary<HttpStatusCode, string>
            {
                { HttpStatusCode.NotFound, LoadResource("404.html") },
                { HttpStatusCode.InternalServerError, LoadResource("500.html") }
            };

            this.responseNegotiator = responseNegotiator;
            this.configuration = environment.GetValue<TraceConfiguration>();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultStatusCodeHandler"/> type.
        /// </summary>
        /// <param name="responseNegotiator">The response negotiator.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public DefaultStatusCodeHandler(IResponseNegotiator responseNegotiator, INancyEnvironment environment)
        {
            this.errorMessages = new Dictionary <HttpStatusCode, string>
            {
                { HttpStatusCode.NotFound, "The resource you have requested cannot be found." },
                { HttpStatusCode.InternalServerError, "Something went horribly, horribly wrong while servicing your request." }
            };

            this.errorPages = new Dictionary <HttpStatusCode, string>
            {
                { HttpStatusCode.NotFound, LoadResource("404.html") },
                { HttpStatusCode.InternalServerError, LoadResource("500.html") }
            };

            this.responseNegotiator = responseNegotiator;
            this.configuration      = environment.GetValue <TraceConfiguration>();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RazorViewEngine"/> class.
        /// </summary>
        /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        /// <param name="assemblyCatalog">An <see cref="IAssemblyCatalog"/> instance.</param>
        public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment, IAssemblyCatalog assemblyCatalog)
        {
            this.viewRenderers = new List <IRazorViewRenderer>
            {
                new CSharpRazorViewRenderer(assemblyCatalog),
                new VisualBasicRazorViewRenderer(assemblyCatalog)
            };

            this.razorConfiguration = configuration;
            this.assemblyCatalog    = assemblyCatalog;
            this.traceConfiguration = environment.GetValue <TraceConfiguration>();

            foreach (var renderer in this.viewRenderers)
            {
                this.AddDefaultNameSpaces(renderer.Host);
            }
        }
Exemplo n.º 18
0
        // [START configure_services_trace]
        public override void Init()
        {
            // [START_EXCLUDE]
            string projectId = ConfigurationManager.AppSettings["projectId"];

            // Confirm that projectId has been changed from placeholder value.
            if (projectId == ("YOUR-PROJECT-ID"))
            {
                throw new Exception("Update Web.config and replace "
                                    + "YOUR-PROJECT-ID with your project id, and recompile.");
            }
            // [END_EXCLUDE]
            base.Init();
            TraceConfiguration traceConfig = TraceConfiguration
                                             .Create(bufferOptions: BufferOptions.NoBuffer());

            CloudTrace.Initialize(this, projectId, traceConfig);
        }
Exemplo n.º 19
0
        void CreateTraceArgument()
        {
            #region Create a Trace Argument

            IReadOnlyList <Element> startingPointList = new List <Element>();

            // Code to fill in list of starting points goes here...

            TraceArgument traceArgument = new TraceArgument(startingPointList);

            TraceConfiguration traceConfiguration = new TraceConfiguration();

            // Code to fill in trace configuration goes here...

            traceArgument.Configuration = traceConfiguration;

            #endregion
        }
Exemplo n.º 20
0
        /// <summary>
        /// Application Monitoring - Configures (prometheus) monitoring middleware to IApplicationBuilder instance
        /// </summary>
        /// <param name="app">IApplicationBuilder instance.</param>
        /// <param name="configuration">IConfiguration instance.</param>
        /// <param name="logger">ILogger instance.</param>
        /// <returns>Same IApplicationBuilder instance after configuring MonitoringMiddleware</returns>
        public static IApplicationBuilder UseMonitoringService(this IApplicationBuilder app, IConfiguration configuration, Microsoft.Extensions.Logging.ILogger logger)
        {
            var traceConfiguration = new TraceConfiguration();

            configuration.Bind(SerilogTrace, traceConfiguration);

            Metrics.SuppressDefaultMetrics();

            var options = new HttpMiddlewareExporterOptions();

            options.RequestDuration.Histogram = Metrics.CreateHistogram("http_request_duration",
                                                                        "The duration of HTTP requests processed by an ASP.NET Core application",
                                                                        new HistogramConfiguration()
            {
                // 500 ms to 2000 ms and infinite buckets
                Buckets              = Histogram.ExponentialBuckets(0.500, 2, 3),
                LabelNames           = new[] { "code", "method", "controller", "action" },
                SuppressInitialValue = true,
            });

            logger.LogInformation(AddingMonitoringMiddleware);

            var pattern = traceConfiguration.ExcludePattern;

            if (options.InProgress.Enabled)
            {
                app.UseMiddleware <HttpMetricsInProgressMiddleware>(options.InProgress.Gauge, pattern);
            }
            if (options.RequestCount.Enabled)
            {
                app.UseMiddleware <HttpMetricsCountMiddleware>(options.RequestCount.Counter, pattern);
            }
            if (options.RequestDuration.Enabled)
            {
                app.UseMiddleware <HttpMetricsDurationMiddleware>(options.RequestDuration.Histogram, pattern);
            }


            app.UseMetricServer();

            logger.LogInformation(MonitoringMiddlewareAdded);

            return(app);
        }
        private static void CreateAndLoadConfigFile(string filename)
        {
            Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            string dir  = Path.GetDirectoryName(config.FilePath);
            string from = Path.Combine(dir, filename);

            if (_configFile == null)
            {
                _configFile = Path.GetFileName(config.FilePath);
                File.Copy(from, _configFile, overwrite: true);
                TraceConfiguration.Register();
                // Do not call Trace.Refresh() here since the first access should be tested without it.
            }
            else
            {
                File.Copy(from, _configFile, overwrite: true);
                Trace.Refresh();
            }
        }
Exemplo n.º 22
0
        private static async Task <TraceResultsSet> TraceAsync(Client c, string token)
        {
            TraceConfiguration   traceConfiguration = new TraceConfiguration();
            List <TraceLocation> tlList             = new List <TraceLocation>();

            tlList.Add(s_traceLocation);
            string traceLocationList = JsonConvert.SerializeObject(tlList);

            Body body = new Body();

            body.F                  = s_formatParam;
            body.GdbVersion         = s_versionSDE;
            body.TraceConfiguration = JsonConvert.SerializeObject(traceConfiguration);
            body.TraceLocations     = tlList.ConvertAll <object>(item => (object)item).ToArray();
            body.TraceType          = s_traceType;

            var result = c.TraceAsync(s_serverWebAdaptorName, s_utilityNetworkName, token, body);

            return(await result);
        }
        /// <summary>
        /// Adds the needed services for Google Cloud Tracing. Used with <see cref="UseGoogleTrace"/>.
        /// </summary>
        /// <param name="services">The service collection. Cannot be null.</param>
        /// <param name="projectId">The Google Cloud Platform project ID. Cannot be null.</param>
        /// <param name="config">Optional trace configuration, if unset the default will be used.</param>
        /// <param name="clientTask">Optional task which produces the Trace client, if
        ///     unset the default will be used.</param>
        public static void AddGoogleTrace(
            this IServiceCollection services, string projectId,
            TraceConfiguration config = null, Task <TraceServiceClient> clientTask = null)
        {
            GaxPreconditions.CheckNotNull(services, nameof(services));
            GaxPreconditions.CheckNotNull(projectId, nameof(projectId));

            clientTask = clientTask ?? TraceServiceClient.CreateAsync();
            config     = config ?? TraceConfiguration.Create();

            IConsumer <TraceProto> consumer = ConsumerFactory <TraceProto> .GetConsumer(
                new GrpcTraceConsumer(clientTask), MessageSizer <TraceProto> .GetSize, config.BufferOptions);

            var tracerFactory = new ManagedTracerFactory(projectId, consumer,
                                                         RateLimitingTraceOptionsFactory.Create(config), TraceIdFactory.Create());

            services.AddSingleton <IManagedTracerFactory>(tracerFactory);
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddScoped(CreateTraceHeaderContext);
            services.AddScoped(CreateManagedTracer);
        }
Exemplo n.º 24
0
        public static TraceConfiguration GetConfig(EventSource eventSource, string outputFile = "default.netperf")
        {
            // Setup the configuration values.
            uint     circularBufferMB = 1024; // 1 GB
            uint     level            = 5;    //(uint)EventLevel.Informational;
            TimeSpan profSampleDelay  = TimeSpan.FromMilliseconds(1);

            // Create a new instance of EventPipeConfiguration.
            TraceConfiguration config = new TraceConfiguration(outputFile, circularBufferMB);
            // Setup the provider values.
            // Public provider.
            string providerName = eventSource.Name;
            UInt64 keywords     = 0xffffffffffffffff;

            // Enable the provider.
            config.EnableProvider(providerName, keywords, level);

            // Set the sampling rate.
            config.SetSamplingRate(profSampleDelay);

            return(config);
        }
Exemplo n.º 25
0
        public async Task <ILspLogger> CreateLoggerAsync(string serverTypeName, string?clientName, JsonRpc jsonRpc, CancellationToken cancellationToken)
        {
            var logName = $"Roslyn.{serverTypeName}.{clientName ?? "Default"}.{Interlocked.Increment(ref s_logHubSessionId)}";
            var logId   = new LogId(logName, new ServiceMoniker(typeof(LanguageServerTarget).FullName));

            var serviceContainer = await VSShell.ServiceExtensions.GetServiceAsync <SVsBrokeredServiceContainer, IBrokeredServiceContainer>(_asyncServiceProvider).ConfigureAwait(false);

            var service = serviceContainer.GetFullAccessServiceBroker();

            var configuration = await TraceConfiguration.CreateTraceConfigurationInstanceAsync(service, cancellationToken).ConfigureAwait(false);

            // Register the default log level as warning to avoid creating log files in the hundreds of GB.
            // This level can be overriden by setting the environment variable 'LogLevel' to the desired source level.
            // See https://dev.azure.com/devdiv/DevDiv/_git/VS?path=%2Fsrc%2FPlatform%2FUtilities%2FImpl%2FLogHub%2FLocalTraceHub.cs&version=GBmain&line=142&lineEnd=143&lineStartColumn=1&lineEndColumn=1&lineStyle=plain&_a=contents
            // This should be switched back to SourceLevels.Information once Loghub adds support for recyclying logs while VS is open.
            // See https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1359778/
            var loggingLevel = SourceLevels.ActivityTracing | SourceLevels.Warning;

            // If VS was explicitly started with /log, then record all information logs as well.
            // This is extremely useful for development so that F5 deployment automatically logs everything.
            var wasVSStartedWithLogParameter = await _wasVSStartedWithLogParameterLazy.GetValueAsync(cancellationToken).ConfigureAwait(false);

            if (wasVSStartedWithLogParameter)
            {
                loggingLevel |= SourceLevels.Information;
            }

            var logOptions  = new RpcContracts.Logging.LoggerOptions(new LoggingLevelSettings(loggingLevel));
            var traceSource = await configuration.RegisterLogSourceAsync(logId, logOptions, cancellationToken).ConfigureAwait(false);

            // Associate this trace source with the jsonrpc conduit.  This ensures that we can associate logs we report
            // with our callers and the operations they are performing.
            jsonRpc.ActivityTracingStrategy = new CorrelationManagerTracingStrategy {
                TraceSource = traceSource
            };

            return(new LogHubLspLogger(configuration, traceSource));
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            // Start the allocator thread.
            //Task t = new Task(new Action(Allocator));
            //t.Start();

            string             outputFilename = string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".netperf";
            TraceConfiguration config         = CreateConfiguration(outputFilename);

            Console.WriteLine("\tStart: Enable tracing.");
            TraceControl.Enable(config);
            Console.WriteLine("\tEnd: Enable tracing.\n");

            Console.WriteLine("\tStart: Allocation.");
            // Allocate for allocIterations iterations.
            for (int i = 0; i < allocIterations; i++)
            {
                GC.KeepAlive(new object());
            }
            Console.WriteLine("\tEnd: Allocation.\n");

            Console.WriteLine("\tStart: Disable tracing.");
            TraceControl.Disable();
            Console.WriteLine("\tEnd: Disable tracing.\n");

            FileInfo outputMeta = new FileInfo(outputFilename);

            Console.WriteLine("\tCreated {0} bytes of data", FileInfo.Length);

            if (keepOutput)
            {
                Console.WriteLine(String.Fromat("\tOutput file: {0}", outputFilename));
            }
            else
            {
                System.IO.File.Delete(outputFilename);
            }
        }
Exemplo n.º 27
0
        public void GetTraceConfiguration_returns_the_correct_trace_configuration_for_given_traceConfigurationId()
        {
            var traceRepositoryMock = new Mock <ITraceRepository>();
            var sut                = new TraceController(traceRepositoryMock.Object, null, null);
            var traceId            = Guid.NewGuid();
            var traceConfiguration = new TraceConfiguration()
            {
                CreationDate = DateTime.Now,
                EndDate      = DateTime.Now.AddMinutes(2),
                Id           = traceId,
                LinkId       = Guid.NewGuid(),
                StartDate    = DateTime.Now
            };

            traceRepositoryMock.Setup(t => t.GetTraceConfiguration(traceId))
            .Returns(traceConfiguration);

            var response = sut.GetTraceConfiguration(traceId) as OkNegotiatedContentResult <TraceConfiguration>;

            traceRepositoryMock.VerifyAll();

            response.Content.Should().BeSameAs(traceConfiguration);
        }
Exemplo n.º 28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // [START configure_services_logging]
            // [START configure_services_error_reporting]
            services.AddOptions();
            services.Configure <StackdriverOptions>(
                Configuration.GetSection("Stackdriver"));
            // [END configure_services_logging]
            services.AddGoogleExceptionLogging(
                Configuration["Stackdriver:ProjectId"],
                Configuration["Stackdriver:ServiceName"],
                Configuration["Stackdriver:Version"]);
            // [END configure_services_error_reporting]

            // [START configure_services_trace]
            // Add trace service.
            TraceConfiguration traceConfig = TraceConfiguration.Create(bufferOptions: BufferOptions.NoBuffer());

            services.AddGoogleTrace(Configuration["Stackdriver:ProjectId"], traceConfig);
            // [END configure_services_trace]

            // Add framework services.
            services.AddMvc();
        }
Exemplo n.º 29
0
        private void CheckConfiguration()
        {
            if (IntegrationOptionsProvider == null)
            {
                return;
            }

            var now = DateTime.Now;

            if (now - configLastChecked < TimeSpan.FromSeconds(10))
            {
                return;
            }

            var integrationOptions = IntegrationOptionsProvider.GetOptions();

            if (traceConfiguration.HasChanged(integrationOptions))
            {
                traceConfiguration = new TraceConfiguration(integrationOptions);
                OnTraceConfigChanged();
            }

            configLastChecked = now;
        }
Exemplo n.º 30
0
        public IHttpActionResult Create(StartTrace startTrace)
        {
            if (startTrace.Minutes < 1)
            {
                return(BadRequest("Tracking must be enabled for one minute at least."));
            }

            if (startTrace.Minutes > 10)
            {
                return(BadRequest("Tracking can only be enabled for ten minutes at most."));
            }

            var traceConfiguration = new TraceConfiguration
            {
                StartDate = DateTime.UtcNow,
                EndDate   = DateTime.UtcNow.AddMinutes(startTrace.Minutes),
                LinkId    = startTrace.LinkId
            };

            _traceRepository.Create(traceConfiguration);

            // TODO: Location
            return(Created("", traceConfiguration));
        }
Exemplo n.º 31
0
        public void Create(TraceConfiguration traceConfiguration)
        {
            using (var context = new RelayContext())
            {
                var link = new DbLink
                {
                    Id = traceConfiguration.LinkId
                };

                context.Links.Attach(link);

                context.TraceConfigurations.Add(new DbTraceConfiguration
                {
                    CreationDate = DateTime.UtcNow,
                    EndDate      = traceConfiguration.EndDate,
                    Id           = Guid.NewGuid(),
                    Link         = link,
                    LinkId       = traceConfiguration.LinkId,
                    StartDate    = traceConfiguration.StartDate
                });

                context.SaveChanges();
            }
        }
Exemplo n.º 32
0
        public void IsRunning_returns_true_when_trace_is_running_and_no_old_trace_is_in_configuration_list()
        {
            var traceRepositoryMock = new Mock <ITraceRepository>();
            var sut                = new TraceController(traceRepositoryMock.Object, null, null);
            var connectionId       = Guid.NewGuid();
            var traceConfiguration = new TraceConfiguration()
            {
                CreationDate = DateTime.Now,
                EndDate      = DateTime.Now.AddMinutes(2),
                Id           = Guid.NewGuid(),
                LinkId       = connectionId,
                StartDate    = DateTime.Now
            };

            traceRepositoryMock.Setup(t => t.GetRunningTranceConfiguration(connectionId))
            .Returns(traceConfiguration);

            var response = sut.IsRunning(connectionId) as OkNegotiatedContentResult <RunningTraceConfiguration>;

            traceRepositoryMock.VerifyAll();

            response.Content.IsRunning.Should().BeTrue();
            response.Content.TraceConfiguration.Should().BeSameAs(traceConfiguration);
        }
Exemplo n.º 33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultRequestTraceFactory"/> class.
 /// </summary>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public DefaultRequestTraceFactory(INancyEnvironment environment)
 {
     this.configuration = environment.GetValue<TraceConfiguration>();
 }
Exemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NancyRazorErrorView"/> class.
 /// </summary>
 /// <param name="message">The message.</param>
 /// <param name="traceConfiguration">A <see cref="TraceConfiguration"/> instance.</param>
 public NancyRazorErrorView(string message, TraceConfiguration traceConfiguration)
 {
     this.traceConfiguration = traceConfiguration;
     this.Message = message;
 }
Exemplo n.º 35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewProcessor"/> class,
 /// with the provided <paramref name="viewFactory"/>.
 /// </summary>
 /// <param name="viewFactory">The view factory that should be used to render views.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public ViewProcessor(IViewFactory viewFactory, INancyEnvironment environment)
 {
     this.viewFactory = viewFactory;
     this.traceConfiguration = environment.GetValue<TraceConfiguration>();
 }
Exemplo n.º 36
0
        private void CheckConfiguration()
        {
            if (IntegrationOptionsProvider == null)
                return;

            var now = DateTime.Now;
            if (now - configLastChecked < TimeSpan.FromSeconds(10))
                return;

            var integrationOptions = IntegrationOptionsProvider.GetOptions();
            if (traceConfiguration.HasChanged(integrationOptions))
            {
                traceConfiguration = new TraceConfiguration(integrationOptions);
                OnTraceConfigChanged();
            }

            configLastChecked = now;
        }
Exemplo n.º 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FavIconApplicationStartup"/> class, with the
 /// provided <see cref="IRootPathProvider"/> instance.
 /// </summary>
 /// <param name="rootPathProvider">The <see cref="IRootPathProvider"/> that should be used to scan for a favicon.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public FavIconApplicationStartup(IRootPathProvider rootPathProvider, INancyEnvironment environment)
 {
     FavIconApplicationStartup.rootPathProvider = rootPathProvider;
     FavIconApplicationStartup.traceConfiguration = environment.GetValue<TraceConfiguration>();
 }
Exemplo n.º 38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewProcessor"/> class,
 /// with the provided <paramref name="viewFactory"/>.
 /// </summary>
 /// <param name="viewFactory">The view factory that should be used to render views.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public ViewProcessor(IViewFactory viewFactory, INancyEnvironment environment)
 {
     this.viewFactory        = viewFactory;
     this.traceConfiguration = environment.GetValue <TraceConfiguration>();
 }
Exemplo n.º 39
0
        /// <summary>
        /// Processes the command line.
        /// </summary>
        /// <param name="ignoreUnknownArguments">if set to <c>true</c> unknown arguments are ignored.</param>
        /// <returns>
        /// True if the arguments were processed; False otherwise.
        /// </returns>
        public bool ProcessCommandLine(bool ignoreUnknownArguments)
        {
            TraceConfiguration config = new TraceConfiguration();
            config.OutputFilePath = "%CommonApplicationData%\\OPC Foundation\\Logs\\Default.InstallLog.txt";
            config.DeleteOnLoad = false;
            config.TraceMasks = 1023;
            config.ApplySettings();

            string[] args =  Environment.GetCommandLineArgs();

            if (args.Length <= 1)
            {
                return false;
            }

            return ProcessCommandLine(ignoreUnknownArguments, args);
        }