Example #1
0
        /// <summary>
        /// Formats the lines of text to be output then writes them to the log.
        /// </summary>
        /// <param name="logEntryFields">Fields to write to the log.</param>
        /// <param name="doWriteLine">Determines whether to perform a WriteLine or a Write to the log.</param>
        /// <returns>True if successful.</returns>
        protected override bool WriteToCustomLog(LogEntryFields logEntryFields, bool doWriteLine)
        {
            bool isOK = false;

            FormattedLogEntry formattedLogEntry = this.GetFormattedLinesToWrite(logEntryFields, doWriteLine);

            if (formattedLogEntry.LinesToWrite.Count > 0)
            {
                isOK = this.WriteToCustomLog(formattedLogEntry, doWriteLine);
            }
            else
            {
                isOK = true;
            }
            return(isOK);
        }
Example #2
0
        /// <summary>
        /// Writes the log message to whichever forms have added themselves to the forms collection.
        /// </summary>
        /// <param name="formattedLogEntry">Structure that wraps the formatted lines of text that will be written
        /// to the log and the category or EventType that applies to the log entry.</param>
        /// <param name="doWriteLine">Determines whether to perform a WriteLine or a Write to the log.</param>
        /// <returns>True if successful.</returns>
        private bool WriteToCustomLog(FormattedLogEntry formattedLogEntry, bool doWriteLine)
        {
            bool isOK = false;

            try
            {
                StringBuilder messageBuilder = new StringBuilder();
                foreach (string lineToWrite in formattedLogEntry.LinesToWrite)
                {
                    if (doWriteLine)
                    {
                        messageBuilder.AppendLine(lineToWrite);
                    }
                    else
                    {
                        messageBuilder.Append(lineToWrite);
                    }
                }

                LogMessageEventArgs logMessageEventArgs
                    = new LogMessageEventArgs(messageBuilder.ToString(),
                                              formattedLogEntry.Properties);
                LogMessageEventHandler eventHandler = LogMessageEvent;
                if (eventHandler != null)
                {
                    eventHandler(this, logMessageEventArgs);
                }

                isOK = true;
            }
            catch
            {
                isOK = false;
            }
            return(isOK);
        }
        /// <summary>
        /// Method that actually writes the log message to the file.
        /// </summary>
        /// <param name="formattedLogEntry">Structure that includes the formatted lines of text
        /// that will be written to the log and the category or EventType that applies to the
        /// log entry.</param>
        /// <param name="doWriteLine">Determines whether to perform a WriteLine or a Write to the
        /// log.</param>
        /// <param name="logFileName">The full name, including path, of the file that the log
        /// entry will be written to.  Excludes any date suffix to the filename.</param>
        /// <param name="fileNameIncludesDate">true if the log filename should include a date, eg
        /// C:\Logs\MyLogFile_20070219.log.  false if the log filename should not include a date,
        /// eg C:\Logs\MyLogFile.log.</param>
        /// <returns>true if successful, otherwise false.</returns>
        private bool WriteToCustomLog(FormattedLogEntry formattedLogEntry, bool doWriteLine,
                                      string logFileName, bool fileNameIncludesDate)
        {
            bool isOK = false;

            try
            {
                // Add date suffix to file name, if required.
                if (fileNameIncludesDate)
                {
                    string dateText = DateTime.Now.ToString("_yyyyMMdd.");
                    // Use home-made ReplaceLast method, rather than built-in string.Replace,
                    //	to deal with paths that contain a "." .  Only want to replace the "."
                    //	before the file extension, not every "." in the path.
                    logFileName = this.ReplaceLast(logFileName, ".", dateText);
                }

                StreamWriter writer = null;
                if (File.Exists(logFileName))
                {
                    writer = File.AppendText(logFileName);
                }
                else
                {
                    writer = new StreamWriter(logFileName);
                }

                // Emphasize any log entry (by writing it in upper case) if its category is one of
                //	the categories to emphasize, or its source is one of the sources to emphasize,
                //	etc.
                //	NB: cannot use List.Contains method for string comparisons - this is
                //	case-sensitive and want to do a case-insensitive comparison.
                LogEntryProperties logEntryProperties      = formattedLogEntry.Properties;
                StringComparer     caseInsensitiveComparer = StringComparer.CurrentCultureIgnoreCase;
                bool emphasizeLogEntry
                    = (_categoriesToEmphasize.BinarySearch(logEntryProperties.Category,
                                                           caseInsensitiveComparer) >= 0) ||
                      (_sourcesToEmphasize.BinarySearch(logEntryProperties.Source,
                                                        caseInsensitiveComparer) >= 0) ||
                      (_methodsToEmphasize.BinarySearch(logEntryProperties.MethodThatWroteToLog,
                                                        caseInsensitiveComparer) >= 0) ||
                      (_threadIDsToEmphasize.BinarySearch(logEntryProperties.ThreadID,
                                                          caseInsensitiveComparer) >= 0) ||
                      (_eventIDsToEmphasize.Contains(logEntryProperties.EventID)) ||
                      (_processIDsToEmphasize.Contains(logEntryProperties.ProcessID));

                string textToWrite = string.Empty;
                foreach (string lineToWrite in formattedLogEntry.LinesToWrite)
                {
                    if (emphasizeLogEntry)
                    {
                        textToWrite = lineToWrite.ToUpper();
                    }
                    else
                    {
                        textToWrite = lineToWrite;
                    }

                    if (doWriteLine)
                    {
                        writer.WriteLine(textToWrite);
                    }
                    else
                    {
                        writer.Write(textToWrite);
                    }
                }

                writer.Flush();
                writer.Close();
                writer.Dispose();
                isOK = true;
            }
            catch
            {
                isOK = false;
            }
            return(isOK);
        }
