Exemple #1
0
 public static void Log(string message, LogType type, LogSource src)
 {
     if (OnLog != null)
     {
         OnLog(message, type, src);
     }
 }
        public void FlatFileListenerWillFallbackIfNotPriviledgesToWrite()
        {
            string fileName = @"trace.log";
            string fullPath = String.Format(@"{0}\{1}", Directory.GetCurrentDirectory(), fileName);

            File.Delete(fileName);

            FileIOPermission fileIOPerm1 = new FileIOPermission(PermissionState.None);
            fileIOPerm1.SetPathList(FileIOPermissionAccess.Read, fullPath);
            fileIOPerm1.PermitOnly();

            try
            {
                FlatFileTraceListener listener = new FlatFileTraceListener(fileName, "---header---", "***footer***",
                    new TextFormatter("DUMMY{newline}DUMMY"));

                // need to go through the source to get a TraceEventCache
                LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);
                source.TraceData(TraceEventType.Error, 0,
                    new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null));
                listener.Dispose();
            }
            catch (SecurityException)
            {
                FileIOPermission.RevertAll();
                throw;
            }
        }
        void SendLogEntry(WmiTraceListener listener,
                          LogEntry logEntry)
        {
            ManagementScope scope = new ManagementScope(@"\\." + wmiPath);
            scope.Options.EnablePrivileges = true;

            StringBuilder sb = new StringBuilder("SELECT * FROM ");
            sb.Append("LogEntryV20");
            string query = sb.ToString();
            EventQuery eq = new EventQuery(query);

            using (ManagementEventWatcher watcher = new ManagementEventWatcher(scope, eq))
            {
                watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
                watcher.Start();

                LogSource source = new LogSource("notfromconfig", SourceLevels.All);
                source.Listeners.Add(listener);
                source.TraceData(TraceEventType.Error, 1, logEntry);

                BlockUntilWMIEventArrives();

                watcher.Stop();
            }
        }
Exemple #4
0
        public void UpdateLog(string message, LogType type, LogSource src)
        {
            Color clr = consoleLogTextbox.ForeColor;
            try
            {
                if ((LogType.Warning & type) == type)
                    clr = Color.Yellow;
                else if ((LogType.OpChat & type) == type || (LogType.GlobalChat & type) == type || (LogType.IRCChat & type) == type || (LogType.GlobalChat & type) == type)
                    clr = Color.White;
                else if ((LogType.Error & type) == type || (LogType.FatalError & type) == type || (LogType.ErrorMessage & type) == type)
                    clr = Color.Red;

                message = Environment.NewLine + "[" + DateTime.Now.ToString("hh:mm:ss tt") + "]"
                               + "[" + Enum.GetName(typeof(LogType), type).Substring(0, 1) + "]"
                               + " - " + message;

                if ((LogTypes & type) == type || ((LogType.Debug & type) == type && MCSharp.Properties.DebugEnabled))
                {
                    if (this.consoleLogTextbox.InvokeRequired)
                    {
                        AppendTextCallback d = new AppendTextCallback(Log);
                        this.Invoke(d, new object[] { message, clr });
                    }
                    else
                    {
                        Log(message, clr);
                    }
                }
            }
            catch (Exception) {  }
        }
        public void AutoFlushDefaultPropertyIsTrue()
        {
            string name = "name";
            bool defaultAutoFlushProperty = true;

            LogSource logSource = new LogSource(name);

            Assert.AreEqual(defaultAutoFlushProperty, logSource.AutoFlush);
        }
 /// <summary>
 /// Gets the <see cref="Delta.CertXplorer.Logging.ILogService"/> with the specified source.
 /// </summary>
 /// <value></value>
 public ILogService this[LogSource source]
 {
     get 
     {
         if ((source != null) && (source.Name == currentSourceName)) 
             return this;
         return this[source.Name];
     }
 }
		public void SetUp()
		{
			logWriter = EnterpriseLibraryFactory.BuildUp<LogWriter>();
			MockTraceListener.Reset();
			ErrorsMockTraceListener.Reset();
			
			emptyTraceSource = new LogSource("none");
			if (emptyTraceSource.Listeners.Count == 1)
				emptyTraceSource.Listeners.RemoveAt(0);
		}
        public void SetUp()
        {
            AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory);

            logWriter = new LogWriterFactory().Create();
            MockTraceListener.Reset();
            ErrorsMockTraceListener.Reset();

            emptyTraceSource = new LogSource("none", Enumerable.Empty<TraceListener>(), SourceLevels.All);
            Assert.IsFalse(emptyTraceSource.Listeners.Any());
        }
        public void FormattedListenerWillUseFormatterIfExists()
        {
            StringWriter writer = new StringWriter();
            FormattedTextWriterTraceListener listener = new FormattedTextWriterTraceListener(writer, new TextFormatter("DUMMY{newline}DUMMY"));

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", SourceLevels.All);
            source.Listeners.Add(listener);
            source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null));

            Assert.AreEqual("DUMMY" + Environment.NewLine + "DUMMY", writer.ToString());
        }
        public void ListenerWillFallbackToTraceEntryToStringIfFormatterDoesNotExists()
        {
            LogEntry testEntry = new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null);
            StringWriter writer = new StringWriter();
            FormattedEventLogTraceListener listener = new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName, CommonUtil.EventLogNameCustom, null);

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);
            source.TraceData(TraceEventType.Error, 1, testEntry);

            Assert.AreEqual(testEntry.ToString(), CommonUtil.GetLastEventLogEntryCustom());
        }
        public void SetUp()
        {
            AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory);

            logWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
            MockTraceListener.Reset();
            ErrorsMockTraceListener.Reset();

            emptyTraceSource = new LogSource("none");
            if (emptyTraceSource.Listeners.Count == 1)
                emptyTraceSource.Listeners.RemoveAt(0);
        }
