예제 #1
0
        //An Overload of the Logit Method to log to both the Console && a Text File...

        public static void LogIt(string msgToLog, MessageSeverity severity, bool logFileYesNo)
        {
            //This OVERLOAD of our "Utilitarian - LogIt() Method will log to both the CONOLSE and a LOG FILE

            // Firstly, let's Log our MESSAGE and SEVERITY to the Console, so the user can see
            System.Console.WriteLine(severity.ToString() + " -- " + msgToLog);

            // NOTE Before continuing to write to the File, you should REMEMBER that you are preparing to Do I/O.
            // ALL I/O should be GUARD-=BLOCKED (Implement PROPER EXCEPTION HANDLING)
            // Now a little "Prep-Work" to write the same MESSAGE & SEVERITY to the LogFile...
            string LogFile = @"C:\Users\student\Documents\LogFiles\LogFile.txt";      //Use a RELATIVE PATH (from the 'cwd')

            // NOTE - NOTE - NOTE -
            // When you are doing File I/O, you should "GUARD-BLOCK" your code (which means, do EXCEPTION HANDLING!!!)
            try
            {
                // Check to see that our LogFile EXISTS in the proper directory...
                if (doExtraDebugoutput)
                {
                    Console.WriteLine(File.Exists(LogFile) ? "Log File exists." : "Log File does not exist."); //Some Console Output
                }
                if (!File.Exists(LogFile))                                                                     //If the Folder (directory) does not exist, we must first CREATE IT.
                {
                    System.IO.Directory.CreateDirectory(@"C:\Users\student\Documents\TextFiles");              //Now, we should have our Folder and LogFile created
                    System.Console.WriteLine(@"LogIt :: LogFile Folder created in C:\Users\student\Documents\...");
                }
                // Now, using a 'USING' statement, write the msgToLog string to the LogFile...
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(LogFile, true)) //DO NOT FORGET THE 'APPEND-TRUE' PARAMETER!!!
                {
                    file.WriteLine(severity.ToString() + " -- " + msgToLog);
                    file.Close();
                }
            }   // END of Guard-Block (try-block)...

            catch (Exception e)
            {
                string excptMsg = "EXCEPTION IN UTILITIES::LogIt(): " +
                                  e.Message.ToString() + " :: Caused by Inner Exception = " + e.InnerException.ToString() +
                                  ":: Exception SOURCE = " + e.Source +
                                  ":: Stack Trace Output = " + e.StackTrace + "END-OF-EXCEPTION STUFF";
                Utilities.LogIt(excptMsg,
                                MessageSeverity.EXCEPTION,
                                false);
            }   // End of this SPECIFIC Catch-Handler...

            //finally
            //{
            //    // If a 'finally' block exists, the CLR will try to execute the code within it, regardless of exception or NORMAL
            //    //... program flow.
            //    // This is where you would "Release" any used Resources, like Open Files, Open DB Connections, Ports you used, etc.
            //    // For now, we will simply demonstrate that this 'finally-block' does execute...
            //LogIt("Utilities:: LogIt(): Executing Finally Block after doing LogFile I/O...",
            //    MessageSeverity.INFORMATIONAL, logFileYesNo);
            //}   // END - of Finally-Block
        }
예제 #2
0
        protected internal override void Log(string message, MessageSeverity severity)
        {
            lock (_syncRoot)
            {
                var prevColor = Console.ForegroundColor;
                try
                {
                    switch (severity)
                    {
                    case MessageSeverity.Information:
                        Console.ForegroundColor = InfoColor;
                        break;

                    case MessageSeverity.Warning:
                        Console.ForegroundColor = WarningColor;
                        break;

                    case MessageSeverity.Error:
                        Console.ForegroundColor = ErrorColor;
                        break;

                    default:
                        break;
                    }
                    Log(Formatter(severity.ToString(), TrimExcess(message)));
                    ++Sucesses;
                }
                finally
                {
                    Console.ForegroundColor = prevColor;
                }
            }
        }
예제 #3
0
 protected internal override void Log(string message, MessageSeverity severity)
 {
     OutputDocument.Root.Add(new XElement(EntryElementName,
                                          new XElement(TimeElementName, DateTime.Now),
                                          new XElement(DescriptionElementName, message),
                                          new XElement(TypeElementName, severity.ToString())));
 }
