Inheritance: IList, ICollection, IEnumerable
		internal TraceSourceInfo (string name, SourceLevels levels, TraceImplSettings settings)
		{
			this.name = name;
			this.levels = levels;
			this.listeners = new TraceListenerCollection (false);
			this.listeners.Add (new DefaultTraceListener(), settings);
		}
        internal TracerConfig(string cfg)
        {
            if (string.IsNullOrEmpty(cfg))
            {
                return;
            }

            var source = new TraceSource(TraceEnvVarName, SourceLevels.All);
            this.myListeners = source.Listeners;

            var parser = new TraceCfgParser(cfg);
            var newListener = parser.OutDevice;
            this.myFilters = parser.Filters;
            this.myNotFilters = parser.NotFilters;

            if (newListener != null)
            {
                // when the App.config _Trace source should be used we do not replace
                // anything
                if (!parser.UseAppConfigListeners)
                {
                    this.myListeners.Clear();
                    this.myListeners.Add(newListener);
                }
            }
            else
            {
                this.myListeners = null;
            }
        }
示例#3
0
        private void TraceConfiguration()
        {
            try
            {
                //delete the old log file
                string logPath = Path.Combine(PathHelper.ApplicationPath, "ReflectionStudio.exe.log");
                if (File.Exists(logPath))
                {
                    File.Delete(logPath);
                }

                if (ReflectionStudio.Properties.Settings.Default.UseTraceListener)
                {
                    //configure the trace
                    System.Diagnostics.Trace.AutoFlush  = true;
                    System.Diagnostics.Trace.IndentSize = 2;

                    //configure the text listenner
                    System.Diagnostics.TraceListenerCollection listeners = System.Diagnostics.Trace.Listeners;
                    listeners.Add(new System.Diagnostics.TextWriterTraceListener(logPath, "LOG"));
                }
            }
            catch (Exception error)
            {
                Tracer.Error("Reflection Studio.TraceConfiguration", error);
            }
        }
示例#4
0
		internal TraceSourceInfo (string name, SourceLevels levels, TraceImplSettings settings)
		{
			this.name = name;
			this.levels = levels;
			this.listeners = new TraceListenerCollection ();
			this.listeners.Add (new DefaultTraceListener() { IndentSize = settings.IndentSize });
		}
示例#5
0
 public TraceHook(TraceSource source)
 {
     this.listener = new PassThruListener();
     this.collection = source.Listeners;
     this.lockContext = new object();
     source.Listeners.Add(listener);
     HookupListener();
 }
示例#6
0
        public ServerConnection()
        {
            WorldModel = new History();
            MessageRecieved += ConnectionMessageRecieved;

            // I wish there were a public constructor for TraceListenerCollection, but there is not
            ConstructorInfo constructor = typeof(TraceListenerCollection).GetConstructor(
                BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { }, null);
            ChatListeners = (TraceListenerCollection)constructor.Invoke(new object[0] { });
        }
        public ClientSideMessageProcessor(ServerConnection connection, History history)
        {
            ServerConnection = connection;
            History = history;
            ServerConnection.MessageRecieved += ConnectionMessageRecieved;

            // I wish there were a public constructor for TraceListenerCollection, but there is not
            ConstructorInfo constructor = typeof(TraceListenerCollection).GetConstructor(
                BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { }, null);
            ChatListeners = (TraceListenerCollection)constructor.Invoke(new object[0] { });
        }
 public void AddRange(TraceListenerCollection value)
 {
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     int count = value.Count;
     for (int i = 0; i < count; i++)
     {
         this.Add(value[i]);
     }
 }
示例#9
0
	// Make sure that the trace configuration is loaded.
	internal static void Initialize()
			{
				// Bail out if already initialized, or called recursively.
				if(initialized)
				{
					return;
				}
				initialized = true;

				// Create the default trace listener.
				DefaultTraceListener defListener =
					new DefaultTraceListener();

				// Create the initial listeners collection.
				listeners = new TraceListenerCollection();
				listeners.Add(defListener);

				// Get the diagnostics configuration options.
				Hashtable options = (Hashtable)
					ConfigurationSettings.GetConfig
						("system.diagnostics",
						 new DiagnosticsConfigurationHandler());
				if(options == null)
				{
					options = new Hashtable();
				}

				// Process the options for the default trace listener.
				Object value = options["assertuienabled"];
				if(value != null)
				{
					defListener.AssertUiEnabled = (bool)value;
				}
				value = options["logfilename"];
				if(value != null)
				{
					defListener.LogFileName = (String)value;
				}

				// Process the trace options.
				value = options["autoflush"];
				if(value != null)
				{
					autoFlush = (bool)value;
				}
				value = options["indentsize"];
				if(value != null)
				{
					indentSize = (int)value;
				}
				switches = (Hashtable)(options["switches"]);
			}