Exemple #12
0
        internal static void Write(LogSource Source, Exception Ex)
        {
            if (Ex == null || !EnableLogging) return;
            if (Ex.InnerException != null) Ex = Ex.InnerException;

            try
            {
                if (!Directory.Exists(ApplicationSettings.DataPath + "log\\"))
                    Directory.CreateDirectory(ApplicationSettings.DataPath + "log\\");

                LogFilePath = ApplicationSettings.DataPath + "log\\LOG." + DateTime.Today.ToString("yyyy-MM-dd") + ".EXCEPTION";

                LogStream = new FileStream(LogFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                Log = new StreamWriter(LogStream, Encoding.UTF8);

                StringBuilder SB = new StringBuilder();

                if (LogStream.Length < 21)
                    SB.AppendLine("<ERRORLOG>");
                else
                    LogStream.Position = LogStream.Length - 13;

                SB.AppendLine("  <LOG TIME=\"{0}\" SOURCE=\"{1}\">");
                SB.AppendLine("    <EXCEPTION>{2}</EXCEPTION>");
                SB.AppendLine("    <MESSAGE>{3}</MESSAGE>");
                SB.AppendLine("    <SOURCE>{4}</SOURCE>");
                SB.AppendLine("    <STACK>{5}</STACK>");
                SB.AppendLine("    <TARGETSITE>{6}</TARGETSITE>");
                SB.AppendLine("  </LOG>");

                SB.AppendLine("</ERRORLOG>"); // End the xml file

                Log.Write(
                    string.Format(SB.ToString(),
                    DateTime.Now.ToString("HH:mm:ss"),
                    Source.ToString(),
                    Ex.ToString(),
                    Ex.Message,
                    Ex.Source,
                    Ex.StackTrace,
                    Ex.TargetSite.Name));

                SB = null;
            }
            catch (Exception Exn)
            { }
            finally
            {
                if (Log != null) Log.Close(); Log = null;
                if (LogStream != null) LogStream.Close(); LogStream = null;
            }
        }
        public void LogSourceDoesAutoFlush()
        {
            MockFlushSensingTraceListener traceListener = new MockFlushSensingTraceListener();
            List<TraceListener> listeners = new List<TraceListener>(1);
            listeners.Add(traceListener);

            // Use the default configuration
            LogSource logSource = new LogSource("name", listeners, SourceLevels.All, true);

            logSource.TraceData(TraceEventType.Critical, 0, CommonUtil.GetDefaultLogEntry());

            Assert.AreEqual(1, traceListener.flushCalls);
        }
        public void LogSourceDoesNotAutoFlush()
        {
            MockFlushSensingTraceListener traceListener = new MockFlushSensingTraceListener();
            List<TraceListener> listeners = new List<TraceListener>(1);
            listeners.Add(traceListener);

            LogSource logSource = new LogSource("name", listeners, SourceLevels.All);

            logSource.AutoFlush = false;

            logSource.TraceData(TraceEventType.Critical, 0, CommonUtil.GetDefaultLogEntry());

            Assert.AreEqual(0, traceListener.flushCalls);
        }
Exemple #15
0
        public IQueryable <LogSource> GetEventLogTypes()
        {
            List <LogSource> eventLogs = new List <LogSource>();

            foreach (var elEventEntry in
                     System.Diagnostics.EventLog.GetEventLogs())
            {
                LogSource event1 = new LogSource();
                event1.SourceName = elEventEntry.Log;
                eventLogs.Add(event1);
            }

            return(eventLogs.AsQueryable());
        }
        public void SetupLogWriter()
        {
            writer = new StringWriter();
            TextFormatter formatter = new TextFormatter(preCallTemplate);

            listener = new FormattedTextWriterTraceListener(writer, formatter);

            LogSource logSource = new LogSource("Logging", new[] { listener }, SourceLevels.All);

            log = new LogWriter(new ILogFilter[0], new LogSource[] { logSource },
                                logSource, logSource, logSource, "General", true, true);

            Logger.SetLogWriter(this.log, false);
        }
Exemple #17
0
        private static void Main()
        {
            var log    = new LogSource();
            var logger = LogSettings.RegisterDefaultLogger <ColorConsoleLogger>();

            logger.LogLevel = LogLevels.Verbose;
            log.Verbose().WriteLine("This is {0}", LogLevels.Verbose);
            log.Debug().WriteLine("This is {0}", LogLevels.Debug);
            log.Info().WriteLine("This is {0}", LogLevels.Info);
            log.Warn().WriteLine("This is {0}", LogLevels.Warn);
            log.Error().WriteLine("This is {0}", LogLevels.Error);
            log.Fatal().WriteLine("This is {0}", LogLevels.Fatal);
            Console.ReadLine();
        }
Exemple #18
0
        public void FormattedListenerWillUseFormatterIfExists()
        {
            using (StringWriter writer = new StringWriter())
            {
                FormattedTextWriterTraceListener listener = new FormattedTextWriterTraceListener(writer, new TextFormatter("DUMMY{newline}DUMMY"));

                // need to go through the source to get a TraceEventCache
                LogSource source = new LogSource("notfromconfig", SourceLevels.All);
                source.Listeners.Add(listener);
                source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null));

                Assert.AreEqual("DUMMY" + Environment.NewLine + "DUMMY", writer.ToString());
            }
        }
        public void ListenerWillFallbackToTraceEntryToStringIfFormatterDoesNotExists()
        {
            LogEntry     testEntry = new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null);
            StringWriter writer    = new StringWriter();
            FormattedEventLogTraceListener listener = new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName, CommonUtil.EventLogNameCustom, null);

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", SourceLevels.All);

            source.Listeners.Add(listener);
            source.TraceData(TraceEventType.Error, 1, testEntry);

            Assert.AreEqual(testEntry.ToString(), CommonUtil.GetLastEventLogEntryCustom());
        }
		public void ListenerWillUseFormatterIfExists()
		{
			StringWriter writer = new StringWriter();
			FormattedEventLogTraceListener listener = new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName, CommonUtil.EventLogNameCustom, new TextFormatter("DUMMY{newline}DUMMY"));

			// need to go through the source to get a TraceEventCache
			LogSource source = new LogSource("notfromconfig", SourceLevels.All);
			source.Listeners.Add(listener);

			LogEntry logEntry = CommonUtil.GetDefaultLogEntry();
			source.TraceData(TraceEventType.Error, 1, logEntry);

			Assert.AreEqual("DUMMY" + Environment.NewLine + "DUMMY", CommonUtil.GetLastEventLogEntryCustom());
		}
