Ejemplo n.º 1
0
        public void AddNewTracerConfigToSameWriterAfterStarting()
        {
            var setupTracerFactory = new SetupLog();
            var logWriter          = new ListLogWriter <TraceEntry>(setupTracerFactory);

            var config = new TraceManagerConfig();

            config.UseLogWriter(logWriter, "A"); // Only logs for tracer A

            TraceManager traceManager;

            using (traceManager = new TraceManager(config, setupTracerFactory))
            {
                var tracerA = traceManager.GetTracer("A");
                var tracerB = traceManager.GetTracer("B");
                Assert.True(traceManager.IsStarted);

                Assert.True(tracerA.IsInfoEnabled());
                Assert.False(tracerB.IsInfoEnabled());

                // For option 1, see the previous test: ConfigCanBeChangedAfterStarting

                // Option 2: Add a new TraceWriterConfig, and restart, to enable B
                config.UseLogWriter(logWriter, "B", new OnOffTraceSwitch(true));
                Assert.False(tracerB.IsInfoEnabled()); // before the restart, tracerB is disabled
                traceManager.Start();

                Assert.True(tracerB.IsInfoEnabled());
                Assert.True(tracerB.IsDebugEnabled());
            }
        }
Ejemplo n.º 2
0
        public void RootThresholdCanBeModifiedAfterTracing()
        {
            var setupTracerFactory = new SetupLog();
            var listLogWriter      = new ListLogWriter <TraceEntry>(setupTracerFactory);

            // Start with threshold == Info
            var traceSwitch = new ThresholdTraceSwitch(TraceLevel.Info);

            using (var traceManager = new TraceManager(listLogWriter, traceSwitch))
            {
                traceManager.Start();
                var tracer = traceManager.TracerFor(this);

                // Log stuff
                tracer.Info("Info");       // Should log
                tracer.Verbose("Verbose"); // Shouldn't log
                Assert.Single(listLogWriter);

                // Change threshold
                traceSwitch.Threshold = TraceLevel.Verbose;

                // Log
                tracer.Info("Info");
                tracer.Verbose("Verbose"); // Should log
                tracer.Debug("Debug");     // Shouldn't log
                Assert.Equal(3, listLogWriter.Count());
            }
        }
Ejemplo n.º 3
0
        public void ParallelRequestsWithTracing()
        {
            var setupLog     = new SetupLog();
            var stringWriter = new StringWriter();

            using (TestServer testServer = CreateTestServer(stringWriter, setupLog))
            {
                // 10 parallel threads, each thread issues 2 requests, each request traces 2x
                Action issueRequestAction = () =>
                {
                    IssueTraceRequest(testServer, 2);
                    IssueTraceRequest(testServer, 2);
                };
                Parallel.Invoke(Enumerable.Repeat(issueRequestAction, 10).ToArray());
            }

            string logOutput = stringWriter.ToString();

            testOutputHelper.WriteLine(logOutput);

            int countLineBreaks = TestHelper.CountLineBreaks(logOutput);

            Assert.True(countLineBreaks > 140 && countLineBreaks < 180);

            Assert.NotEmpty(setupLog);
            Assert.False(setupLog.HasAnyExceeding(TraceLevel.Info));
        }
Ejemplo n.º 4
0
        //[InlineData(40, 1000, 30)]
        public void ParallelTraceTest(int threads, int requestsPerThread, int tracesPerRequest)
        {
            var       setupLog         = new SetupLog();
            Stopwatch overallStopwatch = Stopwatch.StartNew();

            // Test logging to TextWriter.Null - which should have no perf overhead
            using (TestServer testServer = CreateTestServer(TextWriter.Null, setupLog))
            {
                Action testThread = () =>
                {
                    int threadId = Thread.CurrentThread.ManagedThreadId;
                    testOutputHelper.WriteLine("{0}: Starting requests on thread {1}", overallStopwatch.Elapsed, threadId);
                    var stopWatch = Stopwatch.StartNew();

                    for (int i = 0; i < requestsPerThread; ++i)
                    {
                        IssueTraceRequest(testServer, tracesPerRequest);
                    }
                    stopWatch.Stop();

                    testOutputHelper.WriteLine("{0}: Completed {1} requests on thread {2} in {3}",
                                               overallStopwatch.Elapsed,
                                               requestsPerThread,
                                               threadId,
                                               stopWatch.Elapsed);
                };

                Parallel.Invoke(Enumerable.Repeat(testThread, threads).ToArray());
            }

            Assert.NotEmpty(setupLog);
            Assert.False(setupLog.HasAnyExceeding(TraceLevel.Info));
        }
        public BackgroundMultiLogWriterUnitTests(ITestOutputHelper testOutputHelper)
        {
            Contract.Requires <ArgumentNullException>(testOutputHelper != null);

            _testOutputHelper = testOutputHelper;
            SetupLog          = new SetupLog();
        }
