Exemple #1
0
 public LogMessage(
     DateTimeOffset timestamp, string category, LogMessagePriority priority,
     string message, string details = null)
 {
     Timestamp = timestamp;
     Category = category;
     Priority = priority;
     Message = message;
     Details = (details ?? "");
 }
Exemple #2
0
        /// <summary>
        /// Creates a new log file.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="append">Optional. Indicates whether new messages should be appendet to an already existing file. If false an possble old file is overwritten.</param>
        /// <param name="priority">Optional. The priority of this log file.</param>
        public LogFile(string fileName, bool append = false, LogMessagePriority priority = LogMessagePriority.Low)
            : base(priority)
        {
            FileStream stream = File.Open(fileName, append ? FileMode.Append : FileMode.Create, FileAccess.ReadWrite);
            writer = new StreamWriter(stream);
            writer.AutoFlush = true;
            if (append && stream.Length > 0)
                writer.WriteLine(string.Concat(Enumerable.Repeat(writer.NewLine, 3)));

            locker = new object();
        }
Exemple #3
0
        /// <summary>
        /// Creates a new log file.
        /// </summary>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="append">Optional. Indicates whether new messages should be appendet to an already existing file. If false an possble old file is overwritten.</param>
        /// <param name="priority">Optional. The priority of this log file.</param>
        public LogFile(string fileName, bool append = false, LogMessagePriority priority = LogMessagePriority.Low)
            : base(priority)
        {
            FileStream stream = File.Open(fileName, append ? FileMode.Append : FileMode.Create, FileAccess.ReadWrite);

            writer           = new StreamWriter(stream);
            writer.AutoFlush = true;
            if (append && stream.Length > 0)
            {
                writer.WriteLine(string.Concat(Enumerable.Repeat(writer.NewLine, 3)));
            }

            locker = new object();
        }
Exemple #4
0
 public LogMessage(
     DateTimeOffset timestamp, string category, LogMessagePriority priority,
     string message, string details = null)
 {
     Timestamp = timestamp;
     Category = category;
     // lets clean this mess a bit
     Category = Category.Replace("Aldurcraft.", string.Empty);
     Category = Category.Replace("WurmOnline.", string.Empty);
     Category = Category.Replace("Utility.", string.Empty);
     Category = Category.Replace("WurmAssistant2.", string.Empty);
     Category = Category.Replace("ModuleNS.", "Modules >");
     Priority = priority;
     Message = message;
     Details = (details ?? "");
 }
Exemple #5
0
        internal static void WriteException(string message, string category, LogMessagePriority priority, Exception e, bool warningsound = false)
        {
            try
            {
                UpdateErrorCounts(priority);

                if (warningsound) System.Media.SystemSounds.Hand.Play();

                string mess = "";
                if (!string.IsNullOrEmpty(message)) mess += message + "\r\n";
                mess += String.Format("EXCEPTION: {0}", e.Message);
                string detail = String.Format("\r\nEXC TYPE:{0}\r\nSOURCE: {1}\r\nTRACE: {2}", e.GetType(), e.Source, e.StackTrace);

                string cat = category;

                LogMessage logmessage = new LogMessage(DateTimeOffset.Now, cat, priority, mess, detail);

                ForwardLogMessage(logmessage, category);
            }
            catch (Exception _e)
            {
                Debug.WriteLine("LOGGER ERROR!");
                Debug.WriteLine(_e.Message);
                Debug.WriteLine(_e.Source);
                Debug.WriteLine(_e.StackTrace);
            }
        }
Exemple #6
0
        internal static void WriteText(string message, string category, LogMessagePriority priority)
        {
            try
            {
                UpdateErrorCounts(priority);
                string cat = category;
                LogMessage logmessage = new LogMessage(DateTimeOffset.Now, cat, priority, message);

                ForwardLogMessage(logmessage, category);
            }
            catch (Exception _e)
            {
                Debug.WriteLine("LOGGER ERROR!");
                Debug.WriteLine(_e.Message);
                Debug.WriteLine(_e.Source);
                Debug.WriteLine(_e.StackTrace);
            }
        }