示例#10
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;
			}
		}
 public TraceListenerCollection GetRuntimeObject()
 {
     TraceListenerCollection listeners = new TraceListenerCollection();
     bool flag = false;
     foreach (ListenerElement element in this)
     {
         if (!flag && !element._isAddedByDefault)
         {
             new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
             flag = true;
         }
         listeners.Add(element.GetRuntimeObject());
     }
     return listeners;
 }
示例#12
0
 /// <summary>
 /// Registers trace listeners to be used by the application.
 /// Generally web.config is used to do this, but there are special cases.
 /// </summary>
 /// <param name="traceListenerCollection">
 /// The trace Listener Collection to register trace listeners at.
 /// </param>
 public static void RegisterTraceListeners(TraceListenerCollection traceListenerCollection)
 {
     // This replaces web.config setting: configuration\system.diagnostics\trace\listeners\add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.8.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics"
     // This is done because DiagnosticMonitorTraceListener class throws exception when not running in azure/devfabric.
     if (RoleEnvironment.IsAvailable)
     {
         // See 'diagnostics.wadcfg' file. It contains all configurations of the DiagnosticMonitor.
         // It is not needed to configure nor start the DiagnosticMonitor manually in code.
         // It will be started automatically and will use settings in the 'diagnostics.wadcfg' file.
         // All we need to do is to add the trace listener.
         // reference: http://www.windowsazure.com/en-us/develop/net/common-tasks/diagnostics/
         // google: https://www.google.com/search?q=diagnostics.wadcfg
         traceListenerCollection.Add(new DiagnosticMonitorTraceListener());
     }
 }
      public RedirectOutput()
      {
        _oldOut = Console.Out;
        _oldError = Console.Error;
        _oldListeners = Trace.Listeners;

        StdOut = new StringWriter(CultureInfo.CurrentCulture);
        Console.SetOut(StdOut);

        StdError = new StringWriter(CultureInfo.CurrentCulture);
        Console.SetError(StdError);

        DebugTrace = new StringWriter(CultureInfo.CurrentCulture);
        Trace.Listeners.Clear();
        Trace.Listeners.Add(new TextWriterTraceListener(DebugTrace));
      }
