Example #1
0
        public void Configure(IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory)
        {
            loggerFactory
                .WithFilter(new FilterLoggerSettings
                {
                    { "Microsoft", LogLevel.Warning },
                    { "System", LogLevel.Warning },
                    { "ToDoApi", LogLevel.Debug }
                })
                .AddConsole();

            // add Trace Source logging
            var testSwitch = new SourceSwitch("sourceSwitch", "Logging Sample");
            testSwitch.Level = SourceLevels.Warning;
            loggerFactory.AddTraceSource(testSwitch,
                new TextWriterTraceListener(writer: Console.Out));

            app.UseStaticFiles();

            app.UseMvc();

            // Create a catch-all response
            app.Run(async (context) =>
            {
                if (context.Request.Path.Value.Contains("boom"))
                {
                    throw new Exception("boom!");
                }
                var logger = loggerFactory.CreateLogger("Catchall Endpoint");
                logger.LogInformation("No endpoint found for request {path}", context.Request.Path);
                await context.Response.WriteAsync("No endpoint found - try /api/todo.");
            });
        }
Example #2
0
        public void ConfigureTraceLogging(IApplicationBuilder app,
            ILoggerFactory loggerFactory)
        {
            loggerFactory.MinimumLevel = LogLevel.Debug;

#if DNX451
            var sourceSwitch = new SourceSwitch("LoggingSample");
            sourceSwitch.Level = SourceLevels.Critical;
            loggerFactory.AddTraceSource(sourceSwitch,
                new ConsoleTraceListener(false));
            loggerFactory.AddTraceSource(sourceSwitch, 
                new EventLogTraceListener("Application"));
#endif

            app.UseRequestLogger();

            app.Run(async context =>
            {
                if (context.Request.Path.Value.Contains("boom"))
                {
                    throw new Exception("boom!");
                }
                await context.Response.WriteAsync("Hello World!");
            });
        }
Example #3
0
        public void Configure(IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(minLevel:LogLevel.Verbose);

            app.UseStaticFiles();

            app.UseMvc();

            // Create a catch-all response
            app.Run(async (context) =>
            {
                var logger = loggerFactory.CreateLogger("Catchall Endpoint");
                logger.LogInformation("No endpoint found for request {path}", context.Request.Path);
                await context.Response.WriteAsync("No endpoint found - try /api/todo.");
            });

            loggerFactory.MinimumLevel = LogLevel.Debug;
#if DNX451
            var sourceSwitch = new SourceSwitch("LoggingSample");
            sourceSwitch.Level = SourceLevels.Critical;
            loggerFactory.AddTraceSource(sourceSwitch,
                new ConsoleTraceListener(false));
            loggerFactory.AddTraceSource(sourceSwitch,
                new EventLogTraceListener("Application"));
#endif

        }
Example #4
0
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="type"></param>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        public static void WriteLog(TraceEventType type, int id, string msg)
        {
            string direct = HttpContext.Current.Server.MapPath("~/Log/Api/");
            if (!Directory.Exists(direct))
                Directory.CreateDirectory(direct);
            string file = direct + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";

            TextWriterTraceListener listen = new TextWriterTraceListener(file);
            listen.TraceOutputOptions = TraceOptions.ProcessId |
                                        TraceOptions.ThreadId |
                                        TraceOptions.Timestamp |
                                        TraceOptions.DateTime |
                                        TraceOptions.LogicalOperationStack;
                                        //TraceOptions.Callstack;

            Trace.Listeners.Add(listen);
            Trace.AutoFlush = false;
            //Trace.WriteLine("Test");

            SourceSwitch sourceSwitch = new SourceSwitch("sourceSwitch");
            sourceSwitch.Level = SourceLevels.Verbose;

            TraceSource traceSource = new TraceSource("traceSource");
            traceSource.Switch = sourceSwitch;
            traceSource.Listeners.Add(listen);

            traceSource.TraceEvent(type, id, msg);
            Trace.Close();
        }
Example #5
0
		public void ConstructorDefault ()
		{
			SourceSwitch s = new SourceSwitch ("foo");
			Assert.AreEqual ("foo", s.DisplayName, "#1");
			Assert.AreEqual (SourceLevels.Off, s.Level, "#2");
			Assert.AreEqual (0, s.Attributes.Count, "#3");
		}
Example #6
0
 public static void SetTraceLevel(LogCategory category, SourceLevels sourceLevel)
 {
     var sourceSwitch = new SourceSwitch(string.Format(CultureInfo.InvariantCulture, "MigSharp.{0}.Switch", category))
     {
         Level = sourceLevel
     };
     Sources[category].Switch = sourceSwitch;
 }