Ejemplo n.º 6
0
        public void TracerNamesForGenericTypes()
        {
            var tracerFactory = new SetupLog();

            // ListLogWriter<MessageEntry> handling (generic type parameter)
            var tracer1 = tracerFactory.GetTracer(typeof(ListLogWriter <MessageEntry>));

            _testOutputHelper.WriteLine(tracer1.Name);
            var tracer2 = tracerFactory.GetTracer(typeof(ListLogWriter <>));

            _testOutputHelper.WriteLine(tracer2.Name);
            var tracer3 = tracerFactory.TracerFor(new ListLogWriter <MessageEntry>(new SetupLog()));

            _testOutputHelper.WriteLine(tracer3.Name);
            var tracer4 = tracerFactory.TracerFor <ListLogWriter <MessageEntry> >();

            _testOutputHelper.WriteLine(tracer4.Name);
            var tracer5 = tracerFactory.GetTracer(typeof(ListLogWriter <MessageEntry>).GetGenericTypeDefinition());

            _testOutputHelper.WriteLine(tracer5.Name);

            // PrivateClass.TestLogWriter<MessageEntry> handling (inner class + generic type parameter)
            tracer1 = tracerFactory.GetTracer(typeof(PrivateClass.TestEntryWriter <MessageEntry>));
            _testOutputHelper.WriteLine(tracer1.Name);
            tracer2 = tracerFactory.GetTracer(typeof(PrivateClass.TestEntryWriter <>));
            _testOutputHelper.WriteLine(tracer2.Name);
            tracer3 = tracerFactory.TracerFor(new PrivateClass.TestEntryWriter <MessageEntry>());
            _testOutputHelper.WriteLine(tracer3.Name);
            tracer4 = tracerFactory.TracerFor <PrivateClass.TestEntryWriter <MessageEntry> >();
            _testOutputHelper.WriteLine(tracer4.Name);
            tracer5 = tracerFactory.GetTracer(typeof(PrivateClass.TestEntryWriter <MessageEntry>).GetGenericTypeDefinition());
            _testOutputHelper.WriteLine(tracer5.Name);
        }
Ejemplo n.º 7
0
        public void EnableTracingForSpecificGenericType()
        {
            var setupTracerFactory = new SetupLog();
            var traceConfig        = new TraceWriterConfig(new ListLogWriter <TraceEntry>(setupTracerFactory))
            {
                Switches =
                {
                    { typeof(PrivateClass.TestEntryWriter <MessageEntry>), new OnOffTraceSwitch(true) }
                }
            };

            using (var traceManager = new TraceManager(traceConfig, setupTracerFactory))
            {
                var tracer = traceManager.TracerFor(this);
                Assert.False(tracer.IsInfoEnabled());

                tracer = traceManager.GetTracer(typeof(PrivateClass.TestEntryWriter <>));
                Assert.False(tracer.IsInfoEnabled());

                tracer = traceManager.TracerFor <PrivateClass.TestEntryWriter <MessageEntry> >();
                Assert.True(tracer.IsInfoEnabled());

                tracer = traceManager.TracerFor <PrivateClass.TestEntryWriter <TraceEntry> >();
                Assert.False(tracer.IsInfoEnabled());
            }
        }