示例#14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Logger"/> class with the specified <paramref name="name"/> and logging <paramref name="level"/>.
        /// </summary>
        /// <param name="name">The name of the logger.</param>
        /// <param name="level">The log level of the logger.</param>
        /// <param name="listeners">The underlying set of trace listeners.</param>
        public Logger(String name, SourceLevels level, TraceListenerCollection listeners)
        {
            Verify.NotNullOrWhiteSpace(name, nameof(name));

            // Create the trace source.
            traceSource = new TraceSource(name, level);

            // Configure trace source listeners.
            traceSource.Listeners.Clear();
            traceSource.Listeners.AddRange(listeners);

            // Determine supported log operations.
            fatalEnabled = (level & SourceLevels.Critical) == SourceLevels.Critical;
            errorEnabled = (level & SourceLevels.Error) == SourceLevels.Error;
            warnEnabled = (level & SourceLevels.Warning) == SourceLevels.Warning;
            infoEnabled = (level & SourceLevels.Information) == SourceLevels.Information;
            debugEnabled = (level & SourceLevels.Verbose) == SourceLevels.Verbose;
            activityEnabled = (level & SourceLevels.ActivityTracing) == SourceLevels.ActivityTracing;
            traceEnabled = (level & SourceLevels.All) == SourceLevels.All;
        }
        public TraceListenerCollection GetRuntimeObject() {
            TraceListenerCollection listeners = new TraceListenerCollection();
            bool _isDemanded = false;

            foreach(ListenerElement element in this) {
                
                // At some point, we need to pull out adding/removing the 'default' DefaultTraceListener  
                // code from here in favor of adding/not-adding after we load the config (in TraceSource 
                // and in static Trace) 
                
                if (!_isDemanded && !element._isAddedByDefault) {
                    // Do a full damand; This will disable partially trusted code from hooking up listeners
                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
                    _isDemanded = true;
                }

                listeners.Add(element.GetRuntimeObject());
            }

            return listeners;
        }
        private void Initialize() {
            if (!_initCalled) {
                lock(this) {
                    if (_initCalled)
                        return;
                    
                    SourceElementsCollection sourceElements = DiagnosticsConfiguration.Sources;
    
                    if (sourceElements != null) {
                        SourceElement sourceElement = sourceElements[sourceName];
                        if (sourceElement != null) {
                            if (!String.IsNullOrEmpty(sourceElement.SwitchName)) {
                                CreateSwitch(sourceElement.SwitchType, sourceElement.SwitchName);
                            }
                            else {
                                CreateSwitch(sourceElement.SwitchType, sourceName);
    
                                if (!String.IsNullOrEmpty(sourceElement.SwitchValue)) 
                                    internalSwitch.Level = (SourceLevels) Enum.Parse(typeof(SourceLevels), sourceElement.SwitchValue);
                            }

                            listeners = sourceElement.Listeners.GetRuntimeObject();
    
                            attributes = new StringDictionary();
                            TraceUtils.VerifyAttributes(sourceElement.Attributes, GetSupportedAttributes(), this);
                            attributes.contents = sourceElement.Attributes;
                        }
                        else
                            NoConfigInit();
                    }
                    else
                        NoConfigInit();
    
                    _initCalled = true;
                }
            }
        }
 private void Initialize()
 {
     if (!this._initCalled)
     {
         lock (this)
         {
             if (!this._initCalled)
             {
                 SourceElementsCollection sources = DiagnosticsConfiguration.Sources;
                 if (sources != null)
                 {
                     SourceElement element = sources[this.sourceName];
                     if (element != null)
                     {
                         if (!string.IsNullOrEmpty(element.SwitchName))
                         {
                             this.CreateSwitch(element.SwitchType, element.SwitchName);
                         }
                         else
                         {
                             this.CreateSwitch(element.SwitchType, this.sourceName);
                             if (!string.IsNullOrEmpty(element.SwitchValue))
                             {
                                 this.internalSwitch.Level = (SourceLevels) Enum.Parse(typeof(SourceLevels), element.SwitchValue);
                             }
                         }
                         this.listeners = element.Listeners.GetRuntimeObject();
                         this.attributes = new StringDictionary();
                         TraceUtils.VerifyAttributes(element.Attributes, this.GetSupportedAttributes(), this);
                         this.attributes.ReplaceHashtable(element.Attributes);
                     }
                     else
                     {
                         this.NoConfigInit();
                     }
                 }
                 else
                 {
                     this.NoConfigInit();
                 }
                 this._initCalled = true;
             }
         }
     }
 }
示例#18
0
 private void NoConfigInit()
 {
     _internalSwitch = new SourceSwitch(_sourceName, _switchLevel.ToString());
     _listeners      = new TraceListenerCollection();
     _listeners.Add(new DefaultTraceListener());
 }
		public void AddRange (TraceListenerCollection value)
		{
			InitializeRange (value);
			listeners.AddRange (value.listeners);
		}
示例#20
0
        // This method refreshes all the data from the configuration file, so that updated to the configuration file are mirrored
        // in the System.Diagnostics.Trace class
        static internal void Refresh() {
            lock (critSec) {
#if CONFIGURATION_DEP
                settingsInitialized = false;
#endif
                listeners = null;
            }
            InitializeSettings();
        }
 // This method refreshes all the data from the configuration file, so that updated to the configuration file are mirrored
 // in the System.Diagnostics.Trace class
 static internal void Refresh() {
     lock (critSec) {
         settingsInitialized = false;
         listeners = null;
     }
     InitializeSettings();
 }
 public void AddRange(TraceListenerCollection value)
 {
     InitializeRange(value);
     listeners.AddRange(value.listeners);
 }