Exemple #7
0
        /// <summary>
        /// Set a winforms TextBox as an output target. Updated in thread safe way. Set null to disable. Default null.
        /// </summary>
        /// <param name="tb">Should be set for multiline, will only update the text</param>
        /// <param name="priorityTresh">(optional) Priority treshhold at which message should be forwarded to TextBox</param>
        /// <param name="pruneAt">(optional) Will remove oldest entries once number of lines in TextBox hits this number, default 500</param>
        /// <param name="pruneQuantity">(optional) Will prune this amount of oldest entries form TextBox, default 50</param>
        public static void SetTBOutput(TextBox tb, LogMessagePriority priorityTresh = LogMessagePriority.Info, int pruneAt = 500, int pruneQuantity = 50)
        {
#if DEBUG
            priorityTresh = LogMessagePriority.Debug;
#endif
            tbOutput = tb;
            priorityTreshhold = priorityTresh;
            if (pruneQuantity > pruneAt) pruneQuantity = pruneAt - 1;
            PruneAT = pruneAt;
            PruneQuantityToKeep = pruneAt - pruneQuantity;

            if (CacheForTBOut)
            {
                CacheForTBOut = false;
                while (CachedForTBOut.Count > 0)
                {
                    SendMessageToTextBoxOutput(CachedForTBOut.Dequeue());
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Posts a log message to all registered loggers.
        /// </summary>
        /// <param name="message">The message to post.</param>
        /// <param name="messageKind">Optional. The kind of the message.</param>
        /// <param name="messagePriority">Optional. The priority of the message.</param>
        /// <exception cref="System.ArgumentNullException">Is thrown if message is null.</exception>
        public static void PostGlobalLogMessage(string message, LogMessageKind messageKind = LogMessageKind.None, LogMessagePriority messagePriority = LogMessagePriority.Low)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            lock (LoggersLocker)
            {
                foreach (var logger in Loggers)
                {
                    logger.PostMessage(message, messageKind, messagePriority);
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Posts a message to the logger output.
        /// </summary>
        /// <param name="message">The message to post.</param>
        /// <param name="messageKind">Optional. The kind of the message.</param>
        /// <param name="messagePriority">Optional. The priority of the message.</param>
        /// <remarks>
        /// A message kind different from none will be indicated by a prefix in the output.
        /// If the message priority is smaller then the priority of the logger, the message will not be postet.
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">Is thrown if message is null.</exception>
        public void PostMessage(string message, LogMessageKind messageKind = LogMessageKind.None, LogMessagePriority messagePriority = LogMessagePriority.Low)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (messagePriority >= Priority)
            {
                var messageParts = new List <string>();
                if (IncludeTimeStamp)
                {
                    messageParts.Add(string.Concat("[", DateTime.Now.ToString(TimestampFormat), "]"));
                }
                if (messageKind != LogMessageKind.None)
                {
                    messageParts.Add(MessageKindStrings[messageKind]);
                }
                messageParts.Add(message);

                this.SendToOutput(string.Join(" ", messageParts));
            }
        }
Exemple #10
0
 protected Logger(bool includeTimeStamp, string timestampFormat)
 {
     IncludeTimeStamp = includeTimeStamp;
     TimestampFormat  = timestampFormat;
     Priority         = LogMessagePriority.Low;
 }
Exemple #11
0
        internal void WriteException(string message, string category, LogMessagePriority priority, Exception e, bool warningsound = false)
        {
            try
            {
                UpdateErrorCounts(priority);

                if (warningsound) System.Media.SystemSounds.Hand.Play();

                string mess = "";
                if (!string.IsNullOrEmpty(message)) mess += message + "\r\n";
                mess += "EXCEPTIONS: ";
                var sb = new StringBuilder();
                WriteExceptions(sb, e);

                string cat = category;

                LogMessage logmessage = new LogMessage(DateTimeOffset.Now, cat, priority, mess, sb.ToString());

                ForwardLogMessage(logmessage, category);
            }
            catch (Exception _e)
            {
                Debug.WriteLine("LOGGER ERROR!");
                Debug.WriteLine(_e.Message);
                Debug.WriteLine(_e.Source);
                Debug.WriteLine(_e.StackTrace);
            }
        }
Exemple #12
0
        // Write message to log file
        public void WriteToLog(string procName, string message, LogMessagePriority priority)
        {
            // Send log message via event to parent app
            if (logMessageEvent != null)
            {
                logMessageEvent(DateTime.Now.ToString("HH:mm:ss.fff") + "   " + message);
            }



            // Check if log message should be written to file
            if ((int)priority < logLevel)
            {
                return;
            }

            // Check if the the Event Log Exists
            const string sEventLogSource = "SLawLogger";
            //   TODO: code below should be added to installer, as it must be run by an administrator
            //if (!EventLog.SourceExists(sEventLogSource))
            //{
            //    EventLog.CreateEventSource(sEventLogSource, "Application");
            //}

            // Create path & filename
            string logPath = logFilePath;

            if (!logPath.EndsWith(@"\"))
            {
                logPath = logPath + @"\";
            }

            string logFile    = logPath + logFileName + ".log";
            string oldLogFile = logPath + logFileName + ".old";
            long   logSize    = 0;

            // Get log file size
            try
            {
                FileInfo f = new FileInfo(logFile);
                logSize = f.Length;
            }
            catch
            {
            }

            // Rollover old log file if size is exceeded
            if (logSize > logFileSize)
            {
                try
                {
                    File.Delete(oldLogFile);
                    File.Move(logFile, oldLogFile);
                }
                catch (Exception ex)
                {
                    if (priority == LogMessagePriority.Emergency || priority == LogMessagePriority.Error)
                    {
                        // Write to Windows Event Log
                        string sMessage = "Error while deleting or moving log file: " + ex.Message;
                        sMessage += "\r\nMessage: " + message;
                        try
                        {
                            EventLog.WriteEntry(sEventLogSource, sMessage, EventLogEntryType.Error);
                        }
                        catch
                        {
                        }
                    }
                    return;
                }
            }

            // Write to log file
            try
            {
                StreamWriter w = File.AppendText(logFile);
                //w.Write("\r\n");
                w.WriteLine("{0}    {1}: {2}", DateTime.Now.ToString("dd'-'MM'-'yyyy HH:mm:ss.fff"), procName, message);
                w.Flush();
                w.Close();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                if (priority == LogMessagePriority.Emergency || priority == LogMessagePriority.Error)
                {
                    // Write to Windows Event Log
                    string sMessage = "Error while writing log file: " + ex.Message;
                    sMessage += "\r\nMessage: " + message;

                    try
                    {
                        EventLog.WriteEntry(sEventLogSource, sMessage, EventLogEntryType.Error);
                    }
                    catch
                    {
                    }
                }
                return;
            }

            return;
        }
Exemple #13
0
        /// <summary>
        /// Posts a message to the logger output.
        /// </summary>
        /// <param name="message">The message to post.</param>
        /// <param name="messageKind">Optional. The kind of the message.</param>
        /// <param name="messagePriority">Optional. The priority of the message.</param>
        /// <remarks>
        /// A message kind different from none will be indicated by a prefix in the output.
        /// If the message priority is smaller then the priority of the logger, the message will not be postet.
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">Is thrown if message is null.</exception>
        public void PostMessage(string message, LogMessageKind messageKind = LogMessageKind.None, LogMessagePriority messagePriority = LogMessagePriority.Low)
        {
            if (message == null)
                throw new ArgumentNullException(nameof(message));
            
            if (messagePriority >= Priority)
            {
                var messageParts = new List<string>();
                if (IncludeTimeStamp) messageParts.Add(string.Concat("[", DateTime.Now.ToString(TimestampFormat), "]"));
                if (messageKind != LogMessageKind.None) messageParts.Add(MessageKindStrings[messageKind]);
                messageParts.Add(message);

                this.SendToOutput(string.Join(" ", messageParts));
            }
        }
Exemple #14
0
 protected Logger()
 {
     IncludeTimeStamp = true;
     TimestampFormat = "yyyy-MM-dd HH:mm:ss";
     Priority = LogMessagePriority.Low;
 }
Exemple #15
0
 protected Logger(bool includeTimeStamp, string timestampFormat)
 {
     IncludeTimeStamp = includeTimeStamp;
     TimestampFormat = timestampFormat;
     Priority = LogMessagePriority.Low;
 }
Exemple #16
0
 static void UpdateErrorCounts(LogMessagePriority priority)
 {
     switch (priority)
     {
         case LogMessagePriority.Error:
             ErrorCount += 1;
             var eh = ErrorLogged; //tsafe
             if (eh != null)
             {
                 try
                 {
                     eh("Logger", new EventArgs());
                 }
                 catch (Exception _e)
                 {
                     MessageBox.Show(_e.Message, "Logger::UpdateErrorCounts event failed", MessageBoxButtons.OK);
                 }
             }
             break;
         case LogMessagePriority.Critical:
             ErrorCount += 1;
             CriticalErrorCount += 1;
             var eh2 = ErrorLogged; //tsafe
             if (eh2 != null)
             {
                 try
                 {
                     eh2("Logger", new EventArgs());
                 }
                 catch (Exception _e)
                 {
                     MessageBox.Show(_e.Message, "Logger::UpdateErrorCounts event failed", MessageBoxButtons.OK);
                 }
             }
             break;
         default:
             break;
     }
 }
Exemple #17
0
 public static void Log(LogMessagePriority priority, string message, string category = UNKNOWN_LOG_SOURCE, Exception _e = null)
 {
     if (_e == null) WriteText(message, category, priority);
     else WriteException(message, category, priority, _e);
 }
Exemple #18
0
 protected Logger()
 {
     IncludeTimeStamp = true;
     TimestampFormat  = "yyyy-MM-dd HH:mm:ss";
     Priority         = LogMessagePriority.Low;
 }