Exemple #21
0
        public DynamicELLogger(string logRoot, IEnumerable <string> applications)
        {
            string[] categories = new string[] { "Info", "Error", "Debug", "Perf" };

            LoggingSettings loggingSetting = LoggingSettings.GetLoggingSettings(ConfigurationSourceFactory.Create());

            Dictionary <string, TextFormatter> formatters = new Dictionary <string, TextFormatter>(categories.Count(), StringComparer.OrdinalIgnoreCase);

            foreach (string cate in categories)
            {
                var formatData = loggingSetting.Formatters.Where(f => f.Name.Equals(cate, StringComparison.OrdinalIgnoreCase)).SingleOrDefault() as TextFormatterData;

                if (formatData == null)
                {
                    throw new Exception(string.Format("Missing logging formatter \"{0}\"", cate));
                }

                TextFormatter formatter = new TextFormatter(formatData.Template);
                formatters[cate] = formatter;
            }

            string baseLogPath = Path.Combine(logRoot, "{0}.log");
            string logPath     = Path.Combine(logRoot, "{0}\\{1}.log");

            List <LogSource> logSources = new List <LogSource>();

            foreach (var cate in categories)
            {
                logSources.Add(new LogSource(cate, new List <TraceListener>
                {
                    new RollingFlatFileTraceListener(string.Format(baseLogPath, cate), "", "", formatters[cate], 0, "yyyyMMdd", RollFileExistsBehavior.Overwrite, RollInterval.Day)
                }, SourceLevels.All));
            }

            foreach (var app in applications)
            {
                foreach (var cate in categories)
                {
                    logSources.Add(new LogSource(app + "." + cate, new List <TraceListener>
                    {
                        new RollingFlatFileTraceListener(string.Format(logPath, app, cate), "", "", formatters[cate], 0, "yyyyMMdd", RollFileExistsBehavior.Overwrite, RollInterval.Day)
                    }, SourceLevels.All));
                }
            }

            var nonExistantLog = new LogSource("Empty");

            m_Writer = new LogWriter(new ILogFilter[0], logSources, nonExistantLog, categories[0]);
        }
Exemple #22
0
        public static void Error(LogSource ls, String str)
        {
            if (Writer != null)
            {
                lock (Writer)
                {
                    WriteAsync($"{DateTime.UtcNow}\t{AsLogInfo.Error}\t{ls}\t{str}\r\n");

                    if (_externalLogger != null)
                    {
                        _externalLogger.Log(new AsLogEntry(AsLogInfo.Error, DateTime.UtcNow, ApplicationName, str));
                    }
                }
            }
        }
Exemple #23
0
        private void Log(LogSeverity s, LogSource from, string message, Exception e = null)
        {
            lock (_lock)
            {
                if (s is LogSeverity.Debug)
                {
                    if (!Config.EnableDebugLogging)
                    {
                        return;
                    }
                }

                Execute(s, from, message, e);
            }
        }
        public void ListenerWillUseFormatterIfExists()
        {
            StringWriter writer = new StringWriter();
            FormattedEventLogTraceListener listener =
                new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName, CommonUtil.EventLogNameCustom, new TextFormatter("DUMMY{newline}DUMMY"));

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);

            LogEntry logEntry = CommonUtil.GetDefaultLogEntry();

            source.TraceData(TraceEventType.Error, 1, logEntry);

            Assert.AreEqual("DUMMY" + Environment.NewLine + "DUMMY", CommonUtil.GetLastEventLogEntryCustom());
        }
Exemple #25
0
        public void ShouldLogApplyingLog()
        {
            using (StringWriter writer = new StringWriter())
            {
                FormattedTextWriterTraceListener listener = new FormattedTextWriterTraceListener(writer, new TextFormatter("DUMMY{newline}DUMMY"));

                listener.Filter = new EventTypeFilter(SourceLevels.Error);

                LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);

                source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Critical, "title", null));

                Assert.AreNotEqual(0, writer.ToString().Length);
            }
        }