示例#23
0
		public TraceSourceInfo (string name, SourceLevels levels)
		{
			this.name = name;
			this.levels = levels;
			this.listeners = new TraceListenerCollection ();
		}
 private void NoConfigInit()
 {
     this.internalSwitch = new SourceSwitch(this.sourceName, this.switchLevel.ToString());
     this.listeners = new TraceListenerCollection();
     this.listeners.Add(new DefaultTraceListener());
     this.attributes = null;
 }
		// only defines "add" and "remove", but "clear" also works
		// for add, "name" is required; initializeData is optional; "type" is required in 1.x, optional in 2.0.
		private void AddTraceListeners (IDictionary d, XmlNode listenersNode, TraceListenerCollection listeners)
		{
#if !TARGET_JVM
			// There are no attributes on <listeners/>
			ValidateInvalidAttributes (listenersNode.Attributes, listenersNode);

			foreach (XmlNode child in listenersNode.ChildNodes) {
				XmlNodeType t = child.NodeType;
				if (t == XmlNodeType.Whitespace || t == XmlNodeType.Comment)
					continue;
				if (t == XmlNodeType.Element) {
					XmlAttributeCollection attributes = child.Attributes;
					string name = null;
					switch (child.Name) {
						case "add":
							AddTraceListener (d, child, attributes, listeners);
							break;
						case "remove":
							name = GetAttribute (attributes, "name", true, child);
							RemoveTraceListener (name);
							break;
						case "clear":
							configValues.Listeners.Clear ();
							break;
						default:
							ThrowUnrecognizedElement (child);
							break;
					}
					ValidateInvalidAttributes (attributes, child);
				}
				else
					ThrowUnrecognizedNode (child);
			}
#endif
		}
示例#26
0
 private void NoConfigInit()
 {
     _internalSwitch = new SourceSwitch(_sourceName, _switchLevel.ToString());
     _listeners = new TraceListenerCollection();
     _listeners.Add(new DefaultTraceListener());
 }
示例#27
0
文件: TraceImpl.cs 项目: N3X15/mono
 static TraceImpl()
 {
     listeners = new TraceListenerCollection(true);
 }