Ejemplo n.º 8
0
        public void ConfigCanBeChangedAfterStarting()
        {
            var setupTracerFactory = new SetupLog();
            var logWriter          = new ListLogWriter <TraceEntry>(setupTracerFactory);

            var config = new TraceManagerConfig();
            // TODO: Rename to tracerConfig?
            var traceWriterConfig = config.UseLogWriter(logWriter, "A"); // Only logs for tracer A

            TraceManager traceManager;

            using (traceManager = new TraceManager(config, setupTracerFactory))
            {
                var tracerA = traceManager.GetTracer("A");
                var tracerB = traceManager.GetTracer("B");

                Assert.True(traceManager.IsStarted);
                Assert.True(traceManager.LogManager.IsStarted);

                Assert.True(tracerA.IsInfoEnabled());
                Assert.False(tracerB.IsInfoEnabled());

                // Option 1: Change the config
                traceWriterConfig.Switches.Add("B", new OnOffTraceSwitch(true));
                traceManager.Start(); // Explicit restart required

                Assert.True(tracerB.IsInfoEnabled());
                Assert.True(tracerB.IsDebugEnabled());

                // For option 2, see the next test: AddNewTracerConfigToSameWriterAfterStarting
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Creates a new <see cref="TraceManager" /> instance using the specified <paramref name="configuration" />.
        /// </summary>
        /// <param name="configuration">The <see cref="TraceManagerConfig" /> to use to configure this <c>TraceManager</c>.</param>
        /// <param name="setupLog">The <see cref="SetupTracerFactory" /> to use for tracing setup operations.</param>
        public TraceManager(TraceManagerConfig configuration, SetupLog setupLog = null)
            : this(new LogManager(configuration.LogManagerConfig, setupLog), configuration)
        {
            Contract.Requires <ArgumentNullException>(configuration != null);

            // This TraceManager owns the LogManager, so dispose it on this.Dispose()
            LinkDispose(_logManager);
        }
Ejemplo n.º 10
0
        protected virtual Task PerformBootstrapActionsAsync()
        {
            SetupLog?.Trace("Setup: Bootstrap actions");

            var bootstrapRunner = new MvxBootstrapRunner();

            var tasks = GetBootstrapOwningAssemblies()
                        .Select(ass => Task.Run(() => bootstrapRunner.Run(ass)));

            return(Task.WhenAll(tasks));
        }
Ejemplo n.º 11
0
        public ReflectionFormatterTests(ITestOutputHelper testOutput)
        {
            _testOutput = testOutput;

            _setupLog            = new SetupLog();
            _formatterOutput     = new StringWriter();
            _formatWriter        = new TextWriterFormatWriter(_setupLog, _formatterOutput);
            _reflectionFormatter = new ReflectionFormatter
            {
                // Excluded for most tests, b/c type names make the output messy
                IncludeTypeNames = false
            };
        }
Ejemplo n.º 12
0
        public void SingleRequestWithTracing()
        {
            var setupLog     = new SetupLog();
            var stringWriter = new StringWriter();

            using (TestServer testServer = CreateTestServer(stringWriter, setupLog))
            {
                IssueTraceRequest(testServer, 2);
            }

            testOutputHelper.WriteLine(stringWriter.ToString());

            Assert.NotEmpty(setupLog);
            Assert.False(setupLog.HasAnyExceeding(TraceLevel.Info));
        }
Ejemplo n.º 13
0
        public void WriteLinesStringBuilderWorks(string lines, int indentLevel, string expectedOutput)
        {
            // Prepare
            var setupLog   = new SetupLog();
            var sbOut      = new StringBuilder();
            var textWriter = new StringWriter(sbOut);

            using (var formatWriter = new TextWriterFormatWriter(setupLog, textWriter))
            {
                // Test
                formatWriter.WriteLines(new StringBuilder(lines), relativeIndentLevel: indentLevel);
            }

            // Verify
            Assert.Equal(expectedOutput, sbOut.ToString());
        }
Ejemplo n.º 14
0
        public void ExceptionTracing()
        {
            var setupLog     = new SetupLog();
            var stringWriter = new StringWriter();

            using (TestServer testServer = CreateTestServer(stringWriter, setupLog))
            {
                var task     = testServer.CreateRequest("/exception").GetAsync();
                var response = task.Result; // Wait for the call to complete
            }

            testOutputHelper.WriteLine(stringWriter.ToString());

            Assert.NotEmpty(setupLog);
            Assert.False(setupLog.HasAnyExceeding(TraceLevel.Info));
        }
Ejemplo n.º 15
0
        public void WriteTimeOffsetWorks(double milliseconds, string expectedOutput)
        {
            // Prepare
            var setupLog   = new SetupLog();
            var sbOut      = new StringBuilder();
            var textWriter = new StringWriter(sbOut);

            using (var formatWriter = new TextWriterFormatWriter(setupLog, textWriter))
            {
                // Test
                var timeOffset = TimeSpan.FromMilliseconds(milliseconds);
                formatWriter.WriteTimeOffset(timeOffset, ColorCategory.None);
            }

            // Verify
            Assert.Equal(expectedOutput, sbOut.ToString());
        }
Ejemplo n.º 16
0
        public void LogWriterExceptionsDontPropagate()
        {
            var setupLog           = new SetupLog();
            var exceptionLogWriter = new ExceptionThrowingLogWriter <TraceEntry>(setupLog);
            var listLogWriter      = new ListLogWriter <TraceEntry>(setupLog);

            var traceManager = new TraceManager(setupLog);

            traceManager.Config.Writers.Add(new TraceWriterConfig()
            {
                LogWriterConfig = new UseExistingLogWriterConfig(exceptionLogWriter, disposeOnStop: true),
                Switches        =
                {
                    { Tracer.All, new OnOffTraceSwitch(true) }
                }
            });
            traceManager.Config.Writers.Add(new TraceWriterConfig()
            {
                LogWriterConfig = new UseExistingLogWriterConfig(listLogWriter, disposeOnStop: true),
                Switches        =
                {
                    { Tracer.All, new OnOffTraceSwitch(true) }
                }
            });

            using (traceManager)
            {
                traceManager.Start();

                var tracer = traceManager.TracerFor(this);
                tracer.Info("Info");
                tracer.Warn("Warn");

                Assert.Equal(2, listLogWriter.Count());
                Assert.Equal(2, exceptionLogWriter.CountExceptionsThrown);

                // First write exception is reported in SetupLog
                // TODO: Replace logging to SetupLog with TraceWriter reporting its current status
                Assert.Equal(1, traceManager.SetupLog.Count(traceEntry => traceEntry.TraceLevel >= TraceLevel.Error && traceEntry.Details != null));
            }

            Assert.Equal(3, exceptionLogWriter.CountExceptionsThrown);

            // Exceptions should be reported in the SetupLog
            Assert.Equal(2, traceManager.SetupLog.Count(traceEntry => traceEntry.TraceLevel >= TraceLevel.Error && traceEntry.Details != null));
        }
Ejemplo n.º 17
0
        public void RootLogWriterCanBeSetOnInitialization()
        {
            var setupTracerFactory = new SetupLog();
            // Trace output is written to this guy
            var listLogWriter = new ListLogWriter <TraceEntry>(setupTracerFactory);

            using (var traceManager = new TraceManager(listLogWriter))
            {
                traceManager.Start();
                var tracer = traceManager.TracerFor(this);
                tracer.Info("Info");

                Assert.Single(listLogWriter);
                TraceEntry traceEntry = listLogWriter.First();
                Assert.Equal(GetType().GetCSharpName(), traceEntry.TracerName);
                Assert.Equal(TraceLevel.Info, traceEntry.TraceLevel);
            }
        }
Ejemplo n.º 18
0
        public static void Main(string[] args)
        {
            SetupLog.Log("**********************************************************");
            SetupLog.Log("Initializing App");

            var isService   = !(Debugger.IsAttached || args.Contains("--console"));
            var webHostArgs = args.Where(arg => arg != "--console").ToArray();

            string url           = new UrlConfiguration().GetAppUrl();
            var    configuration = new ConfigurationBuilder()
                                   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                                   .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
                                   .AddJsonFile("appsettings.Production.json", optional: true, reloadOnChange: true)
                                   .Build();

            SetupLog.Log("Url - got - " + url);

            SetupLog.Log("Now buildwebost");

            var pathToExe         = Process.GetCurrentProcess().MainModule.FileName;
            var pathToContentRoot = Path.GetDirectoryName(pathToExe);
            //pathToContentRoot = "";
            var host = BuildWebHost(url, webHostArgs, configuration, pathToContentRoot);

            SetupLog.Log("Host Initialized and running");

            if (isService)
            {
                try
                {
                    host.RunAsService();
                }
                catch (Exception ex)
                {
                    SetupLog.Log("Host Initialized and running" + ex.Message);
                }
            }
            else
            {
                host.Run();
            }

            SetupLog.Log("Host is runinng..");
        }
Ejemplo n.º 19
0
        public void MultiLogWriterToText()
        {
            // Log output written here
            var stringWriter = new StringWriter();

            var setupTracerFactory = new SetupLog();
            EntryFormatAction <LoggingTimer.StartRecord> formatStart = (startRecord, writer) =>
            {
                writer.BeginEntry();
                writer.WriteField((buffer) => buffer.AppendFormat(">{0}", startRecord.TimingId));
                writer.EndEntry();
            };
            EntryFormatAction <LoggingTimer.StopRecord> formatStop = (stopRecord, writer) =>
            {
                writer.BeginEntry();
                writer.WriteField((buffer) => buffer.AppendFormat("<{0}", stopRecord.TimingId));
                writer.WriteField(stopRecord.ElapsedTime.ToString());
                writer.EndEntry();
            };
            var logWriter = new TextLogWriter(setupTracerFactory, new TextWriterFormatWriter(setupTracerFactory, stringWriter))
                            .AddFormat(formatStart)
                            .AddFormat(formatStop);

            using (var logManager = new LogManager(logWriter))
            {
                // LoggingTimer test class logs starts and stops
                LoggingTimer.RestartTimingIds();
                var timer   = new LoggingTimer("test LoggingTimer", logManager);
                var timing1 = timer.Start();
                Thread.Sleep(15);
                timing1.Stop();
                var timing2 = timer.Start();
                Thread.Sleep(10);
                timing2.Stop();
            }

            string logOutput = stringWriter.ToString();

            _testOutputHelper.WriteLine(logOutput);

            Assert.Contains(">2\r\n<2  00:00:00.", logOutput);
            Assert.Contains(">3\r\n<3  00:00:00.", logOutput);
        }
Ejemplo n.º 20
0
        public void SingleRequestWithTracingWith3LogTargets()
        {
            var setupLog     = new SetupLog();
            var stringWriter = new StringWriter();

            using (TestServer testServer = new OwinTestWith3LogTargets(testOutputHelper).CreateTestServer(stringWriter, setupLog, true))
            {
                IssueTraceRequest(testServer, 2);
            }
            testOutputHelper.WriteLine("Logging complete.");

            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine("StringWriter contents:");
            testOutputHelper.WriteLine(stringWriter.ToString());

            Assert.NotEmpty(setupLog);

            testOutputHelper.WriteLine("");
            testOutputHelper.WriteLine("Setup log:");
            testOutputHelper.WriteEntries(setupLog);
            Assert.False(setupLog.HasAnyExceeding(TraceLevel.Info));
        }
Ejemplo n.º 21
0
        public virtual async Task InitializeSecondaryAsync()
        {
            await PerformBootstrapActionsAsync();

            var pluginManager = InitializePluginFramework();

            var app = CreateApp();

            Mvx.RegisterSingleton(app);

            InitializeApp(pluginManager, app);

            await Task.Run(() => InitializeViewsContainer()).ConfigureAwait(false);

            var tasks = new[] {
                Task.Run(() => InitializeStringToTypeParser()),
                Task.Run(() => InitializeCommandHelper()),
                Task.Run(() =>
                {
                    InitializeNavigationService(app);
                    LoadNavigationServiceRoutes();
                }),
                Task.Run(() => InitializeViewModelTypeFinder()),
                Task.Run(() => InitializeViewDispatcher()),
                Task.Run(() => InitializeViewLookup()),
                Task.Run(() => InitializeCommandCollectionBuilder()),
                Task.Run(() => InitializeNavigationSerializer()),
                Task.Run(() => InitializeInpcInterception()),
                Task.Run(() => InitializeViewModelCache())
            };

            await Task.WhenAll(tasks).ConfigureAwait(false);

            InitializeLastChance();

            SetupLog?.Trace("Setup: Secondary end");

            StateWrapper = MvxSetupState.Initialized;
        }
Ejemplo n.º 22
0
        public void MultipleTraceLogWritersForSameNamePrefixWithDifferentSwitchThresholds()
        {
            var setupTracerFactory = new SetupLog();
            var allListLogWriter   = new ListLogWriter <TraceEntry>(setupTracerFactory);
            var errorListLogWriter = new ListLogWriter <TraceEntry>(setupTracerFactory);

            var traceWriterConfigAll = new TraceWriterConfig(allListLogWriter)
            {
                Switches =
                {
                    { "LogJam.UnitTests", new OnOffTraceSwitch(true) }
                }
            };
            var traceWriterConfigErrors = new TraceWriterConfig(errorListLogWriter)
            {
                Switches =
                {
                    { "LogJam.UnitTests", new ThresholdTraceSwitch(TraceLevel.Error) }
                }
            };

            using (var traceManager = new TraceManager(new TraceManagerConfig(traceWriterConfigAll, traceWriterConfigErrors), setupTracerFactory))
            {
                var tracer    = traceManager.TracerFor(this);
                var fooTracer = traceManager.GetTracer("foo");

                tracer.Info("Info");
                tracer.Verbose("Verbose");
                tracer.Error("Error");
                tracer.Severe("Severe");

                // fooTracer shouldn't log to either of these lists
                fooTracer.Severe("foo Severe");

                Assert.Equal(2, errorListLogWriter.Count);
                Assert.Equal(4, allListLogWriter.Count);
            }
        }
Ejemplo n.º 23
0
        public void FinalizerCausesQueuedLogsToFlush()
        {
            var setupLog = new SetupLog();

            // Slow log writer - starting, stopping, disposing, writing an entry, all take at least 10ms each.
            const int opDelayMs              = 5;
            var       slowLogWriter          = new SlowTestLogWriter <MessageEntry>(setupLog, opDelayMs, false);
            const int countLoggingThreads    = 5;
            const int countMessagesPerThread = 5;
            const int expectedEntryCount     = countLoggingThreads * countMessagesPerThread;

            // Run the test code in a delegate so that local variable references can be GCed
            Action logTestMessages = () =>
            {
                var logManager = new LogManager(new LogManagerConfig(), setupLog);
                logManager.Config.UseLogWriter(slowLogWriter).BackgroundLogging = true;
                var entryWriter = logManager.GetEntryWriter <MessageEntry>();

                ExampleHelper.LogTestMessagesInParallel(entryWriter, countMessagesPerThread, countLoggingThreads, _testOutputHelper);

                // Key point: The LogManager is never disposed, and it has a number of queued
                // entries that haven't been written at this point.
            };

            logTestMessages();

            Assert.True(slowLogWriter.Count < expectedEntryCount);

            // Force a GC cyle, and wait for finalizers to complete.
            GC.Collect();
            GC.WaitForPendingFinalizers();

            Assert.Equal(expectedEntryCount, slowLogWriter.Count);

            // When the finalizer is called, an error is logged to the SetupLog.
            Assert.True(setupLog.Any(traceEntry => (traceEntry.TraceLevel == TraceLevel.Error) && (traceEntry.Message.StartsWith("In finalizer "))));
        }
Ejemplo n.º 24
0
        public void LogManagerCanBePassedToTraceManagerCtor()
        {
            var setupLog  = new SetupLog();
            var logConfig = new LogManagerConfig();

            // Just a logwriter that is not used for tracing
            var messageListWriter       = new ListLogWriter <MessageEntry>(setupLog);
            var messageListWriterConfig = logConfig.UseLogWriter(messageListWriter);
            var logManager = new LogManager(logConfig, setupLog);

            // The TraceManagerConfig includes a DebugTraceWriter, which adds to the LogManager.Writers
            using (var traceManager = new TraceManager(logManager, TraceManagerConfig.CreateDebugTraceWriterConfig()))
            {
                traceManager.Start();

                // Starting the TraceManager starts the LogManager
                Assert.True(logManager.IsStarted);

                // There should be two started LogWriters - one is the DebuggerLogWriter for tracing; the other is messageListWriter
                Assert.Equal(2, logManager.Config.Writers.Where(writerConfig => ((IStartable)logManager.GetLogWriter(writerConfig)).IsStarted).Count());

                Assert.True(logManager.IsHealthy); // Ensure no warnings or errors
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Creates a new <see cref="TraceManager" /> instance using the specified <paramref name="traceWriterConfig" />.
 /// </summary>
 /// <param name="traceWriterConfig">The <see cref="TraceWriterConfig" /> to use for this <c>TraceManager</c>.</param>
 /// <param name="setupLog">The <see cref="SetupTracerFactory" /> to use for tracing setup operations.</param>
 public TraceManager(TraceWriterConfig traceWriterConfig, SetupLog setupLog = null)
     : this(new TraceManagerConfig(traceWriterConfig), setupLog)
 {
     Contract.Requires <ArgumentNullException>(traceWriterConfig != null);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Creates a new <see cref="TraceManager" /> instance using default configuration and the specified
 /// <paramref name="setupLog" />.
 /// </summary>
 /// <param name="setupLog"></param>
 public TraceManager(SetupLog setupLog)
     : this(TraceManagerConfig.Default(new LogManagerConfig()), setupLog)
 {
     // TODO: Check for local or remote config?
 }
Ejemplo n.º 27
0
        public TestServer CreateTestServer(TextWriter logTarget, SetupLog setupLog, bool backgroundThreadLogging = true)
        {
            Contract.Requires <ArgumentNullException>(logTarget != null);

            string appName = GetType().FullName;

            return(TestServer.Create(appBuilder =>
            {
                appBuilder.Properties["host.AppName"] = appName;

                // Use the specified setupLog
                appBuilder.RegisterLogManager(new TraceManager(setupLog));

                // Configure logging
                ConfigureLogging(appBuilder, logTarget, backgroundThreadLogging);

                // Run the ExceptionLoggingMiddleware _after_ the Owin.Diagnostics.Error page, which will result in exceptions being
                // logged twice, and results in the Owin.Diagnostis.Error page converting the Exception into a response
                appBuilder.UseErrorPage();
                appBuilder.TraceExceptions(logFirstChance: false, logUnhandled: true);

                // Request handling
                appBuilder.Use(async(owinContext, next) =>
                {
                    IOwinRequest req = owinContext.Request;
                    IOwinResponse res = owinContext.Response;

                    if (req.Path == ExceptionPath)
                    {
                        throw new Exception("Expected exception thrown from /exception URL");
                    }
                    else if (req.Path == TracePath)
                    {
                        string requestUri = req.Uri.ToString();
                        string strTraceCount = req.Query["traceCount"];
                        int traceCount = 3;
                        int.TryParse(strTraceCount, out traceCount);

                        var tracer = owinContext.GetTracerFactory().TracerFor(this);
                        for (int i = 0; i < traceCount; ++i)
                        {
                            tracer.Verbose("{0} #{1}", requestUri, i);
                        }
                    }
                    else if (req.Path == LogJamStatusPath)
                    {
                        res.StatusCode = (int)HttpStatusCode.OK;
                        res.ContentType = "text/plain";
                        var sw = new StringWriter();
                        LogManager logManager = owinContext.GetLogManager();
                        logManager.SetupLog.WriteEntriesTo(sw);
                        res.Write(sw.ToString());
                    }
                    else
                    {
                        await next();
                    }
                });

                logTarget.WriteLine("TestAuthServer configuration complete.");
            }));
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            SetupLog.Log("Configuring log");
            string date = DateTime.UtcNow.ToLongDateString();

            loggerFactory.AddFile($"Logs/{date}.txt");

            SetupLog.Log("Configure log");
            if (env.IsDevelopment())
            {
                //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                //loggerFactory.AddDebug();
                app.UseDeveloperExceptionPage();
            }

            app.Use((r, s) =>
            {
                var headers = r.Request.Headers;
                if (headers.ContainsKey("origin"))
                {
                    string headerOrigin = headers["origin"];
                    Console.WriteLine("Starting Request - from - " + headerOrigin);
                }

                return(s.Invoke());
            })
            ;
            //ServiceStack.Licensing.RegisterLicense(@"provide your license key");

            app.UseCors(builder =>
                        builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                        );

            DefaultFilesOptions options = new DefaultFilesOptions();

            options.DefaultFileNames.Add("index.html");
            options.DefaultFileNames.Add("Index.html");
            app.UseDefaultFiles(options);

            app.UseStaticFiles();
            var scope = app.ApplicationServices.CreateScope();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            var syncService = app.ApplicationServices.GetService <ISyncService>();

            syncService.Timer();

            var myConfiguration  = scope.ServiceProvider.GetRequiredService <MyConfiguration>();
            var identityResolver = scope.ServiceProvider.GetRequiredService <IdentityResolver>();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "CampaignSync Api V2");
            });
            app.UseAuthentication();
            app.UseSimpleTokenProvider(new TokenProviderOptions
            {
                Path               = "/token",
                Audience           = myConfiguration.settings.DefaultSettings.ValidAudience,
                Issuer             = myConfiguration.settings.DefaultSettings.ValidIssuer,
                SigningCredentials = JwtSecurityKey.GetSigningCredentials(),
                IdentityResolver   = identityResolver.CheckUserLogin,
                Expiration         = DateTime.UtcNow.AddDays(30).TimeOfDay
            });


            app.UseMvc();
        }
Ejemplo n.º 29
0
 public override void SetUp()
 {
     SetupLog?.INFO("Start setup method");
 }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            SetupLog.Log("Configuring log");
            string date = DateTime.UtcNow.ToLongDateString();

            loggerFactory.AddFile($"Logs/{date}.txt");

            SetupLog.Log("Configure log");
            if (env.IsDevelopment())
            {
                //loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                //loggerFactory.AddDebug();
                app.UseDeveloperExceptionPage();
            }

            app.Use((r, s) =>
            {
                var headers = r.Request.Headers;
                if (headers.ContainsKey("origin"))
                {
                    string headerOrigin = headers["origin"];
                    Console.WriteLine("Starting Request - from - " + headerOrigin);
                }

                return(s.Invoke());
            });
            ServiceStack.Licensing.RegisterLicense(@"6058-e1JlZjo2MDU4LE5hbWU6Q29uUXN5cyBJVCBQdnQuIEx0ZC4sVHlwZTpPcm1MaXRlQnVzaW5lc3MsSGFzaDpsbHVmU3cxaGtHZ1ZhY2xMTnZkTWxRR0w3Rm5TY3Q2U1oydVhQR3VCQkF1SVZHL1k3TXozZllWZ0Jod25pMlU1VnVDYXBXRUdXOXA2akNGbjE2QXNYMVIyMExyV1FSSHNXdTYxK0dDU2MxU0tzVzNMZzBYK3E5WGFqZzAyL0RwTzJnRzJQSCtxbDE5aytieERVbEd0MTlqRDdtdUFlYjNOcm4wckUxMEhpWU09LEV4cGlyeToyMDE5LTA0LTI1fQ==");
            app.UseCors(builder =>
                        builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                        );

            DefaultFilesOptions options = new DefaultFilesOptions();

            options.DefaultFileNames.Add("index.html");
            options.DefaultFileNames.Add("Index.html");
            app.UseDefaultFiles(options);

            app.UseStaticFiles();
            var scope = app.ApplicationServices.CreateScope();

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();
            var syncService = app.ApplicationServices.GetService <ISyncService>();

            syncService.Timer();

            var myConfiguration  = scope.ServiceProvider.GetRequiredService <MyConfiguration>();
            var identityResolver = scope.ServiceProvider.GetRequiredService <IdentityResolver>();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "LOGISTIC API V2");
            });
            app.UseAuthentication();
            app.UseSimpleTokenProvider(new TokenProviderOptions
            {
                Path               = "/token",
                Audience           = myConfiguration.settings.DefaultSettings.ValidAudience,
                Issuer             = myConfiguration.settings.DefaultSettings.ValidIssuer,
                SigningCredentials = JwtSecurityKey.GetSigningCredentials(),
                IdentityResolver   = identityResolver.CheckUserLogin,
                Expiration         = DateTime.UtcNow.AddDays(30).TimeOfDay
            });


            app.UseMvc();
        }