Exemple #26
0
        private static void HandleLog(LogSeverity severity, LogSource source, string message, Exception?exception)
        {
            if ((int)severity > (int)Constants.ConsoleHelperLogLevel)
            {
                return;
            }
            var(color, simplified) = ProcessLogSeverity(severity);
            Append($"    {simplified}", color);

            (color, simplified) = ProcessSource(source);
            Append($" -> {simplified} -> ", color);

            AppendLine(message ?? string.Empty, Color.White);

            if (exception is { })
        public void ListenerWithHeaderAndFooterWillUseFormatterIfExists()
        {
            File.Delete("tracewithheaderandfooter.log");

            FlatFileTraceListener listener = new FlatFileTraceListener("tracewithheaderandfooter.log", "--------header------", "=======footer===========", new TextFormatter("DUMMY{newline}DUMMY"));

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);
            source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null));
            listener.Dispose();

            string strFileContents = GetFileContents("tracewithheaderandfooter.log");

            Assert.AreEqual("--------header------" + Environment.NewLine + "DUMMY" + Environment.NewLine + "DUMMY" + Environment.NewLine + "=======footer===========" + Environment.NewLine, strFileContents);
        }
        public void LogSourceDoesNotAutoFlush()
        {
            MockFlushSensingTraceListener traceListener = new MockFlushSensingTraceListener();
            List <TraceListener>          listeners     = new List <TraceListener>(1);

            listeners.Add(traceListener);

            LogSource logSource = new LogSource("name", listeners, SourceLevels.All);

            logSource.AutoFlush = false;

            logSource.TraceData(TraceEventType.Critical, 0, CommonUtil.GetDefaultLogEntry());

            Assert.AreEqual(0, traceListener.flushCalls);
        }
Exemple #29
0
        /// <summary>
        ///     This will call all available methods on the ILogger
        /// </summary>
        public static void TestAllLogMethods(ILogger loggerUnderTest)
        {
            var logSource = LogSource.ForCustomSource(Guid.NewGuid().ToString());

            logSource.LogTo(loggerUnderTest);
            try
            {
                AssertLogLevels(logSource, loggerUnderTest);
                AssertWriteLines(logSource);
            }
            finally
            {
                LoggerMapper.DeRegisterLoggerFor(logSource, loggerUnderTest);
            }
        }
Exemple #30
0
        public void FormattedListenerWillFallbackToTraceEntryToStringIfFormatterDoesNotExists()
        {
            LogEntry testEntry = new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null);

            using (StringWriter writer = new StringWriter())
            {
                FormattedTextWriterTraceListener listener = new FormattedTextWriterTraceListener(writer);
                LogSource source = new LogSource("notfromconfig", SourceLevels.All);
                source.Listeners.Add(listener);
                source.TraceData(TraceEventType.Error, 0, testEntry);
                string writtenData       = writer.ToString();
                string testEntryToString = testEntry.ToString();
                Assert.IsTrue(-1 != writtenData.IndexOf(testEntryToString));
            }
        }
 protected void DispatchVLogEvent(Object obj,
                                  LogType type,
                                  string message,
                                  string scenePath = "",
                                  LogSource source = LogSource.Scene)
 {
     LogCreated?.Invoke(new ValidationLog
     {
         logType       = type,
         source        = source,
         validatorName = TypeName,
         message       = message,
         objectPath    = ObjectTools.GetObjectPath(obj),
         scenePath     = scenePath
     });
 }
 /// <summary>
 /// Dispatches a <see cref="ValidationLog"/> instance via <see cref="LogCreated"/>.
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="type"></param>
 /// <param name="message"></param>
 /// <param name="scenePath"></param>
 /// <param name="source"></param>
 protected ValidationLog CreateVLog(Object obj,
                                    LogType type,
                                    string message,
                                    string scenePath,
                                    LogSource source)
 {
     return(new ValidationLog
     {
         logType = type,
         source = source,
         validatorName = TypeName,
         message = message,
         objectPath = ObjectTools.GetObjectPath(obj),
         scenePath = scenePath
     });
 }
        public void SetUp()
        {
            AppDomain.CurrentDomain.SetData("APPBASE", Environment.CurrentDirectory);

            logWriter =
#if NETCOREAPP
                new LogWriterFactory(NetCoreHelper.LookupConfigSection).Create();
#else
                new LogWriterFactory().Create();
#endif
            MockTraceListener.Reset();
            ErrorsMockTraceListener.Reset();

            emptyTraceSource = new LogSource("none", Enumerable.Empty <TraceListener>(), SourceLevels.All);
            Assert.IsFalse(emptyTraceSource.Listeners.Any());
        }
        public void ShouldLogApplyingLog()
        {
            using (StringWriter writer = new StringWriter())
            {
                FormattedTextWriterTraceListener listener = new FormattedTextWriterTraceListener(writer, new TextFormatter("DUMMY{newline}DUMMY"));

                listener.Filter = new EventTypeFilter(SourceLevels.Error);

                LogSource source = new LogSource("notfromconfig", SourceLevels.All);
                source.Listeners.Add(listener);

                source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Critical, "title", null));

                Assert.AreNotEqual(0, writer.ToString().Length);
            }
        }
        public void FormattedListenerWillFallbackToTraceEntryToStringIfFormatterDoesNotExists()
        {
            LogEntry testEntry = new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null);
            StringWriter writer = new StringWriter();
            FormattedTextWriterTraceListener listener = new FormattedTextWriterTraceListener(writer);

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", SourceLevels.All);
            source.Listeners.Add(listener);
            source.TraceData(TraceEventType.Error, 0, testEntry);

            string writtenData = writer.ToString();
            string testEntryToString = testEntry.ToString();

            Assert.IsTrue(-1 != writtenData.IndexOf(testEntryToString));
        }