Example #4
0
        /// <summary>
        /// Returns the lines of text that will be written to the log.  Reads format strings and replaces the
        /// placeholders with the data that is to be written to the log.
        /// </summary>
        /// <param name="logEntryFields">Fields to write to the log.</param>
        /// <param name="doWriteLine">Determines whether to perform a WriteLine or a Write to the log.</param>
        /// <returns>FormattedLogEntry structure that wraps the formatted lines of text that will be written to the log
        /// and the category or EventType that applies to the log entry.</returns>
        /// <remarks>If no format strings have been set, default format strings will be used.</remarks>
        protected virtual FormattedLogEntry GetFormattedLinesToWrite(LogEntryFields logEntryFields, bool doWriteLine)
        {
            FormattedLogEntry logEntry      = new FormattedLogEntry();
            List <string>     linesToWrite  = new List <string>();
            List <string>     formatStrings = new List <string>();

            // If no formatting strings have been defined, use defaults.
            if (_formatStrings.Count == 0)
            {
                formatStrings.Add("{DATE:yyyy-MM-dd HH:mm:ss} {CATEGORY} {METHOD} (ID: {EVENT_ID:000}): {MESSAGE}");
                formatStrings.Add("{INDENT}Process ID: {PROCESS_ID}; Thread ID: {THREAD_ID}.");
                formatStrings.Add("{INDENT}Detailed Failure Message: {DETAILED_MESSAGE}");
                formatStrings.Add("{INDENT}Call Stack: {CALL_STACK}");
                formatStrings.Add("{INDENT}Logical Operation Stack: {LOGICAL_OPERATION_STACK}");
                formatStrings.Add("{INDENT}Related Activity ID: {RELATED_ACTIVITY_ID}");
            }
            else
            {
                formatStrings = _formatStrings;
            }

            LogEntryProperties logEntryProperties = new LogEntryProperties();

            logEntryProperties.Category             = logEntryFields.Category;
            logEntryProperties.Source               = logEntryFields.Source;
            logEntryProperties.MethodThatWroteToLog = logEntryFields.MethodThatWroteToLog;
            logEntryProperties.EventID              = logEntryFields.EventID;
            logEntryProperties.ThreadID             = logEntryFields.ThreadID;
            logEntryProperties.ProcessID            = logEntryFields.ProcessID;
            logEntry.Properties = logEntryProperties;

            logEntry.LinesToWrite = new List <string>();
            string lineToWrite = string.Empty;

            foreach (string formatString in formatStrings)
            {
                bool wasDataInserted         = false;
                bool morePlaceholdersToCheck = true;
                lineToWrite = formatString;
                string spaces = new string(' ', this.IndentSize);
                lineToWrite = lineToWrite.Replace("{INDENT}", spaces);
                lineToWrite = ReplaceFormattedPlaceholder <DateTime>(lineToWrite, "{DATE}", logEntryFields.EventDateTime,
                                                                     DateTime.MinValue, ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{MESSAGE}", logEntryFields.Message,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{DETAILED_MESSAGE}", logEntryFields.DetailedMessage,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{APPLICATION}", this.ApplicationName,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{SOURCE}", logEntryFields.Source,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{METHOD}", logEntryFields.MethodThatWroteToLog,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{CATEGORY}", logEntryFields.Category,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{EVENT_TYPE}", logEntryFields.Category,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceFormattedPlaceholder <Int32>(lineToWrite, "{EVENT_ID}", logEntryFields.EventID, 0,
                                                                  ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceFormattedPlaceholder <Int32>(lineToWrite, "{PROCESS_ID}", logEntryFields.ProcessID, 0,
                                                                  ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{THREAD_ID}", logEntryFields.ThreadID,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{CALL_STACK}", logEntryFields.CallStack,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{LOGICAL_OPERATION_STACK}", logEntryFields.LogicalOperationStack,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                lineToWrite = ReplaceTextPlaceholder(lineToWrite, "{RELATED_ACTIVITY_ID}", logEntryFields.RelatedActivityID,
                                                     ref wasDataInserted, ref morePlaceholdersToCheck);
                if (wasDataInserted)
                {
                    logEntry.LinesToWrite.Add(lineToWrite);
                }
            }

            return(logEntry);
        }