示例#28
0
        private void AddTraceListener(IDictionary d, XmlNode child, XmlAttributeCollection attributes, TraceListenerCollection listeners)
        {
            string name = GetAttribute(attributes, "name", true, child);
            string type = null;

#if CONFIGURATION_DEP
            type = GetAttribute(attributes, "type", false, child);
            if (type == null)
            {
                // indicated by name.
                TraceListener shared = GetSharedListeners(d) [name];
                if (shared == null)
                {
                    throw new ConfigurationException(String.Format("Shared trace listener {0} does not exist.", name));
                }
                if (attributes.Count != 0)
                {
                    throw new ConfigurationErrorsException(string.Format(
                                                               "Listener '{0}' references a shared " +
                                                               "listener and can only have a 'Name' " +
                                                               "attribute.", name));
                }
                listeners.Add(shared, configValues);
                return;
            }
#else
            type = GetAttribute(attributes, "type", true, child);
#endif

            Type t = Type.GetType(type);
            if (t == null)
            {
                throw new ConfigurationException(string.Format("Invalid Type Specified: {0}", type));
            }

            object[] args;
            Type[]   types;

            string initializeData = GetAttribute(attributes, "initializeData", false, child);
            if (initializeData != null)
            {
                args  = new object[] { initializeData };
                types = new Type[] { typeof(string) };
            }
            else
            {
                args  = null;
                types = Type.EmptyTypes;
            }

            BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
            if (t.Assembly == GetType().Assembly)
            {
                flags |= BindingFlags.NonPublic;
            }

            ConstructorInfo ctor = t.GetConstructor(flags, null, types, null);
            if (ctor == null)
            {
                throw new ConfigurationException("Couldn't find constructor for class " + type);
            }

            TraceListener l = (TraceListener)ctor.Invoke(args);
            l.Name = name;

#if CONFIGURATION_DEP
            string trace = GetAttribute(attributes, "traceOutputOptions", false, child);
            if (trace != null)
            {
                if (trace != trace.Trim())
                {
                    throw new ConfigurationErrorsException(string.Format(
                                                               "Invalid value '{0}' for 'traceOutputOptions'.",
                                                               trace), child);
                }

                TraceOptions trace_options;

                try {
                    trace_options = (TraceOptions)Enum.Parse(
                        typeof(TraceOptions), trace);
                } catch (ArgumentException) {
                    throw new ConfigurationErrorsException(string.Format(
                                                               "Invalid value '{0}' for 'traceOutputOptions'.",
                                                               trace), child);
                }

                l.TraceOutputOptions = trace_options;
            }

            string [] supported_attributes = l.GetSupportedAttributes();
            if (supported_attributes != null)
            {
                for (int i = 0; i < supported_attributes.Length; i++)
                {
                    string key   = supported_attributes [i];
                    string value = GetAttribute(attributes, key, false, child);
                    if (value != null)
                    {
                        l.Attributes.Add(key, value);
                    }
                }
            }
#endif

            listeners.Add(l, configValues);
        }
 internal void Refresh()
 {
     if (!this._initCalled)
     {
         this.Initialize();
     }
     else
     {
         SourceElementsCollection sources = DiagnosticsConfiguration.Sources;
         if (sources != null)
         {
             SourceElement element = sources[this.Name];
             if (element != null)
             {
                 if ((string.IsNullOrEmpty(element.SwitchType) && (this.internalSwitch.GetType() != typeof(SourceSwitch))) || (element.SwitchType != this.internalSwitch.GetType().AssemblyQualifiedName))
                 {
                     if (!string.IsNullOrEmpty(element.SwitchName))
                     {
                         this.CreateSwitch(element.SwitchType, element.SwitchName);
                     }
                     else
                     {
                         this.CreateSwitch(element.SwitchType, this.Name);
                         if (!string.IsNullOrEmpty(element.SwitchValue))
                         {
                             this.internalSwitch.Level = (SourceLevels) Enum.Parse(typeof(SourceLevels), element.SwitchValue);
                         }
                     }
                 }
                 else if (!string.IsNullOrEmpty(element.SwitchName))
                 {
                     if (element.SwitchName != this.internalSwitch.DisplayName)
                     {
                         this.CreateSwitch(element.SwitchType, element.SwitchName);
                     }
                     else
                     {
                         this.internalSwitch.Refresh();
                     }
                 }
                 else if (!string.IsNullOrEmpty(element.SwitchValue))
                 {
                     this.internalSwitch.Level = (SourceLevels) Enum.Parse(typeof(SourceLevels), element.SwitchValue);
                 }
                 else
                 {
                     this.internalSwitch.Level = SourceLevels.Off;
                 }
                 TraceListenerCollection listeners = new TraceListenerCollection();
                 foreach (ListenerElement element2 in element.Listeners)
                 {
                     TraceListener listener = this.listeners[element2.Name];
                     if (listener != null)
                     {
                         listeners.Add(element2.RefreshRuntimeObject(listener));
                     }
                     else
                     {
                         listeners.Add(element2.GetRuntimeObject());
                     }
                 }
                 TraceUtils.VerifyAttributes(element.Attributes, this.GetSupportedAttributes(), this);
                 this.attributes = new StringDictionary();
                 this.attributes.ReplaceHashtable(element.Attributes);
                 this.listeners = listeners;
             }
             else
             {
                 this.internalSwitch.Level = this.switchLevel;
                 this.listeners.Clear();
                 this.attributes = null;
             }
         }
     }
 }
        internal void Refresh()
        {
            if (!_initCalled)
            {
                Initialize();
                return;
            }

            SourceElementsCollection sources = DiagnosticsConfiguration.Sources;

            if (sources != null)
            {
                SourceElement sourceElement = sources[Name];
                if (sourceElement != null)
                {
                    // first check if the type changed
                    if ((String.IsNullOrEmpty(sourceElement.SwitchType) && internalSwitch.GetType() != typeof(SourceSwitch)) ||
                        (sourceElement.SwitchType != internalSwitch.GetType().AssemblyQualifiedName))
                    {
                        if (!String.IsNullOrEmpty(sourceElement.SwitchName))
                        {
                            CreateSwitch(sourceElement.SwitchType, sourceElement.SwitchName);
                        }
                        else
                        {
                            CreateSwitch(sourceElement.SwitchType, Name);

                            if (!String.IsNullOrEmpty(sourceElement.SwitchValue))
                            {
                                internalSwitch.Level = (SourceLevels)Enum.Parse(typeof(SourceLevels), sourceElement.SwitchValue);
                            }
                        }
                    }
                    else if (!String.IsNullOrEmpty(sourceElement.SwitchName))
                    {
                        // create a new switch if the name changed, otherwise just refresh.
                        if (sourceElement.SwitchName != internalSwitch.DisplayName)
                        {
                            CreateSwitch(sourceElement.SwitchType, sourceElement.SwitchName);
                        }
                        else
                        {
                            internalSwitch.Refresh();
                        }
                    }
                    else
                    {
                        // the switchValue changed.  Just update our internalSwitch.
                        if (!String.IsNullOrEmpty(sourceElement.SwitchValue))
                        {
                            internalSwitch.Level = (SourceLevels)Enum.Parse(typeof(SourceLevels), sourceElement.SwitchValue);
                        }
                        else
                        {
                            internalSwitch.Level = SourceLevels.Off;
                        }
                    }

                    TraceListenerCollection newListenerCollection = new TraceListenerCollection();
                    foreach (ListenerElement listenerElement in sourceElement.Listeners)
                    {
                        TraceListener listener = listeners[listenerElement.Name];
                        if (listener != null)
                        {
                            newListenerCollection.Add(listenerElement.RefreshRuntimeObject(listener));
                        }
                        else
                        {
                            newListenerCollection.Add(listenerElement.GetRuntimeObject());
                        }
                    }

                    TraceUtils.VerifyAttributes(sourceElement.Attributes, GetSupportedAttributes(), this);

                    attributes          = new StringDictionary();
                    attributes.contents = sourceElement.Attributes;

                    listeners = newListenerCollection;
                }
                else
                {
                    // there was no config, so clear whatever we have.
                    internalSwitch.Level = switchLevel;
                    listeners.Clear();
                    attributes = null;
                }
            }
        }