Exemple #36
0
        /// <summary>
        /// Whether to trace this message or not?
        /// </summary>
        /// <param name="source">The source to trace for</param>
        /// <param name="level">The level of the message</param>
        /// <returns>True if message is to be traced</returns>
        private static bool ShouldTrace(LogSource source, TraceLevel level)
        {
            // Check if all source tracing at this level is enabled
            if (m_switchMinLevel.Level >= level)
            {
                return(true);
            }

            // Check if tracing for the source at this level is enabled
            if (m_switchSources[(int)source].Level >= level)
            {
                return(true);
            }

            return(false);
        }
        public void UseTracingWithDisabledLoggerDoesntWrite()
        {
            MockTraceListener.Reset();

            LogSource source = new LogSource("tracesource", new[] { new MockTraceListener() }, SourceLevels.All);

            List <LogSource> traceSources = new List <LogSource>(new LogSource[] { source });
            LogWriter        logWriter    = new LogWriter(new List <ILogFilter>(), new List <LogSource>(), source, null, new LogSource("errors"), "default", false, false);

            using (Tracer tracer = new Tracer("testoperation", logWriter))
            {
                Assert.AreEqual(0, MockTraceListener.Entries.Count);
            }

            Assert.AreEqual(0, MockTraceListener.Entries.Count);
        }
        public void ListenerWithHeaderAndFooterWillUseFormatterIfExists()
        {
            File.Delete("tracewithheaderandfooter.log");

            FlatFileTraceListener listener = new FlatFileTraceListener("tracewithheaderandfooter.log", "--------header------", "=======footer===========", new TextFormatter("DUMMY{newline}DUMMY"));

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);

            source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null));
            listener.Dispose();

            string strFileContents = GetFileContents("tracewithheaderandfooter.log");

            Assert.AreEqual("--------header------" + Environment.NewLine + "DUMMY" + Environment.NewLine + "DUMMY" + Environment.NewLine + "=======footer===========" + Environment.NewLine, strFileContents);
        }
        public static LogColor GetEntryColor(LogType type, LogSource source)
        {
            if (type == LogType.Error)
            {
                return(LogColor.Error);
            }
            else if (source == LogSource.VidCoder)
            {
                return(LogColor.VidCoder);
            }
            else if (source == LogSource.VidCoderWorker)
            {
                return(LogColor.VidCoderWorker);
            }

            return(LogColor.Normal);
        }
        public void GetTracerFromTraceManagerWithNoInstrumentation()
        {
            MockTraceListener.Reset();
            LogSource source = new LogSource("tracesource", SourceLevels.All);

            source.Listeners.Add(new MockTraceListener());
            List <LogSource> traceSources = new List <LogSource>(new LogSource[] { source });
            LogWriter        lg           = new LogWriter(new List <ILogFilter>(), new List <LogSource>(), source, null, new LogSource("errors"), "default", true, false);
            TraceManager     tm           = new TraceManager(lg);

            Assert.IsNotNull(tm);
            using (tm.StartTrace("testoperation"))
            {
                Assert.AreEqual(1, MockTraceListener.Entries.Count);
            }
            Assert.AreEqual(2, MockTraceListener.Entries.Count);
        }
        private MetricsTracingFactory(
            LogSource logSource,
            [CanBeNull] string summaryServiceName,
            TimeSpan longRequestTime,
            string tracingServiceName = null,
            params string[] summaryLabelNames)
        {
            _tracingServiceName = tracingServiceName;
            _longRequestTime    = longRequestTime;
            _logSource          = logSource;

            if (summaryServiceName != null)
            {
                Summary = Prometheus.Metrics.CreateSummary(summaryServiceName, string.Empty, summaryLabelNames, null,
                                                           TimeSpan.FromMinutes(1), null, null);
            }
        }
Exemple #42
0
        public static LogWriter BuildLogWriter(ILogFilter filter)
        {
            var filters = new ILogFilter[] { filter };
            //通用的LogSource,對應的是specialSources的allEvents
            var allEventsTraceSource = BuildAllEventsTraceSource();
            //日誌記錄組件自己出現錯誤時的LogSource,對應的是specialSources的errors
            var errorsLogSource = BuildErrorsLogSource();
            //categorySources, 可不需要設置,全部走allEventsTraceSource
            var categorySources = new List <LogSource>();
            //notProcessedTraceSource, 由於設置了allEventsTraceSource,故不需要設置
            var notProcessedTraceSource = new LogSource("Unprocessed Category");

            var logWriter = new LogWriter(filters, categorySources, allEventsTraceSource,
                                          notProcessedTraceSource, errorsLogSource, "DefaultCategory", true, true);

            return(logWriter);
        }
        public void ListenerWillFallbackToTraceEntryToStringIfFormatterDoesNotExists()
        {
            LogEntry testLogEntry = new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null);
            StreamWriter writer = new StreamWriter("trace.log");
            FlatFileTraceListener listener = new FlatFileTraceListener(writer);

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);
            source.TraceData(TraceEventType.Error, 0, testLogEntry);
            listener.Dispose();

            string strFileContents = GetFileContents("trace.log");

            string testLogEntryAsString = testLogEntry.ToString();

            Assert.IsTrue(-1 != strFileContents.IndexOf(testLogEntryAsString));
        }
        public void ListenerWillUseFormatterIfExists()
        {
            MockEmailTraceListener listener = new MockEmailTraceListener(new TextFormatter("DUMMY\r\nTime:{timestamp}\r\nMessage:{message}DUMMY"));

            LogEntry entry = new LogEntry("Test Message", "Test Category", 42, 999, TraceEventType.Information, "Test Title", null);
            DateTime messageTimestamp = DateTime.UtcNow;

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);
            source.TraceData(TraceEventType.Error, 0, entry);

            Assert.AreEqual("EntLib-Logging: Information has occurred", lastMailMessageSent.Subject);
            Assert.AreEqual("[email protected]", lastMailMessageSent.To[0].Address);
            Assert.AreEqual("[email protected]", lastMailMessageSent.To[1].Address);
            Assert.AreEqual("*****@*****.**", lastMailMessageSent.From.Address);
            AssertContainsSubstring(lastMailMessageSent.Body, messageTimestamp.ToString());
        }
