/// <summary>
        /// Initializes a new instance of the <see cref="EventSourceSettings" /> class.
        /// </summary>
        /// <param name="name">The friendly event source name.</param>
        /// <param name="eventSourceId">The event source id.</param>
        /// <param name="level">The level.</param>
        /// <param name="matchAnyKeyword">The match any keyword.</param>
        /// <param name="arguments">The arguments for the event source.</param>
        /// <param name="processNameFilters">The the process filters.</param>
        /// <exception cref="ConfigurationException">A validation exception.</exception>
        public EventSourceSettings(
            string name = null,
            Guid? eventSourceId = null,
            EventLevel level = EventLevel.LogAlways,
            EventKeywords matchAnyKeyword = Keywords.All,
            IEnumerable<KeyValuePair<string, string>> arguments = null,
            IEnumerable<string> processNameFilters = null)
        {
            // If no Id, Name should not be optional so we may derive an Id from it.
            if (!eventSourceId.HasValue || eventSourceId == Guid.Empty)
            {
                if (string.IsNullOrWhiteSpace(name))
                {
                    throw new ConfigurationException(Properties.Resources.MissingEventSourceNameAndId);
                }

                eventSourceId = TraceEventProviders.GetEventSourceGuidFromName(name);
            }
            else if (!string.IsNullOrWhiteSpace(name))
            {
                // throw and both name & Id specified
                throw new ConfigurationException(Properties.Resources.EventSourceAmbiguityError);
            }

            this.EventSourceId = eventSourceId.Value;
            this.Name = name ?? eventSourceId.ToString(); // Set a not null value for later use
            this.Level = level;
            this.MatchAnyKeyword = matchAnyKeyword;
            this.Arguments = arguments ?? Enumerable.Empty<KeyValuePair<string, string>>();
            this.ProcessNamesToFilter = processNameFilters ?? Enumerable.Empty<string>();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="EventTextFormatter" /> class.
 /// </summary>
 /// <param name="header">The header.</param>
 /// <param name="footer">The footer.</param>
 /// <param name="verbosityThreshold">The verbosity threshold.</param>
 /// <param name="dateTimeFormat">The date time format used for timestamp value.</param>
 public EventTextFormatter(string header = null, string footer = null, EventLevel verbosityThreshold = DefaultVerbosityThreshold, string dateTimeFormat = null)
 {
     this.Header = header;
     this.Footer = footer;
     this.VerbosityThreshold = verbosityThreshold;
     this.DateTimeFormat = dateTimeFormat;
 }
 public static void EnableEvents(this EventListener self, IEnumerable<EventSource> sources, EventLevel level)
 {
     foreach (var source in sources)
     {
         self.EnableEvents(source, level);
     }
 }
 protected void OnProcessEvent(EventLevel eventLevel, string message)
 {
     if (ProcessEventOccurred != null)
     {
         ProcessEventOccurred(this, new ProcessEventArgs(DateTime.Now, message, eventLevel));
     }
 }
        public override Task<bool> Start()
        {
            // Load the trace level if specified
            string levelStr = GetConfigurationSetting("Trace.Level");
            EventLevel level;
            if (!String.IsNullOrEmpty(levelStr) && Enum.TryParse<EventLevel>(levelStr, true, out level))
            {
                TraceLevel = level;
            }
            else
            {
                TraceLevel = EventLevel.Warning;
            }

            RoleEnvironment.Changing += (_, __) => ConfigurationChanging();
            RoleEnvironment.Changed += (_, __) => ConfigurationChanging();
            RoleEnvironment.StatusCheck += (sender, e) =>
            {
                if (GetCurrentStatus() == ServiceStatus.Busy)
                {
                    e.SetBusy();
                }
            };

            return base.Start();
        }
        private ActionResult Add(string projectId, int? transitionId, EventLevel level, EventType eventType, AppUser creator, object item, DateTime? createdOn = null)
        {
            try
            {
                var i = new ProjectHistory
                {
                    CreatedBy = creator,
                    CreatedOn = createdOn ?? DateTime.UtcNow,
                    Description = JsonConvert.SerializeObject(item),
                    Level = level,
                    ProjectId = projectId,
                    TransitionId = transitionId,
                    Type = eventType
                };

                if (!_dbContext.ChangeTracker.Entries().Where(e => e.State != EntityState.Unchanged).Any())
                {
                    _dbContext.ProjectHistory.Add(i);
                    _dbContext.SaveChanges();
                }
                else
                {
                    _dbContext.ProjectHistory.Add(i);
                }

                return ActionResult.Success(item);
            }
            catch(Exception ex)
            {
                return ActionResult.Failed(ex);
            }
        }
        internal TraceLoggingTypeInfo(
            Type dataType,
            string name,
            EventLevel level,
            EventOpcode opcode,
            EventKeywords keywords,
            EventTags tags)
        {
            if (dataType == null)
            {
                throw new ArgumentNullException("dataType");
            }

            if (name == null)
            {
                throw new ArgumentNullException("eventName");
            }

            Contract.EndContractBlock();

            Statics.CheckName(name);

            this.name = name;
            this.keywords = keywords;
            this.level = level;
            this.opcode = opcode;
            this.tags = tags;
            this.dataType = dataType;
        }
 /// <summary>
 /// Initializes the ConsoleLogListener.
 /// </summary>
 /// <param name="eventLevel">The event level.</param>
 public static void Initialize(EventLevel eventLevel)
 {
     if (instance == null)
     {
         instance = new ConsoleLogListener(eventLevel);
     }
 }
Example #9
0
        internal static void EnableProvider(TraceEventSession session, Guid providerId, EventLevel level, EventKeywords matchAnyKeyword, bool sendManifest = true)
        {
            // Make explicit the invocation for requesting the manifest from the EventSource (Provider).
            var values = sendManifest ? new Dictionary<string, string>() { { "Command", "SendManifest" } } : null;

            session.EnableProvider(providerId, (TraceEventLevel)level, (ulong)matchAnyKeyword, 0, TraceEventOptions.None, values);
        }
        internal static void EnableProvider(
            TraceEventSession session,
            Guid providerId,
            EventLevel level,
            EventKeywords matchAnyKeyword,
            IEnumerable<KeyValuePair<string, string>> arguments,
            IEnumerable<string> processNamesToFilter,
            bool sendManifest = true)
        {
            // Make explicit the invocation for requesting the manifest from the EventSource (Provider).
            var argumentsDictionary = arguments.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
            if (sendManifest)
            {
                argumentsDictionary["Command"] = "SendManifest";
            }

            var options =
                new TraceEventProviderOptions
                {
                    Arguments = argumentsDictionary,
                    ProcessNameFilter = processNamesToFilter.ToArray()
                };

            session.EnableProvider(providerId, (TraceEventLevel)level, (ulong)matchAnyKeyword, options);
        }
		/// <summary>
		/// Initializes a new instance of <see cref="DiagnosticsEventArgs" /> class.
		/// </summary>
		/// <param name="level">The level of the event.</param>
		/// <param name="message">The message of the event.</param>
		/// <param name="source">The source of the event.</param>
		public DiagnosticsEventArgs(EventLevel level, String message, String source)
		{
			Level = level;

			Message = message;

			Source = source;
		}
 public ConsoleColor? Map(EventLevel eventLevel)
 {
     if (eventLevel == EventLevel.Error)
     {
         this.Color = Error;
     }
     return this.Color;
 }
Example #13
0
        public void WriteMessage(string eventMessage, EventLevel level, EventKeywords keywords) 
        {
#if ETW_SUPPORTED 
            if(m_provider != null) 
                m_provider.WriteMessageEvent(eventMessage, (byte)level, (long)keywords);
#endif 
            WriteToAllStreams(0, eventMessage);
        }
Example #14
0
 public bool IsEnabled(EventLevel level, EventKeywords keywords)
 {
     if (!m_providerEnabled) 
         return false;
     if (m_level != 0 && m_level < level) 
         return false; 
     return m_matchAnyKeyword == 0 || (keywords & m_matchAnyKeyword) != 0;
 } 
        private ErrorLevel GetLogLevel(EventLevel level)
        {
            ErrorLevel mappedLevel;
            if (LevelMap.TryGetValue(level, out mappedLevel))
                return mappedLevel;

            return ErrorLevel.Debug;
        }
Example #16
0
        public TestEventListener(string taretSourceName, EventLevel level)
        {
            // Store the arguments
            _targetSourceName = taretSourceName;
            _level = level;

            LoadSourceList();
        }
Example #17
0
        public TestEventListener(Guid targetSourceGuid, EventLevel level)
        {
            // Store the arguments
            _targetSourceGuid = targetSourceGuid;
            _level = level;

            LoadSourceList();
        }
 public void VerifyEvent(ClientEventId id, EventLevel level, EventKeywords keywords, EventOpcode opcode, params object[] payloadItems)
 {
     Assert.Equal(1, this.Events.Count);
     Assert.Equal((int)id, this.Events[0].EventId);
     Assert.Equal(level, this.Events[0].Level);
     Assert.Equal(opcode, this.Events[0].Opcode);
     Assert.True(this.Events[0].Keywords.HasFlag(keywords));
     Assert.Equal(payloadItems, this.Events[0].Payload.ToArray());
 }
 public bool IsEnabled(EventLevel level, EventKeywords keywords)
 {
     if (!m_eventSourceEnabled)
         return false;
     if (m_level != 0 && m_level < level)
         return false;
     if (m_matchAnyKeyword != 0 && (keywords & m_matchAnyKeyword) == 0)
         return false;
     return true;
 }
Example #20
0
        public TestEventListener(List<string> targetSourceNames, EventLevel level)
        {
            // Store the arguments
            foreach (var targetSourceName in targetSourceNames)
            {
                _targetSourceName.Add(targetSourceName, true);
            }
            _level = level;

            LoadSourceList();
        }
        public EventLevel GetLogLevel()
        {
            const string Key = "IOT_LOGLEVEL";
            object logLevel = Environment.GetEnvironmentVariable(Key);
            if (logLevel != null)
            {
                _eventLevel = ConfigurationHelper.ConvertValue<EventLevel>(Key, logLevel);
            }

            return _eventLevel;
        }
        public static void ValidateEventLogMessage(TestEventListener listener, string expectedMessage, EventLevel level)
        {
            bool messageFound = false;

            foreach (var actualEvent in listener.Messages.Where((arg) => { return arg.Level == level; }))
            {
                string actualMessage = string.Format(CultureInfo.InvariantCulture, actualEvent.Message, actualEvent.Payload.ToArray());
                messageFound = messageFound || actualMessage.Contains(expectedMessage);
            }

            Assert.IsTrue(messageFound);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Schema.EventSchema"/> class with the specified values.
 /// </summary>
 /// <param name="id">The event id.</param>
 /// <param name="providerId">The provider GUID.</param>
 /// <param name="providerName">The provider name.</param>
 /// <param name="level">The event level.</param>
 /// <param name="task">The event task.</param>
 /// <param name="taskName">The event task name.</param>
 /// <param name="opcode">The event operation code.</param>
 /// <param name="opcodeName">The event operation code name.</param>
 /// <param name="keywords">The event keywords.</param>
 /// <param name="keywordsDescription">The event keywords description.</param>
 /// <param name="version">The event version.</param>
 /// <param name="payload">The event payload.</param>
 public EventSchema(int id, Guid providerId, string providerName, EventLevel level, EventTask task, string taskName, EventOpcode opcode, string opcodeName, EventKeywords keywords, string keywordsDescription, int version, IEnumerable<string> payload)
 {
     this.id = id;
     this.providerId = providerId;
     this.providerName = providerName;
     this.level = level;
     this.task = task;
     this.taskName = taskName;
     this.opcode = opcode;
     this.opcodeName = opcodeName;
     this.keywords = keywords;
     this.keywordsDescription = keywordsDescription;
     this.version = version;
     this.payload = payload.ToArray();
 }
Example #24
0
        /// <summary>
        /// Add a new logger to the logger pool.
        /// </summary>
        /// <param name="loggerId"></param>
        /// <param name="parentLoggerId"></param>
        /// <returns>The new logger if an existing logger is not found, otherwise the existing logger</returns>
        public static ILogger AddLogger(string loggerId,
            string parentLoggerId,
            EventLevel loggerEventLevel)
        {
            // attempt to find the logger by Id
              ILogger existingLogger = loggerPool.Find(
            delegate(ILogger logger) { return logger.LoggerId == loggerId; });

              // if a logger is found return it,
              if (existingLogger != null) return existingLogger;

              // otherwise add the logger to the logger pool and return it
              ILogger newLogger = new Logger(loggerId, parentLoggerId, loggerEventLevel);
              loggerPool.Add(newLogger);
              return newLogger;
        }
 public static EventEntry Create(
     int eventId = 0,
     Guid providerId = default(Guid),
     string providerName = null,
     EventLevel level = default(EventLevel),
     EventTask task = default(EventTask),
     string taskName = null,
     EventOpcode opcode = default(EventOpcode),
     string opcodeName = null,
     EventKeywords keywords = default(EventKeywords),
     string keywordsDescription = null,
     int version = 0,
     IEnumerable<string> payloadNames = null,
     string formattedMessage = null,
     IEnumerable<object> payload = null,
     DateTimeOffset timestamp = default(DateTimeOffset),
     Guid activityId = default(Guid),
     Guid relatedActivityId = default(Guid),
     int processId = 0,
     int threadId = 0)
 {
     return
         new EventEntry(
             providerId,
             eventId,
             formattedMessage,
             new ReadOnlyCollection<object>((payload ?? Enumerable.Empty<object>()).ToList()),
             timestamp != default(DateTimeOffset) ? timestamp : DateTimeOffset.UtcNow,
             processId,
             threadId,
             activityId,
             relatedActivityId,
             new EventSchema(
                 eventId,
                 providerId,
                 providerName,
                 level,
                 task,
                 taskName,
                 opcode,
                 opcodeName,
                 keywords,
                 keywordsDescription,
                 version,
                 (payloadNames ?? Enumerable.Empty<string>())));
 }
Example #26
0
 /// <summary>
 /// Instanciate New Event Message
 /// </summary>
 /// <param name="level">as event level</param>
 /// <param name="action">as event action</param>
 /// <param name="result">as event result</param>
 /// <param name="data">as event messages in list</param>
 /// <param name="app">as application</param>
 /// <param name="appver">as application version</param>
 /// <param name="opcode">as operation code</param>
 /// <param name="keys">as key words</param>
 /// <param name="uid">us user's identifier</param>
 /// <param name="ip">as client's ip address</param>
 /// <param name="url">as assoicated page url</param>
 public EventMessage(EventLevel level, EventAction action, EventResult result, List<String> data, String app,
                     String appver = "", String opcode = "", String keys = "", String uid = "", String ip = "", String url = "")
 {
     SetBase();
     Level = level;
     Action = action;
     Result = result;
     Data = data;
     Application = app;
     ApplicationVersion = appver;
     OperationCode = opcode;
     KeyWords = keys;
     EventDateTime = DateTime.UtcNow;
     IP = ip;
     URL = url;
     if (!String.IsNullOrEmpty(uid)) UID = new Guid(uid);
 }
Example #27
0
        /// <summary>
        /// Wrapper around writing events
        /// </summary>
        /// <param name="Message">Message to write</param>
        /// <param name="theLevel">The EventLevel</param>
        /// <param name="SpecificID"></param>
        public static void Write(string Message, EventLevel theLevel = EventLevel.Information, int SpecificID = 1, string AppName = ChefServiceInstallerDefinition.ChefServiceName)
        {
            RegisterEventSource(AppName);
            switch (theLevel)
            {
                case EventLevel.Error:
                    EventLog.WriteEntry(AppName, Message, EventLogEntryType.Error, SpecificID);
                    break;

                case EventLevel.Information:
                    EventLog.WriteEntry(AppName, Message, EventLogEntryType.Information, SpecificID);
                    break;

                case EventLevel.Warning:
                    EventLog.WriteEntry(AppName, Message, EventLogEntryType.Warning, SpecificID);
                    break;
            }
        }
        private static LogLevel MapLogLevel(EventLevel level)
        {
            switch (level)
            {
                case EventLevel.Error:
                    return LogLevel.Error;

                case EventLevel.Warning:
                    return LogLevel.Warning;

                case EventLevel.Informational:
                    return LogLevel.Informational;

                case EventLevel.Verbose:
                    return LogLevel.Verbose;

                default:
                    throw new InvalidOperationException();
            }
        }
 /// <summary>
 /// Maps the specified <see cref="System.Diagnostics.Tracing.EventLevel"/> to a <see cref="System.ConsoleColor"/>.
 /// </summary>
 /// <param name="eventLevel">The event level.</param>
 /// <returns>The console color.</returns>
 public virtual ConsoleColor? Map(EventLevel eventLevel)
 {
     switch (eventLevel)
     {
         case EventLevel.Critical:
             return Critical;
         case EventLevel.Error:
             return Error;
         case EventLevel.Warning:
             return Warning;
         case EventLevel.Verbose:
             return Verbose;
         case EventLevel.LogAlways:
             return LogAlways;
         case EventLevel.Informational:
             return Informational;
         default:
             return null;
     }
 }
Example #30
0
        private TraceEventType ConvertLevel(EventLevel level)
        {
            switch (level) {
                case EventLevel.Critical:
                    return TraceEventType.Critical;

                case EventLevel.Error:
                    return TraceEventType.Error;

                case EventLevel.Informational:
                    return TraceEventType.Information;

                case EventLevel.Warning:
                    return TraceEventType.Warning;

                case EventLevel.Verbose:
                case EventLevel.LogAlways:
                default:
                    return TraceEventType.Verbose;
            }
        }
Example #31
0
 public bool IsEnabled(EventLevel level, EventKeywords keywords)
 {
     return(false);
 }
Example #32
0
 public ITracer StartActivity(string activityName, EventLevel level)
 {
     return(new MockTracer());
 }
Example #33
0
 public void AddDiagnosticConsoleEventListener(EventLevel maxVerbosity, Keywords keywordFilter)
 {
     this.listeners.Add(new DiagnosticConsoleEventListener(maxVerbosity, keywordFilter));
 }
Example #34
0
 public ConsoleEventListener(Events eventSource, DateTime baseTime, WarningMapper warningMapper = null, EventLevel level = EventLevel.Verbose, bool captureAllDiagnosticMessages = false, TimeDisplay timeDisplay = TimeDisplay.None, EventMask eventMask = null, DisabledDueToDiskWriteFailureEventHandler onDisabledDueToDiskWriteFailure = null, bool listenDiagnosticMessages = false, bool useCustomPipDescription = false)
     : base(eventSource, baseTime, warningMapper, level, captureAllDiagnosticMessages, timeDisplay, eventMask, onDisabledDueToDiskWriteFailure, listenDiagnosticMessages, useCustomPipDescription)
 {
 }
Example #35
0
 private ListenerRegistration(EventLevel level, Type type, Func <IServiceProvider, object> factory)
 {
     Level   = level;
     Type    = type;
     Factory = factory;
 }
Example #36
0
 public void AddPrettyConsoleEventListener(EventLevel maxVerbosity, Keywords keywordFilter)
 {
     this.listeners.Add(new PrettyConsoleEventListener(maxVerbosity, keywordFilter));
 }
 public static string EventCode(EventLevel level, string eventName, string prefix)
 {
     return($"{GetEventLevelCode(level)}_CHECKOUT_{prefix}_{eventName}");
 }
Example #38
0
 public LogMessage(string message, EventLevel eventLevel)
 {
     Message    = message;
     EventLevel = eventLevel;
 }
Example #39
0
 public ITracer StartActivity(string childActivityName, EventLevel startStopLevel)
 {
     return(this.StartActivity(childActivityName, startStopLevel, null));
 }
Example #40
0
 public virtual void RelatedEvent(EventLevel level, string eventName, EventMetadata metadata, Keywords keyword)
 {
     this.WriteEvent(eventName, level, keyword, metadata, opcode: 0);
 }
Example #41
0
 public MockListener(EventLevel maxVerbosity, Keywords keywordFilter) : base(maxVerbosity, keywordFilter)
 {
 }
        internal static void EnableProvider(TraceEventSession session, Guid providerId, EventLevel level, EventKeywords matchAnyKeyword, bool sendManifest = true)
        {
            // Make explicit the invocation for requesting the manifest from the EventSource (Provider).
            var values = sendManifest ? new Dictionary <string, string>()
            {
                { "Command", "SendManifest" }
            } : null;

            session.EnableProvider(providerId, (TraceEventLevel)level, (ulong)matchAnyKeyword, 0, TraceEventOptions.None, values);
        }
Example #43
0
 public ITracer StartActivity(string childActivityName, EventLevel startStopLevel, EventMetadata startMetadata)
 {
     return(this.StartActivity(childActivityName, startStopLevel, Keywords.None, startMetadata));
 }
Example #44
0
        public Tracer(StreamJsonRpc.JsonRpc pushRpc, string logFilePath, EventLevel logFileVerbosity, EventLevel outputPaneVerbosity)
        {
            Contract.Requires(pushRpc != null);
            Contract.Requires(!string.IsNullOrEmpty(logFilePath));
            Contract.Requires(logFileVerbosity > outputPaneVerbosity, $"Log file verbosity ('{logFileVerbosity}') should be more detailed than output pane verbosity '{outputPaneVerbosity}'.");

            m_logFilePath = logFilePath;
            var outputEventWriter = new OutputWindowEventWriter(
                new OutputWindowReporter(pushRpc),
                File.CreateText(logFilePath),
                outputPaneVerbosity);

            m_loggingListeners = SetupLogging(logFileVerbosity, outputEventWriter);
        }
Example #45
0
 public static void WriteLine(string line, EventLevel el = EventLevel.Logging)
 {
     Write(line + "\n", el);
 }
 /// <summary>
 /// Creates a new instance of <see cref="AzureEventSourceListener"/> that forwards events to <see cref="Console.WriteLine(string)"/>.
 /// </summary>
 /// <param name="level">The level of events to enable.</param>
 public static AzureEventSourceListener CreateConsoleLogger(EventLevel level = EventLevel.Informational)
 {
     return(new AzureEventSourceListener((eventData, text) => Console.WriteLine("[{1}] {0}: {2}", eventData.EventSource.Name, eventData.Level, text), level));
 }
Example #47
0
 public virtual void RelatedEvent(EventLevel level, string eventName, EventMetadata metadata)
 {
     this.RelatedEvent(level, eventName, metadata, Keywords.None);
 }
Example #48
0
 public void AddLogFileEventListener(string logFilePath, EventLevel maxVerbosity, Keywords keywordFilter)
 {
     this.listeners.Add(new LogFileEventListener(logFilePath, maxVerbosity, keywordFilter));
 }
Example #49
0
 public ExceptionLogMessage(Exception ex, EventLevel eventLevel = EventLevel.Error) : base(ex?.Message, eventLevel)
 {
     this.Exception = ex;
 }
Example #50
0
        public TypeAnalysis(
            Type dataType,
            EventDataAttribute?eventAttrib,
            List <Type> recursionCheck)
        {
            IEnumerable <PropertyInfo> propertyInfos = Statics.GetProperties(dataType);
            var propertyList = new List <PropertyAnalysis>();

            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                if (Statics.HasCustomAttribute(propertyInfo, typeof(EventIgnoreAttribute)))
                {
                    continue;
                }

                if (!propertyInfo.CanRead ||
                    propertyInfo.GetIndexParameters().Length != 0)
                {
                    continue;
                }

                MethodInfo?getterInfo = Statics.GetGetMethod(propertyInfo);
                if (getterInfo == null)
                {
                    continue;
                }

                if (getterInfo.IsStatic || !getterInfo.IsPublic)
                {
                    continue;
                }

                Type propertyType     = propertyInfo.PropertyType;
                var  propertyTypeInfo = TraceLoggingTypeInfo.GetInstance(propertyType, recursionCheck);
                EventFieldAttribute?fieldAttribute = Statics.GetCustomAttribute <EventFieldAttribute>(propertyInfo);

                string propertyName =
                    fieldAttribute != null && fieldAttribute.Name != null
                    ? fieldAttribute.Name
                    : Statics.ShouldOverrideFieldName(propertyInfo.Name)
                    ? propertyTypeInfo.Name
                    : propertyInfo.Name;
                propertyList.Add(new PropertyAnalysis(
                                     propertyName,
                                     propertyInfo,
                                     propertyTypeInfo,
                                     fieldAttribute));
            }

            this.properties = propertyList.ToArray();

            foreach (PropertyAnalysis property in this.properties)
            {
                TraceLoggingTypeInfo typeInfo = property.typeInfo;
                this.level     = (EventLevel)Statics.Combine((int)typeInfo.Level, (int)this.level);
                this.opcode    = (EventOpcode)Statics.Combine((int)typeInfo.Opcode, (int)this.opcode);
                this.keywords |= typeInfo.Keywords;
                this.tags     |= typeInfo.Tags;
            }

            if (eventAttrib != null)
            {
                this.level     = (EventLevel)Statics.Combine((int)eventAttrib.Level, (int)this.level);
                this.opcode    = (EventOpcode)Statics.Combine((int)eventAttrib.Opcode, (int)this.opcode);
                this.keywords |= eventAttrib.Keywords;
                this.tags     |= eventAttrib.Tags;
                this.name      = eventAttrib.Name;
            }

            if (this.name == null)
            {
                this.name = dataType.Name;
            }
        }
 /// <summary>
 /// Creates a new instance of <see cref="AzureEventSourceListener"/> that forwards events to <see cref="Trace.WriteLine(object)"/>.
 /// </summary>
 /// <param name="level">The level of events to enable.</param>
 public static AzureEventSourceListener CreateTraceLogger(EventLevel level = EventLevel.Informational)
 {
     return(new AzureEventSourceListener(
                (eventData, text) => Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "[{0}] {1}", eventData.Level, text), eventData.EventSource.Name), level));
 }
 public DiagnosticConsoleEventListener(EventLevel maxVerbosity, Keywords keywordFilter, IEventListenerEventSink eventSink)
     : base(maxVerbosity, keywordFilter, eventSink)
 {
 }