Example #7
0
        public TraceManager(TextWriterTraceListener hostTraceListener)
        {
            //SaveTrees.Logging.Log.CurrentLogger.Debug()("hostTraceListener is null: " + (hostTraceListener == null));
            //SaveTrees.Logging.Log.CurrentLogger.Debug()("hostTraceListener type: " + hostTraceListener?.GetType());

            Switch = new SourceSwitch("SignalRSwitch");
            _hostTraceListener = hostTraceListener;
        }
        public StylizeLogTraceListener()
        {
            this.consoleSwitch = new SourceSwitch("StylizeConsole")
            {
                Level = SourceLevels.Information
            };

            Log.Source.Listeners.Add(this);
        }
Example #9
0
 public DiagnosticsHelper()
 {
     ConfigTraceSwitch = new SourceSwitch("ConfigTrace", "Off");
     WebTraceSwitch = new SourceSwitch("WebTrace", "Off");
     ConfigTrace = new TraceSource("ConfigTrace");
     ConfigTrace.Switch = ConfigTraceSwitch;
     WebTrace = new TraceSource("WebTrace");
     WebTrace.Switch = WebTraceSwitch;
 }
 private void CreateSwitch(string typename, string name)
 {
     if (!string.IsNullOrEmpty(typename))
     {
         this.internalSwitch = (SourceSwitch) TraceUtils.GetRuntimeObject(typename, typeof(SourceSwitch), name);
     }
     else
     {
         this.internalSwitch = new SourceSwitch(name, this.switchLevel.ToString());
     }
 }