Exemple #45
0
        public void ActivityEventTypesAreTreatedAsVerbose(TraceEventType eventType)
        {
            TelemetryChannel.ResetTelemetry();
            using (var listener = new ApplicationInsightsTraceListener(string.Empty))
            {
                var source = new LogSource("TestSource", new[] { listener }, SourceLevels.All);

                source.TraceData(TraceEventType.Information, 1, new LogEntry(string.Empty, "TestCategory", 1, 1, eventType, string.Empty, null));
            }

            Assert.AreEqual(TelemetryChannel.Traces.Count, 1);
            var trace = TelemetryChannel.Traces.Single() as TraceTelemetry;

            Assert.IsNotNull(trace);
            Assert.AreEqual(SeverityLevel.Verbose, trace.SeverityLevel);
            Assert.AreEqual(eventType.ToString(), trace.Properties["LoggedSeverity"]);
        }
Exemple #46
0
        private LogEntry ParseLineWithMissingLevelTag(string line, LogSource logFile)
        {
            string dateEndDelimiter = " ";

            if (line.Length < 15)
            {
                return(null);
            }

            int firstDelimiter = line.IndexOf(dateEndDelimiter, 15, StringComparison.InvariantCulture);

            if (firstDelimiter == -1)
            {
                return(null);
            }

            string date = line.Substring(0, firstDelimiter);

            if (!DateTime.TryParse(date, out var entryTime))
            {
                return(null);
            }

            string content = line.Substring(firstDelimiter + dateEndDelimiter.Length);

            var tags = ParseTags(content, out var lastTagIndex);

            LogEntry logFileEntry = new LogEntry(logFile, entryTime, LogLevel.Unknown, tags);

            if (lastTagIndex != -1)
            {
                var contentBeforeTags = line.Substring(0, firstDelimiter + dateEndDelimiter.Length + lastTagIndex);

                string contentWithoutTag = content.Substring(lastTagIndex);

                logFileEntry.AddContent(contentBeforeTags, contentWithoutTag);
            }
            else
            {
                logFileEntry.AddContent(string.Empty, string.Empty);
            }


            return(logFileEntry);
        }
Exemple #47
0
        private void Init(LogSource source)
        {
            _logSource = source;
            switch (source)
            {
            case LogSource.File:
                logAppender = "LogToFile";
                break;

            case LogSource.RuleLoggerToDB:
                logAppender = "RuleLogToDB";
                break;

            case LogSource.WinSvcLogToDB:
                logAppender = "WinSvcLogToDB";
                break;

            case LogSource.BusinessServiceErrorLog:
                logAppender = "BusinessServiceErrors";
                break;

            case LogSource.UserActivityLog:
                logAppender = "ActivityLogToDB";
                break;

            default:
                logAppender = "LogToDB";
                break;
            }
            try
            {
                ILog m_Log = GetLogFactory();
                //قسمت دوم شرط برای برنامه تستر کاربرد دارد
                if (m_Log == null || !(m_Log.IsDebugEnabled | m_Log.IsErrorEnabled | m_Log.IsFatalEnabled | m_Log.IsInfoEnabled | m_Log.IsWarnEnabled))
                {
                    Config();
                }
            }

            catch (NullReferenceException ex)
            {
                Exception s = new Exception();
                throw new ResourceNotFoundException("configuration file not found ", "LogConfigurationPath", ExceptionType.ALARM, "GTS.Clock.Infrastructure.Log.GTSRuleLogger.Constuctor", ex);
            }
        }
        public void ListenerWillFallbackToTraceEntryMessageIfFormatterDoesNotExists()
        {
            MockEmailTraceListener listener = new MockEmailTraceListener("[email protected];[email protected]", "*****@*****.**",
                                        "EntLib-Logging ->", "has occurred", "smtphost");

            LogEntry entry = new LogEntry("Test Message", "Test Category", 42, 999, TraceEventType.Error, "Test Title", null);
            DateTime messageTimestamp = DateTime.UtcNow;

            LogSource source = new LogSource("notfromconfig", SourceLevels.All);
            source.Listeners.Add(listener);
            source.TraceData(TraceEventType.Error, 0, entry);

            Assert.AreEqual("EntLib-Logging -> Error has occurred", lastMailMessageSent.Subject);
            Assert.AreEqual("[email protected]", lastMailMessageSent.To[0].Address);
            Assert.AreEqual("[email protected]", lastMailMessageSent.To[1].Address);
            Assert.AreEqual("*****@*****.**", lastMailMessageSent.From.Address);
            AssertContainsSubstring(lastMailMessageSent.Body, "Test Message");
        }
        public void ListenerWillFallbackToTraceEntryToStringIfFormatterDoesNotExists()
        {
            LogEntry              testLogEntry = new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null);
            StreamWriter          writer       = new StreamWriter("trace.log");
            FlatFileTraceListener listener     = new FlatFileTraceListener(writer);

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);

            source.TraceData(TraceEventType.Error, 0, testLogEntry);
            listener.Dispose();

            string strFileContents = GetFileContents("trace.log");

            string testLogEntryAsString = testLogEntry.ToString();

            Assert.IsTrue(-1 != strFileContents.IndexOf(testLogEntryAsString));
        }