示例#31
0
 public void AddRange(System.Diagnostics.TraceListenerCollection value)
 {
 }
 public void AddRange(TraceListenerCollection value)
 {
     Contract.Requires(value != null);
 }
        //---------------------------------------------------------------------

        public static SysDiag.TraceListener[] Copy(SysDiag.TraceListenerCollection listeners)
        {
            SysDiag.TraceListener[] array = new SysDiag.TraceListener[listeners.Count];
            listeners.CopyTo(array, 0);
            return(array);
        }
        // Initialize the world.
        //
        // This logically belongs in the static constructor (as it only needs
        // to be done once), except for one thing: if the .config file has a
        // syntax error, .NET throws a ConfigurationException.  If we read the
        // .config file in the static ctor, we throw a ConfigurationException
        // from the static ctor, which results in a TypeLoadException.  Oops.
        // Reading the .config file here will allow the static ctor to
        // complete successfully, allowing us to throw a normal
        // ConfigurationException should the .config file contain an error.
        //
        // There are also some ordering issues.
        //
        // The DiagnosticsConfigurationHandler assumes that the TraceImpl.Listeners
        // collection exists (so it can initialize the DefaultTraceListener and
        // add/remove existing listeners).
        private static object InitOnce()
        {
            object d = null;
#if !NO_LOCK_FREE
            // The lock-free version
            if (listeners == null)
            {
                var c = new TraceListenerCollection();
                Thread.MemoryBarrier();
                while (Interlocked.CompareExchange(ref listeners, c, null) == null)
                {
                    // Read in the .config file and get the ball rolling...
                    // d = DiagnosticsConfiguration.Settings;
                }
                Thread.MemoryBarrier();
            }
#else
    // The lock version (saved for posterity and potential debugging)
			lock (lock_) {
				if (listeners == null) {
					listeners = new TraceListenerCollection ();
					// Read in the .config file and get the ball rolling...
					d = DiagnosticsConfiguration.Settings;
				}
			}
#endif
            return d;
        }
		private TraceListenerCollection GetSharedListeners (IDictionary d)
		{
			TraceListenerCollection shared_listeners = d ["sharedListeners"] as TraceListenerCollection;
			if (shared_listeners == null) {
				shared_listeners = new TraceListenerCollection (false);
				d ["sharedListeners"] = shared_listeners;
			}
			return shared_listeners;
		}