예제 #4
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="Message"></param>
		/// <param name="Severity"></param>
		public override void RecordMessage(string Message, MessageSeverity Severity)
		{
			FileStream fileStream = null;
			StreamWriter writer = null;
			StringBuilder message = new StringBuilder();

 
			// Create the message
			message.Append("["+DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentUICulture));
			message.Append(", " + Severity.ToString());
			message.Append("]\r\n" + Message + "\r\n");

			lock(this) 
			{
				string filePath = getAbsoluteFilePath();
				fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
				using (writer = new StreamWriter(fileStream))
				{
					// Set the file pointer to the end of the file
					writer.BaseStream.Seek(0, SeekOrigin.End); 
				
					// Force the write to the underlying file
					writer.WriteLine(message.ToString());
					writer.Flush();
					if( writer != null ) writer.Close();
				}
			}
		}
        public void Receive(MessageSeverity severity)
        {
            var message   = new Log();
            var queueName = _channel.QueueDeclare().QueueName;

            _channel.QueueBind(queueName, "logs", severity.ToString());

            var consumer = new EventingBasicConsumer(_channel);

            consumer.Received += (model, ea) =>
            {
                message = DataConverter(ea.Body);
                var routingKey = ea.RoutingKey;

                SendToDal(message);

                if (severity == MessageSeverity.Error)
                {
                    WriteToFile(message);
                }

                Console.WriteLine($"[x] Message received with severity: {message.Severity}. Title: {message.Title}, Detail: {message.Details}");
            };

            _channel.BasicConsume(queueName, true, consumer);
        }
예제 #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Message"></param>
        /// <param name="Severity"></param>
        public override void RecordMessage(string Message, MessageSeverity Severity)
        {
            FileStream    fileStream = null;
            StreamWriter  writer     = null;
            StringBuilder message    = new StringBuilder();


            // Create the message
            message.Append("[" + DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentUICulture));
            message.Append(", " + Severity.ToString());
            message.Append("]\r\n" + Message + "\r\n");

            lock (this)
            {
                string filePath = getAbsoluteFilePath();
                fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
                using (writer = new StreamWriter(fileStream))
                {
                    // Set the file pointer to the end of the file
                    writer.BaseStream.Seek(0, SeekOrigin.End);

                    // Force the write to the underlying file
                    writer.WriteLine(message.ToString());
                    writer.Flush();
                    if (writer != null)
                    {
                        writer.Close();
                    }
                }
            }
        }
예제 #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Message"></param>
        /// <param name="Severity"></param>
        public override void RecordMessage(string Message, MessageSeverity Severity)
        {
            StringBuilder message = new StringBuilder();

            message.Append("[" + DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentUICulture));
            message.Append(", " + Severity.ToString());
            message.Append("]\r\n" + Message + "\r\n");

            // Force the write to the underlying file
            Console.WriteLine(message);
        }
예제 #8
0
 public async Task LogMessageAsync(MessageSeverity severity, string message)
 {
     if (this.PrefixSeverity)
     {
         await StringWriter.WriteLineAsync($"{severity.ToString()}: {message}");
     }
     else
     {
         await StringWriter.WriteLineAsync(message);
     }
 }
예제 #9
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="Message"></param>
		/// <param name="Severity"></param>
		public override void RecordMessage(string Message, MessageSeverity Severity)
		{
			StringBuilder message = new StringBuilder();

			message.Append("["+DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentUICulture));
			message.Append(", " + Severity.ToString());
			message.Append("]\r\n" + Message + "\r\n");

			// Force the write to the underlying file
			Console.WriteLine(message);
		}
        public void AddLogMessage(MessageSeverity severity, string message)
        {
            if (this.logListView.Items.Count >= MaxLogSize)
            {
                this.logListView.Items.RemoveAt(0);
            }

            var text = string.Format("{0} [{1:HH:mm:ss.fff}] {2}", severity.ToString().ToUpper(), DateTime.Now, message);
            this.logListView.Items.Add(text);
            this.logListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            this.logListView.TopItem = this.logListView.Items[this.logListView.Items.Count - 1];
        }
예제 #11
0
        public void AddLogMessage(MessageSeverity severity, string message)
        {
            if (this.logListView.Items.Count >= MaxLogSize)
            {
                this.logListView.Items.RemoveAt(0);
            }

            var text = string.Format("{0} [{1:HH:mm:ss.fff}] {2}", severity.ToString().ToUpper(), DateTime.Now, message);

            this.logListView.Items.Add(text);
            this.logListView.Columns[0].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
            this.logListView.TopItem = this.logListView.Items[this.logListView.Items.Count - 1];
        }
예제 #12
0
        /// <summary>Reports analyser warning.</summary>
        /// <param name="competitionState">State of the run.</param>
        /// <param name="warnings">The list the warnings will be added to.</param>
        /// <param name="severity">Severity of the message.</param>
        /// <param name="message">The message.</param>
        /// <param name="report">The report the message belongs to.</param>
        public static void AddAnalyserWarning(
            [NotNull] this CompetitionState competitionState,
            [NotNull] List <IWarning> warnings,
            MessageSeverity severity,
            [NotNull] string message,
            BenchmarkReport report = null)
        {
            Code.NotNull(competitionState, nameof(competitionState));
            Code.NotNull(warnings, nameof(warnings));
            Code.NotNullNorEmpty(message, nameof(message));

            competitionState.WriteMessage(MessageSource.Analyser, severity, message);
            warnings.Add(new Warning(severity.ToString(), message, report));
        }