Exemple #50
0
        public void UseTracingWithOwnLogWriter()
        {
            MockTraceListener.Reset();

            LogSource source = new LogSource("tracesource", SourceLevels.All);

            source.Listeners.Add(new MockTraceListener());

            List <LogSource> traceSources = new List <LogSource>(new LogSource[] { source });
            LogWriter        logWriter    = new LogWriter(new List <ILogFilter>(), new List <LogSource>(), source, null, new LogSource("errors"), "default", true, false);

            using (Tracer tracer = new Tracer("testoperation", logWriter, null))
            {
                Assert.AreEqual(1, MockTraceListener.Entries.Count);
            }

            Assert.AreEqual(2, MockTraceListener.Entries.Count);
        }
Exemple #51
0
        public void ListenerWithParamsWillUseFormatterIfExists()
        {
            MockEmailTraceListener listener = new MockEmailTraceListener("[email protected];[email protected]", "*****@*****.**",
                                                                         "EntLib-Logging ->", "has occurred", "smtphost", new TextFormatter("DUMMY\r\nTime:{timestamp}\r\nMessage:{message}DUMMY"));

            LogEntry entry            = new LogEntry("Test Message", "Test Category", 42, 999, TraceEventType.Error, "Test Title", null);
            DateTime messageTimestamp = DateTime.UtcNow;

            LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);

            source.TraceData(TraceEventType.Error, 0, entry);

            Assert.AreEqual("EntLib-Logging -> Error has occurred", lastMailMessageSent.Subject);
            Assert.AreEqual("[email protected]", lastMailMessageSent.To[0].Address);
            Assert.AreEqual("[email protected]", lastMailMessageSent.To[1].Address);
            Assert.AreEqual("*****@*****.**", lastMailMessageSent.From.Address);
            AssertContainsSubstring(lastMailMessageSent.Body, messageTimestamp.ToString());
        }
        public void SetUp()
        {
            CommonUtil.DeletePrivateTestQ();
            CreateQueueForTesting();

            clientSource = new LogSource("unnamed", SourceLevels.All);
            clientSource.Listeners.Add(
                new MsmqTraceListener("unnamed", CommonUtil.MessageQueuePath, new BinaryLogFormatter(),
                                      MessagePriority.Normal, false, new TimeSpan(0, 1, 0), new TimeSpan(0, 1, 0),
                                      false, true, false, MessageQueueTransactionType.None));

            LogSource distributorSource = new LogSource("unnamed", SourceLevels.All);
            distributorSource.Listeners.Add(new MockTraceListener());
            Dictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();
            logWriter = new LogWriterImpl(new List<ILogFilter>(), traceSources, distributorSource, null, new LogSource("errors"), "default", false, false);
            eventLogger = new DistributorEventLogger();
            msmqDistributor = new MsmqLogDistributor(logWriter, CommonUtil.MessageQueuePath, eventLogger);
            msmqDistributor.StopReceiving = false;
        }
        public void GetTracerFromTraceManagerWithNoInstrumentation()
        {
            MockTraceListener.Reset();

            LogSource source = new LogSource("tracesource", new[] { new MockTraceListener() }, SourceLevels.All);

            List<LogSource> traceSources = new List<LogSource>(new LogSource[] { source });
            LogWriter lg = new LogWriter(new List<ILogFilter>(), new List<LogSource>(), source, null, new LogSource("errors"), "default", true, false);

            TraceManager tm = new TraceManager(lg);

            Assert.IsNotNull(tm);

            using (tm.StartTrace("testoperation"))
            {
                Assert.AreEqual(1, MockTraceListener.Entries.Count);
            }

            Assert.AreEqual(2, MockTraceListener.Entries.Count);
        }
        public void FlatFileTraceListenerMultipleWrites()
        {
            File.Delete("tracewithheaderandfooter.log");
            string header = "--------header------";
            int numberOfWrites = 4;

            FlatFileTraceListener listener = new FlatFileTraceListener("tracewithheaderandfooter.log", header, "=======footer===========", new TextFormatter("DUMMY{newline}DUMMY"));

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", SourceLevels.All);
            source.Listeners.Add(listener);
            for (int writeLoop = 0; writeLoop < numberOfWrites; writeLoop++)
                source.TraceData(TraceEventType.Error, 0, new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null));
            source.Dispose();

            StreamReader reader = new StreamReader("tracewithheaderandfooter.log");
            int headersFound = NumberOfItems("tracewithheaderandfooter.log", header);

            Assert.AreEqual(numberOfWrites,headersFound);
        }