Example #53
0
 /// <inheritdoc />
 public void WriteLine(EventLevel level, string message)
 {
     m_pushRpc
     .NotifyWithParameterObjectAsync(TraceTargetName, LogMessageParams.Create(level, message))
     .IgnoreErrors();
 }
        private static void VerifyEventLevel(MethodInfo eventMethod, EventWrittenEventArgs actualEvent)
        {
            EventLevel expectedLevel = GetEventAttribute(eventMethod).Level;

            AssertEqual(expectedLevel, actualEvent.Level, "Level");
        }
Example #55
0
 public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword)
 {
     this.EnableEvents(eventSource, level, matchAnyKeyword, (IDictionary <string, string>)null);
 }
Example #56
0
        public void GetMetadataForHeartBeatDoesSetsEventLevelToInformationalWhenPlaceholdersHaveBeenCreated()
        {
            Mock <IPlaceholderCollection> mockPlaceholderDb = new Mock <IPlaceholderCollection>(MockBehavior.Strict);
            int filePlaceholderCount   = 0;
            int folderPlaceholderCount = 0;

            mockPlaceholderDb.Setup(x => x.GetCount()).Returns(() => filePlaceholderCount + folderPlaceholderCount);
            mockPlaceholderDb.Setup(x => x.AddFile("test.txt", "1111122222333334444455555666667777788888")).Callback(() => ++ filePlaceholderCount);
            mockPlaceholderDb.Setup(x => x.AddFile("test.txt", "2222233333444445555566666777778888899999")).Callback(() => ++ filePlaceholderCount);
            mockPlaceholderDb.Setup(x => x.AddFile("test.txt", "3333344444555556666677777888889999900000")).Callback(() => ++ filePlaceholderCount);
            mockPlaceholderDb.Setup(x => x.AddPartialFolder("foo")).Callback(() => ++ folderPlaceholderCount);
            mockPlaceholderDb.Setup(x => x.GetFilePlaceholdersCount()).Returns(() => filePlaceholderCount);
            mockPlaceholderDb.Setup(x => x.GetFolderPlaceholdersCount()).Returns(() => folderPlaceholderCount);
            Mock <ISparseCollection> mockSparseDb = new Mock <ISparseCollection>(MockBehavior.Strict);

            mockSparseDb.Setup(x => x.GetAll()).Returns(new HashSet <string>());
            using (MockBackgroundFileSystemTaskRunner backgroundTaskRunner = new MockBackgroundFileSystemTaskRunner())
                using (FileSystemCallbacks fileSystemCallbacks = new FileSystemCallbacks(
                           this.Repo.Context,
                           this.Repo.GitObjects,
                           RepoMetadata.Instance,
                           new MockBlobSizes(),
                           gitIndexProjection: null,
                           backgroundFileSystemTaskRunner: backgroundTaskRunner,
                           fileSystemVirtualizer: null,
                           placeholderDatabase: mockPlaceholderDb.Object,
                           sparseCollection: mockSparseDb.Object))
                {
                    fileSystemCallbacks.OnPlaceholderFileCreated("test.txt", "1111122222333334444455555666667777788888", "GVFS.UnitTests.exe");

                    EventMetadata metadata   = fileSystemCallbacks.GetAndResetHeartBeatMetadata(out bool writeToLogFile);
                    EventLevel    eventLevel = writeToLogFile ? EventLevel.Informational : EventLevel.Verbose;
                    eventLevel.ShouldEqual(EventLevel.Informational);

                    // "ModifiedPathsCount" should be 1 because ".gitattributes" is always present
                    metadata.Count.ShouldEqual(8);
                    metadata.ContainsKey("FilePlaceholderCreation").ShouldBeTrue();
                    metadata.TryGetValue("FilePlaceholderCreation", out object fileNestedMetadata);
                    JsonConvert.SerializeObject(fileNestedMetadata).ShouldContain("\"ProcessName1\":\"GVFS.UnitTests.exe\"");
                    JsonConvert.SerializeObject(fileNestedMetadata).ShouldContain("\"ProcessCount1\":1");
                    metadata.ShouldContain("ModifiedPathsCount", 1);
                    metadata.ShouldContain("FilePlaceholderCount", 1);
                    metadata.ShouldContain("FolderPlaceholderCount", 0);
                    metadata.ShouldContain(nameof(RepoMetadata.Instance.EnlistmentId), RepoMetadata.Instance.EnlistmentId);
                    metadata.ContainsKey("PhysicalDiskInfo").ShouldBeTrue();

                    // Create more placeholders
                    fileSystemCallbacks.OnPlaceholderFileCreated("test.txt", "2222233333444445555566666777778888899999", "GVFS.UnitTests.exe2");
                    fileSystemCallbacks.OnPlaceholderFileCreated("test.txt", "3333344444555556666677777888889999900000", "GVFS.UnitTests.exe2");
                    fileSystemCallbacks.OnPlaceholderFolderCreated("foo", "GVFS.UnitTests.exe2");

                    // Hydrate a file
                    fileSystemCallbacks.OnPlaceholderFileHydrated("GVFS.UnitTests.exe2");

                    metadata   = fileSystemCallbacks.GetAndResetHeartBeatMetadata(out bool writeToLogFile2);
                    eventLevel = writeToLogFile2 ? EventLevel.Informational : EventLevel.Verbose;
                    eventLevel.ShouldEqual(EventLevel.Informational);

                    metadata.Count.ShouldEqual(8);

                    // Only processes that have created placeholders since the last heartbeat should be named
                    metadata.ContainsKey("FilePlaceholderCreation").ShouldBeTrue();
                    metadata.TryGetValue("FilePlaceholderCreation", out object fileNestedMetadata2);
                    JsonConvert.SerializeObject(fileNestedMetadata2).ShouldContain("\"ProcessName1\":\"GVFS.UnitTests.exe2\"");
                    JsonConvert.SerializeObject(fileNestedMetadata2).ShouldContain("\"ProcessCount1\":2");
                    metadata.ContainsKey("FolderPlaceholderCreation").ShouldBeTrue();
                    metadata.TryGetValue("FolderPlaceholderCreation", out object folderNestedMetadata2);
                    JsonConvert.SerializeObject(folderNestedMetadata2).ShouldContain("\"ProcessName1\":\"GVFS.UnitTests.exe2\"");
                    JsonConvert.SerializeObject(folderNestedMetadata2).ShouldContain("\"ProcessCount1\":1");
                    metadata.ContainsKey("FilePlaceholdersHydrated").ShouldBeTrue();
                    metadata.TryGetValue("FilePlaceholdersHydrated", out object hydrationNestedMetadata2);
                    JsonConvert.SerializeObject(hydrationNestedMetadata2).ShouldContain("\"ProcessName1\":\"GVFS.UnitTests.exe2\"");
                    JsonConvert.SerializeObject(hydrationNestedMetadata2).ShouldContain("\"ProcessCount1\":1");
                    metadata.ShouldContain("ModifiedPathsCount", 1);
                    metadata.ShouldContain("FilePlaceholderCount", 3);
                    metadata.ShouldContain("FolderPlaceholderCount", 1);
                    metadata.ShouldContain(nameof(RepoMetadata.Instance.EnlistmentId), RepoMetadata.Instance.EnlistmentId);
                    metadata.ContainsKey("PhysicalDiskInfo").ShouldBeTrue();
                }

            mockPlaceholderDb.VerifyAll();
            mockSparseDb.VerifyAll();
        }
Example #57
0
 public void EnableEvents(EventSource eventSource, EventLevel level)
 {
     this.EnableEvents(eventSource, level, EventKeywords.None);
 }
Example #58
0
 public ITracer StartActivity(string activityName, EventLevel level, Keywords startStopKeywords, EventMetadata metadata)
 {
     return(new MockTracer());
 }
Example #59
0
 protected override void Output(EventLevel level, int id, string eventName, EventKeywords eventKeywords, string text, bool doNotTranslatePaths = false)
 {
     Console.WriteLine($"[{DateTime.Now:HH:mm:ss.ff}] {text}");
 }
Example #60
0
        private JsonEtwTracer(List <InProcEventListener> listeners, Guid parentActivityId, string activityName, EventLevel startStopLevel, Keywords startStopKeywords)
        {
            this.listeners         = listeners;
            this.parentActivityId  = parentActivityId;
            this.activityName      = activityName;
            this.startStopLevel    = startStopLevel;
            this.startStopKeywords = startStopKeywords;

            this.activityId = Guid.NewGuid();
        }