示例#36
0
文件: TraceImpl.cs 项目: nkuln/mono
		static TraceImpl ()
		{
			listeners = new TraceListenerCollection (true);
		}
		private void AddTraceListener (IDictionary d, XmlNode child, XmlAttributeCollection attributes, TraceListenerCollection listeners)
		{
			string name = GetAttribute (attributes, "name", true, child);
			string type = null;

#if NET_2_0 && CONFIGURATION_DEP
			type = GetAttribute (attributes, "type", false, child);
			if (type == null) {
				// indicated by name.
				TraceListener shared = GetSharedListeners (d) [name];
				if (shared == null)
					throw new ConfigurationException (String.Format ("Shared trace listener {0} does not exist.", name));
				if (attributes.Count != 0)
					throw new ConfigurationErrorsException (string.Format (
						"Listener '{0}' references a shared " +
						"listener and can only have a 'Name' " +
						"attribute.", name));
				listeners.Add (shared, configValues);
				return;
			}
#else
			type = GetAttribute (attributes, "type", true, child);
#endif

			Type t = Type.GetType (type);
			if (t == null)
				throw new ConfigurationException (string.Format ("Invalid Type Specified: {0}", type));

			object[] args;
			Type[] types;

			string initializeData = GetAttribute (attributes, "initializeData", false, child);
			if (initializeData != null) {
				args = new object[] { initializeData };
				types = new Type[] { typeof(string) };
			} else {
				args = null;
				types = Type.EmptyTypes;
			}

			BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
			if (t.Assembly == GetType ().Assembly)
				flags |= BindingFlags.NonPublic;

			ConstructorInfo ctor = t.GetConstructor (flags, null, types, null);
			if (ctor == null) 
				throw new ConfigurationException ("Couldn't find constructor for class " + type);
			
			TraceListener l = (TraceListener) ctor.Invoke (args);
			l.Name = name;

#if NET_2_0 && CONFIGURATION_DEP
			string trace = GetAttribute (attributes, "traceOutputOptions", false, child);
			if (trace != null) {
				if (trace != trace.Trim ())
					throw new ConfigurationErrorsException (string.Format (
						"Invalid value '{0}' for 'traceOutputOptions'.",
						trace), child);

				TraceOptions trace_options;
	
				try {
					trace_options = (TraceOptions) Enum.Parse (
						typeof (TraceOptions), trace);
				} catch (ArgumentException) {
					throw new ConfigurationErrorsException (string.Format (
						"Invalid value '{0}' for 'traceOutputOptions'.",
						trace), child);
				}

				l.TraceOutputOptions = trace_options;
			}

			string [] supported_attributes = l.GetSupportedAttributes ();
			if (supported_attributes != null) {
				for (int i = 0; i < supported_attributes.Length; i++) {
					string key = supported_attributes [i];
					string value = GetAttribute (attributes, key, false, child);
					if (value != null)
						l.Attributes.Add (key, value);
				}
			}
#endif

			listeners.Add (l, configValues);
		}
示例#38
0
 public LogModel(TraceListenerCollection traceListenerCollection)
 {
     traceListenerCollection.Add(this);
 }
示例#39
0
		// Initialize the world.
		//
		// This logically belongs in the static constructor (as it only needs
		// to be done once), except for one thing: if the .config file has a
		// syntax error, .NET throws a ConfigurationException.  If we read the
		// .config file in the static ctor, we throw a ConfigurationException
		// from the static ctor, which results in a TypeLoadException.  Oops.
		// Reading the .config file here will allow the static ctor to
		// complete successfully, allowing us to throw a normal
		// ConfigurationException should the .config file contain an error.
		//
		// There are also some ordering issues.
		//
		// DiagnosticsConfigurationHandler doesn't store values within TraceImpl,
		// but instead stores values it reads from the .config file within a
		// TraceImplSettings object (accessible via the TraceImplSettings.Key key
		// in the IDictionary returned).
		private static void InitOnce ()
		{
			if (initLock != null) {
				lock (initLock) {
					if (listeners == null) {
						IDictionary       d = DiagnosticsConfiguration.Settings;
						TraceImplSettings s = (TraceImplSettings) d [TraceImplSettings.Key];

						d.Remove (TraceImplSettings.Key);

						autoFlush   = s.AutoFlush;
						indentLevel = s.IndentLevel;
						indentSize  = s.IndentSize;
						listeners   = s.Listeners;
					}
				}
				initLock = null;
			}
		}
示例#40
0
 public TraceSourceInfo(string name, SourceLevels levels)
 {
     this.name      = name;
     this.levels    = levels;
     this.listeners = new TraceListenerCollection();
 }