Exemple #55
0
        static void Log(string message, LogType type, LogSource src)
        {
            if ((LogType.Warning & type) == type)
                Console.ForegroundColor = ConsoleColor.Yellow;
            else if ((LogType.OpChat & type) == type || (LogType.GlobalChat & type) == type || (LogType.IRCChat & type) == type || (LogType.GlobalChat & type) == type)
                Console.ForegroundColor = ConsoleColor.White;
            else if ((LogType.Error & type) == type || (LogType.FatalError & type) == type || (LogType.ErrorMessage & type) == type)
                Console.ForegroundColor = ConsoleColor.Red;

            message = "[" + DateTime.Now.ToString("hh:mm:ss tt") + "]"
                           + "[" + Enum.GetName(typeof(LogType), type).Substring(0, 1) + "]"
                           + " - " + message;

            if ((consoleLogTypes & type) == type)
                Console.WriteLine(message);
            else if ((LogType.Debug & type) == type && Properties.DebugEnabled)
                Console.WriteLine(message);

            // Reset the console color afterwards to make sure the informational messages are always there
            Console.ResetColor();
        }
        public void CanSendMessageToQueue()
        {
            ILogFormatter formatter = new BinaryLogFormatter();
            MsmqTraceListener listener =
                new MsmqTraceListener("unnamed", CommonUtil.MessageQueuePath, formatter, MessagePriority.Low, true,
                                      MsmqTraceListenerData.DefaultTimeToBeReceived, MsmqTraceListenerData.DefaultTimeToReachQueue,
                                      false, false, false, MsmqTraceListenerData.DefaultTransactionType, new MockMsmqInterfaceFactory());
            LogSource source = new LogSource("unnamed", new List<TraceListener>(new TraceListener[] { listener }), SourceLevels.All);

            MockMsmqInterface.Instance.transactional = false;
            LogEntry entry = CommonUtil.GetDefaultLogEntry();
            source.TraceData(TraceEventType.Error, 1, entry);

            Message message = MockMsmqInterface.Instance.message;
            Assert.IsNotNull(message);
            Assert.IsNotNull(message.Body);
            Assert.AreEqual(message.Body.GetType(), typeof(string));
            Assert.AreEqual(MessageQueueTransactionType.None, MockMsmqInterface.Instance.transactionType);

            LogEntry deserializedEntry = BinaryLogFormatter.Deserialize(message.Body as string);
            Assert.IsNotNull(deserializedEntry);
        }
        static void Main()
        {
            Program.AppName = StarcounterEnvironment.AppName;
            Program.PlaygroundKeeperLogSource = new LogSource(StarcounterEnvironment.AppName);

            PrintVersion();

            // Database Hooks
            RegisterHooks();
            PlaygroundHost.RegisterHooks();
            Playground.RegisterHooks();
            Settings.RegisterHooks();

            // Handlers
            MainHandlers.Register();
            SettingsHandlers.Register();
            PlaygroundHostHandlers.Register();
            ApplicationHandlers.Register();

            // Mapping
            Program.InitilizeMapping();
        }
        public void GetTracerFromTraceManagerWithInstrumentationEnabled()
        {
            MockTraceListener.Reset();

            LogSource source = new LogSource("tracesource", SourceLevels.All);
            source.Listeners.Add(new MockTraceListener());

            List<LogSource> traceSources = new List<LogSource>(new LogSource[] { source });
            LogWriter lg = new LogWriterImpl(new List<ILogFilter>(), new List<LogSource>(), source, null, new LogSource("errors"), "default", true, false);

            TracerInstrumentationProvider instrumentationProvider = new TracerInstrumentationProvider(true, false, "applicationname");
            TraceManager tm = new TraceManager(lg, instrumentationProvider);

            Assert.IsNotNull(tm);

            using (tm.StartTrace("testoperation"))
            {
                Assert.AreEqual(1, MockTraceListener.Entries.Count);
            }

            Assert.AreEqual(2, MockTraceListener.Entries.Count);
        }
        public void ShouldSendMessageToQueueApplyingFilter()
        {
            ILogFormatter formatter = new BinaryLogFormatter();
            MsmqTraceListener listener =
                new MsmqTraceListener("unnamed", CommonUtil.MessageQueuePath, formatter, MessagePriority.Low, true,
                                      MsmqTraceListenerData.DefaultTimeToBeReceived, MsmqTraceListenerData.DefaultTimeToReachQueue,
                                      false, false, false, MsmqTraceListenerData.DefaultTransactionType, new MockMsmqInterfaceFactory());

            // Filter only Warning
            listener.Filter = new EventTypeFilter(SourceLevels.Warning);

            LogSource source = new LogSource("unnamed", new List<TraceListener>(new TraceListener[] { listener }), SourceLevels.All);

            MockMsmqInterface.Instance.transactional = false;
            MockMsmqInterface.Instance.ResetMessageCount();

            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            // Trace a Critical LogEntry
            source.TraceData(TraceEventType.Critical, 1, entry);

            Assert.AreEqual(1, MockMsmqInterface.Instance.MessageCount);
        }
		public void LogSourceCallsFlushRegardlessOfAutoflushValue()
		{
			MockFlushSensingTraceListener traceListener = new MockFlushSensingTraceListener();
			List<TraceListener> traceListeners = new List<TraceListener>(1);
			traceListeners.Add(traceListener);
			LogSource logSource = new LogSource("name", traceListeners, SourceLevels.All);

			bool currentAutoFlush = Trace.AutoFlush;

			try
			{
				Trace.AutoFlush = false;
				logSource.TraceData(TraceEventType.Critical, 0, CommonUtil.GetDefaultLogEntry());

				Trace.AutoFlush = true;
				logSource.TraceData(TraceEventType.Critical, 0, CommonUtil.GetDefaultLogEntry());

				Assert.AreEqual(2, traceListener.flushCalls);
			}
			finally
			{
				Trace.AutoFlush = currentAutoFlush;
			}
		}