예제 #13
0
        private DiagnosticSeverity ConvertSeverity(MessageSeverity severity)
        {
            switch (severity)
            {
            case MessageSeverity.Error:
                return(DiagnosticSeverity.Error);

            case MessageSeverity.Warning:
                return(DiagnosticSeverity.Warning);

            default:
                throw new NotImplementedException(severity.ToString());
            }
        }
예제 #14
0
        protected string FormatSeverity(MessageSeverity severity)
        {
            switch (severity)
            {
            case MessageSeverity.Debug: return("DebugInfo");

            case MessageSeverity.Information: return(string.Empty);

            case MessageSeverity.Warning: return("WARN!");

            case MessageSeverity.Error: return("!!! ERROR !!!");
            }

            return(severity.ToString().ToLower());
        }
예제 #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Message"></param>
        /// <param name="Severity"></param>
        public override void RecordMessage(string Message, MessageSeverity Severity)
        {
            StringBuilder message = new StringBuilder();

            System.Diagnostics.EventLog eventLog = new System.Diagnostics.EventLog();

            // Create the source if it does not already exist
            if (!System.Diagnostics.EventLog.SourceExists(mEventLogSource))
            {
                System.Diagnostics.EventLog.CreateEventSource(mEventLogSource, mEventLogName);
            }
            eventLog.Source      = mEventLogSource;
            eventLog.MachineName = mMachineName;

            // Determine what the EventLogEventType should be
            // based on the LogSeverity passed in
            EventLogEntryType type = EventLogEntryType.Information;

            switch (Severity)
            {
            case MessageSeverity.Informational:
                type = EventLogEntryType.Information;
                break;

            case MessageSeverity.Failure:
                type = EventLogEntryType.FailureAudit;
                break;

            case MessageSeverity.Warning:
                type = EventLogEntryType.Warning;
                break;

            case MessageSeverity.Error:
                type = EventLogEntryType.Error;
                break;
            }


            message.Append("[" + DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentUICulture));
            message.Append(", " + Severity.ToString());
            message.Append("]\r\n" + Message + "\r\n");

            eventLog.WriteEntry(message.ToString(), type);
        }
예제 #16
0
 protected internal override void Log(string message, MessageSeverity severity)
 {
     Log(Formatter(severity.ToString(), TrimExcess(message)));
 }
예제 #17
0
        public async Task LogMessageAsync(MessageSeverity severity, string message)
        {
            if (this.IsEnabled(severity))
            {
                await _writer.WriteLineAsync($"{DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")} {severity.ToString().ToUpper()} {message}");

                // I'm intentioanlly not awaiting this
                _writer.FlushAsync();
            }
        }
예제 #18
0
파일: EventLogger.cs 프로젝트: fudder/cs493
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Message"></param>
        /// <param name="Severity"></param>
        public override void RecordMessage(string Message, MessageSeverity Severity)
        {
            StringBuilder message = new StringBuilder();
            System.Diagnostics.EventLog eventLog = 	new System.Diagnostics.EventLog();

            // Create the source if it does not already exist
            if( !System.Diagnostics.EventLog.SourceExists(mEventLogSource) )
            {
                System.Diagnostics.EventLog.CreateEventSource(mEventLogSource, mEventLogName);
            }
            eventLog.Source = mEventLogSource;
            eventLog.MachineName = mMachineName;

            // Determine what the EventLogEventType should be
            // based on the LogSeverity passed in
            EventLogEntryType type = EventLogEntryType.Information;

            switch(Severity)
            {
                case MessageSeverity.Informational:
                    type = EventLogEntryType.Information;
                    break;
                case MessageSeverity.Failure:
                    type = EventLogEntryType.FailureAudit;
                    break;
                case MessageSeverity.Warning:
                    type = EventLogEntryType.Warning;
                    break;
                case MessageSeverity.Error:
                    type = EventLogEntryType.Error;
                    break;
            }

            message.Append("["+DateTime.Now.ToString(System.Globalization.CultureInfo.CurrentUICulture));
            message.Append(", " + Severity.ToString());
            message.Append("]\r\n" + Message + "\r\n");

            eventLog.WriteEntry(message.ToString(), type);
        }
        public void PrintToScreen(string message, MessageSeverity severity)
        {
            var caption = severity == MessageSeverity.None ? MessageSeverity.Information.ToString() : severity.ToString();

            PrintToScreen(message, caption, severity);
        }
 private string GetFriendlyName(MessageSeverity severity) => severity.ToString();