Example #11
0
        private Tracing CreateTraceSource(string name)
        {
            SourceSwitch sourceSwitch = Switch;

            TraceLevel sourceTraceLevel;
            if (_traceSetting.DetailTraceSetting.TryGetValue(name, out sourceTraceLevel))
            {
                sourceSwitch = new SourceSwitch("VSTSAgentSubSwitch") 
                {
                    Level = sourceTraceLevel.ToSourceLevels()
                };
            }
            return new Tracing(name, _secretMasker, sourceSwitch, _hostTraceListener);
        }
        public void SetUp()
        {
            var sourceSwitchRegex = new SourceSwitch("SourceSwitchRegex", "Verbose");
            TraceSourceRegex.Switch = sourceSwitchRegex;
            TraceSourceRegex.Listeners.Add(new ConsoleTraceListener());
            TraceSourceRegex.Listeners[0].Name = "console1";
            TraceSourceRegex.Listeners[0].Filter = new KeyFilter("^([0-9]*-[a-zA-Z]*)+$");

            var sourceSwitchLiteral = new SourceSwitch("SourceSwitchLiteral", "Verbose");
            TraceSourceLiteral.Switch = sourceSwitchLiteral;
            TraceSourceLiteral.Listeners.Add(new ConsoleTraceListener());
            TraceSourceLiteral.Listeners[0].Name = "console2";
            TraceSourceLiteral.Listeners[0].Filter = new KeyFilter("10-article");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="TraceSourceLoggerProvider"/> class.
        /// </summary>
        /// <param name="rootSourceSwitch"></param>
        /// <param name="rootTraceListener"></param>
        public TraceSourceLoggerProvider(SourceSwitch rootSourceSwitch, TraceListener rootTraceListener)
        {
            if (rootSourceSwitch == null)
            {
                throw new ArgumentNullException(nameof(rootSourceSwitch));
            }

            if (rootTraceListener == null)
            {
                throw new ArgumentNullException(nameof(rootTraceListener));
            }

            _rootSourceSwitch = rootSourceSwitch;
            _rootTraceListener = rootTraceListener;
        }
Example #14
0
		public void ShouldTrace ()
		{
			SourceSwitch s = new SourceSwitch ("foo");
			s.Level = SourceLevels.Verbose;
			Assert.IsTrue (s.ShouldTrace (TraceEventType.Critical), "#1");
			Assert.IsTrue (s.ShouldTrace (TraceEventType.Error), "#2");
			Assert.IsTrue (s.ShouldTrace (TraceEventType.Warning), "#3");
			Assert.IsTrue (s.ShouldTrace (TraceEventType.Information), "#4");
			Assert.IsTrue (s.ShouldTrace (TraceEventType.Verbose), "#5");
			Assert.IsFalse (s.ShouldTrace (TraceEventType.Start), "#6");
			Assert.IsFalse (s.ShouldTrace (TraceEventType.Stop), "#7");
			Assert.IsFalse (s.ShouldTrace (TraceEventType.Suspend), "#8");
			Assert.IsFalse (s.ShouldTrace (TraceEventType.Resume), "#9");
			Assert.IsFalse (s.ShouldTrace (TraceEventType.Transfer), "#10");
		}
Example #15
0
        public TraceManager(HostTraceListener traceListener, TraceSetting traceSetting, ISecretMasker secretMasker)
        {
            // Validate and store params.
            ArgUtil.NotNull(traceListener, nameof(traceListener));
            ArgUtil.NotNull(traceSetting, nameof(traceSetting));
            ArgUtil.NotNull(secretMasker, nameof(secretMasker));
            _hostTraceListener = traceListener;
            _traceSetting = traceSetting;
            _secretMasker = secretMasker;

            Switch = new SourceSwitch("VSTSAgentSwitch")
            {
                Level = _traceSetting.DefaultTraceLevel.ToSourceLevels()
            };
        }
Example #16
0
		public TraceSource (string name, SourceLevels sourceLevels)
		{
			if (name == null)
				throw new ArgumentNullException ("name");
			Hashtable sources = DiagnosticsConfiguration.Settings ["sources"] as Hashtable;
			TraceSourceInfo info = sources != null ? sources [name] as TraceSourceInfo : null;
			source_switch = new SourceSwitch (name);

			if (info == null)
				listeners = new TraceListenerCollection ();
			else {
				source_switch.Level = info.Levels;
				listeners = info.Listeners;
			}
		}
        static InternalTrace()
        {
            string asmName = typeof(InternalTrace).Assembly.GetName().Name;

            // assemblies are name using xx.xx.xx.platform pattern
            // remove last part of the name

            Name = asmName.Substring(0, asmName.LastIndexOf('.'));

#if DEBUG
            Switch = new SourceSwitch(Name, "Information");
#else
            Switch = new SourceSwitch(Name, "Error");
#endif
        }
Example #18
0
        public Tracing(string name, ISecretMasker secretMasker, SourceSwitch sourceSwitch, HostTraceListener traceListener)
        {
            ArgUtil.NotNull(secretMasker, nameof(secretMasker));
            _secretMasker = secretMasker;
            _traceSource = new TraceSource(name);
            _traceSource.Switch = sourceSwitch;

            // Remove the default trace listener.
            if (_traceSource.Listeners.Count > 0 &&
                _traceSource.Listeners[0] is DefaultTraceListener)
            {
                _traceSource.Listeners.RemoveAt(0);
            }

            _traceSource.Listeners.Add(traceListener);
        }
Example #19
0
        public static void MultipleLoggers_IsEnabledReturnsCorrectValue(SourceLevels first, SourceLevels second, bool expected)
        {
            // Arrange
            var firstSwitch = new SourceSwitch("FirstSwitch", "First Test Switch");
            firstSwitch.Level = first;

            var secondSwitch = new SourceSwitch("SecondSwitch", "Second Test Switch");
            secondSwitch.Level = second;

            var factory = new LoggerFactory();
            var logger = factory.CreateLogger("Test");

            // Act
            factory.AddTraceSource(firstSwitch, new ConsoleTraceListener());
            factory.AddTraceSource(secondSwitch, new ConsoleTraceListener());

            // Assert
            Assert.Equal(expected, logger.IsEnabled(LogLevel.Information));
        }
Example #20
0
        public static void IsEnabledReturnsCorrectValue()
        {
            // Arrange
            var testSwitch = new SourceSwitch("TestSwitch", "Level will be set to warning for this test");
            testSwitch.Level = SourceLevels.Warning;

            var factory = new LoggerFactory();
            var logger = factory.CreateLogger("Test");

            // Act
            factory.AddTraceSource(testSwitch, new ConsoleTraceListener());

            // Assert
            Assert.True(logger.IsEnabled(LogLevel.Critical));
            Assert.True(logger.IsEnabled(LogLevel.Error));
            Assert.True(logger.IsEnabled(LogLevel.Warning));
            Assert.False(logger.IsEnabled(LogLevel.Information));
            Assert.False(logger.IsEnabled(LogLevel.Verbose));
        }
        public void Dispose_TraceListenerIsFlushedOnce()
        {
            // Arrange
            var testSwitch = new SourceSwitch("TestSwitch", "Level will be set to warning for this test");
            testSwitch.Level = SourceLevels.Warning;
            var listener = new BufferedConsoleTraceListener();
            
            TraceSourceLoggerProvider provider = new TraceSourceLoggerProvider(testSwitch, listener);
            var logger1 = provider.CreateLogger("FirstLogger");
            var logger2 = provider.CreateLogger("SecondLogger");
            logger1.LogError("message1");
            logger2.LogError("message2");
            
            // Act
            provider.Dispose();

            // Assert
            Assert.Equal(1, listener.FlushCount);
        }
Example #22
0
        public Tracer()
        {
            SourceSwitch sourceSwitch = new SourceSwitch("SourceSwitch", "Verbose");
            ts.Switch = sourceSwitch;

            ConsoleTraceListener consoleListener = new ConsoleTraceListener();
            consoleListener.Name = "console";
            consoleListener.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.ProcessId | TraceOptions.ThreadId;

            ts.Listeners.Add(consoleListener);

            FileStream traceLog = new FileStream(@"pomodoro.log", FileMode.OpenOrCreate);

            TextWriterTraceListener fileListener = new TextWriterTraceListener(traceLog);
            fileListener.Name = "log";
            fileListener.TraceOutputOptions = TraceOptions.DateTime | TraceOptions.ProcessId | TraceOptions.ThreadId;

            ts.Listeners.Add(fileListener);
        }
Example #23
0
        public Startup(IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            var builder = new ConfigurationBuilder()
                .AddJsonFile("config.json")
                .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

            if (env.IsDevelopment())
            {
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
                loggerFactory.AddDebug();
                loggerFactory.MinimumLevel = LogLevel.Debug;
            }

            builder.AddEnvironmentVariables();

            Configuration = builder.Build();

            _environment = env;
            LoggerFactory = loggerFactory;

            loggerFactory.AddConsole();
            
#if DNX451
            int io, worker;
            ThreadPool.GetMinThreads(out worker, out io);
            Console.WriteLine("Startup min worker thread {0}, min io thread {1}", worker, io);
            ThreadPool.GetMaxThreads(out worker, out io);
            Console.WriteLine("Startup max worker thread {0}, max io thread {1}", worker, io);
            ThreadPool.SetMaxThreads(32767, 1000);
            ThreadPool.SetMinThreads(50, 50);
            ThreadPool.GetMinThreads(out worker, out io);
            Console.WriteLine("Startup min worker thread {0}, min io thread {1}", worker, io);
            ThreadPool.GetMaxThreads(out worker, out io);
            Console.WriteLine("Startup max worker thread {0}, max io thread {1}", worker, io);

            var sourceSwitch = new SourceSwitch("chatle");
            loggerFactory.AddTraceSource(sourceSwitch, new ConsoleTraceListener());
#endif
        }
        public static ILoggerFactory AddTraceSource(
            this ILoggerFactory factory,
            SourceSwitch sourceSwitch,
            TraceListener listener)
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            if (sourceSwitch == null)
            {
                throw new ArgumentNullException(nameof(sourceSwitch));
            }

            if (listener == null)
            {
                throw new ArgumentNullException(nameof(listener));
            }

            factory.AddProvider(new TraceSourceLoggerProvider(sourceSwitch, listener));

            return factory;
        }
        /// <summary>
        /// Get the configured trace switches from the application configuration file.
        /// </summary>
        /// <param name="diagnosticsSection">The system.diagnostics configuration section.</param>
        private static IReadOnlyDictionary<String, SourceSwitch> GetConfiguredSwitches(ConfigurationSection diagnosticsSection)
        {
            var switchSection = diagnosticsSection != null ? diagnosticsSection.ElementInformation.Properties["switches"] : null;
            var switches = switchSection?.Value is IEnumerable ? (IEnumerable)switchSection.Value : Enumerable.Empty<ConfigurationElement>();
            var configuredSwitches = new Dictionary<String, SourceSwitch>(StringComparer.InvariantCultureIgnoreCase);

            foreach (var name in switches.OfType<ConfigurationElement>().Select(element => GetPropertyValue(element, "name")).Where(name => name.IsNotNullOrWhiteSpace()))
                configuredSwitches[name] = new SourceSwitch(name);

            return new ReadOnlyDictionary<String, SourceSwitch>(configuredSwitches);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DiagnosticsLoggerFactory"/> class. 
 /// </summary>
 /// <summary>
 /// Creates a factory named "Microsoft.Owin".
 /// </summary>
 public DiagnosticsLoggerFactory()
 {
     _rootSourceSwitch = new SourceSwitch(RootTraceName);
     _rootTraceListener = null;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DiagnosticsLoggerFactory"/> class.
 /// </summary>
 /// <param name="rootSourceSwitch"></param>
 /// <param name="rootTraceListener"></param>
 public DiagnosticsLoggerFactory(SourceSwitch rootSourceSwitch, TraceListener rootTraceListener)
 {
     _rootSourceSwitch = rootSourceSwitch ?? new SourceSwitch(RootTraceName);
     _rootTraceListener = rootTraceListener;
 }
Example #28
0
		public void ConstructorNullDefaultValue ()
		{
			SourceSwitch s = new SourceSwitch ("foo", null);
		}
Example #29
0
		public void ConstructorNullName ()
		{
			SourceSwitch s = new SourceSwitch (null);
			Assert.IsNull (s.DisplayName);
		}
Example #30
0
 public TraceManager(TextWriterTraceListener hostTraceListener)
 {
     Switch = new SourceSwitch("SignalRSwitch");
     _hostTraceListener = hostTraceListener;
 }