Exemple #1
0
        private void TraceInternal(Level tracingType, DateTime?startTime, string message, string exceptionMessage, Exception exception, bool appendLine)
        {
            DateTime now = DateTime.Now;

            { // try to trace with thread tracer
                MMTracer tracer = ThreadRelatedTracing ? CurrentThreadTracer : null;
                if (tracer != this)
                {
                    tracer?.TraceInternal(tracingType, startTime, message, exceptionMessage, exception, appendLine);
                }
            }

            string stackTrace = "";

            if (!appendLine && (TraceStackLevel <= tracingType))
            {
                stackTrace = "[" + GetOptimizedStackTrace(out string stackTraceDefinition) + "]";
                if (!string.IsNullOrEmpty(stackTraceDefinition))
                {
                    TraceInternal($"STACK: {stackTrace}={stackTraceDefinition}", now, false);
                }
                stackTrace += "  ";
            }

            TraceInternal((((tracingType >= 0) && ((int)tracingType < s_TracingTypeStrings.Length)) ? s_TracingTypeStrings[(int)tracingType] : "UNK") + " "
                          + now.ToString(s_DateFormat)
                          + (" (THRD=" + Thread.CurrentThread.ManagedThreadId + ")" + (startTime == null ? ":" : ",")).PadRight(14)
                          + (startTime == null ? "" : ("(" + (int)(now - startTime.Value).TotalMilliseconds + "ms):")).PadRight(10)
                          + stackTrace
                          + message
                          + (exceptionMessage == null ? "" : (" EX: " + exceptionMessage))
                          + (exception == null ? "" : (" EX: \r\n" + exception))
                          , now, appendLine);
        }
Exemple #2
0
        /// <summary>
        /// Append text to existing log without caret returning and additional formatting
        /// </summary>
        /// <param name="startTime">Start Time which is used to calculate duration when logging</param>
        /// <param name="message">message</param>
        /// <param name="prefix">new line prefix</param>
        /// <param name="maxLineLength">line length</param>
        public void Append(DateTime?startTime, string message, string prefix = null, int maxLineLength = 100)
        {
            DateTime now = DateTime.Now;

            { // try to trace with thread tracer
                MMTracer tracer = ThreadRelatedTracing ? CurrentThreadTracer : null;
                if (tracer != this)
                {
                    tracer?.Append(startTime, message, prefix, maxLineLength);
                }
            }

            lock (m_locker)
            {
                bool newLine = (m_pureCounter == 0);
                m_pureCounter += message?.Length ?? 0;
                if (m_pureCounter >= maxLineLength) // new string after 80 characters
                {
                    m_pureCounter = 0;
                }
                if (newLine)
                {
                    if (m_lineWasAppended)
                    {
                        TraceInternal("\r\n", now, true);
                    }
                    TraceInternal(InfoType, startTime, prefix + message, null, null, true);
                }
                else
                {
                    TraceInternal(message, now, true);
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Constructs a tracer object
        /// </summary>
        /// <param name="logFileName">Main Part of creating log files name</param>
        /// <param name="threadRelated"></param>
        /// <param name="traceStackLevel"></param>
        public static MMTracer Create(string logFileName = "common", bool threadRelated = true, Level traceStackLevel = ErrorType)
        {
            string name = logFileName.ToLower();

            lock (s_ExistingTracers)
            {
                if (!s_ExistingTracers.TryGetValue(name, out var tracer))
                {
                    tracer = new MMTracer(logFileName)
                    {
                        ThreadRelatedTracing = threadRelated,
                        TraceStackLevel      = traceStackLevel,
                    };
                    s_ExistingTracers[name] = tracer;
                }

                return(tracer);
            }
        }
Exemple #4
0
        /// <summary>
        /// Delete old files
        /// </summary>
        /// <param name="logStoringPeriod"></param>
        /// <param name="tracer"></param>
        /// <param name="cleanAllFiles"></param>
        public static void Clean(TimeSpan logStoringPeriod, MMTracer tracer, bool cleanAllFiles = false)
        {
            try
            {
                if (logStoringPeriod < TimeSpan.FromDays(1))
                {
                    tracer?.Info("Cleaning of old log files is switched off due to zero log storing period.");
                    return;
                }

                int      deleted    = 0;
                DateTime cutoffTime = DateTime.Now - logStoringPeriod;
                string   abbrev     = string.IsNullOrEmpty(ApplicationAbbreviation) ? "" : (ApplicationAbbreviation + "_");
                string[] files      = cleanAllFiles
          ? Directory.GetFiles(MMTracer.LogPath, "*", SearchOption.AllDirectories)
          : Directory.GetFiles(MMTracer.LogPath, $"{s_FileDeleteMask}{abbrev}*.log", SearchOption.TopDirectoryOnly);
                foreach (string fn in files)
                {
                    if ((new FileInfo(fn)).LastWriteTime < cutoffTime)
                    {
                        try
                        {
                            File.Delete(fn);
                            deleted++;
                            tracer?.Info($"file '{fn}' is deleted.");
                        }
                        catch (Exception ex)
                        {
                            tracer?.Error($"Error deleting the old log file: {fn}", ex.Message);
                        }
                    }
                }
                if (deleted > 0)
                {
                    tracer?.Info($"{deleted} old log files was deleted.");
                }
            }
            catch (Exception ex)
            {
                tracer?.Error("Error deleting old log files.", ex);
            }
        }
Exemple #5
0
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MMTracer tracer = MMTracer.Create("unhandled");

            tracer.Error("Unhandled exception occurred!", e.ExceptionObject?.ToString());
        }