Exemple #1
0
 public void Debug(string message, params object[] arguments)
 {
     if (_debug)
     {
         Console.WriteLine(_logFormatter.Format("DEBUG", message, arguments));
     }
 }
        public void Log(RequestData requestData, ResponseData responseData)
        {
            var info = _formatter.Format(requestData, responseData);

            info.LoggerName = _logger.Name;

            _logger.Log(info);
        }
        public void Format_ShouldReturn_LogEventInfo()
        {
            var requestData  = new RequestData();
            var responseData = new ResponseData();

            var result = _formatter.Format(requestData, responseData);

            Assert.IsNotNull(result);
            Assert.IsInstanceOf <LogEventInfo>(result);
        }
Exemple #4
0
        public void Log(object sender, LogEventArgs args)
        {
            if (_logColors.TryGetValue(args.Level, out ConsoleColor color))
            {
                Console.ForegroundColor = color;

                Console.WriteLine(_formatter.Format(args));

                Console.ResetColor();
            }
            else
            {
                Console.WriteLine(_formatter.Format(args));
            }
        }
        /// <inheritdoc cref="ILogTarget"/>
        public void OnLog(LogLevel level, object caller, string message)
        {
            var formattedMessage = _formatter.Format(level, caller, message);

            switch (level)
            {
            case LogLevel.Info:
            case LogLevel.Debug:
            {
                Debug.Log(formattedMessage);
                break;
            }

            case LogLevel.Warning:
            {
                Debug.LogWarning(formattedMessage);
                break;
            }

            case LogLevel.Error:
            case LogLevel.Fatal:
            {
                Debug.LogError(formattedMessage);
                break;
            }
            }
        }
Exemple #6
0
 /// <inheritdoc cref="ILogTarget"/>
 public void OnLog(LogLevel level, object caller, string message)
 {
     Debug.WriteLine(_formatter.Format(
                         level,
                         caller,
                         message));
 }
        private void Log(LogEntry entry, EventLogEntryType logType, ILogFormatter formatter)
        {
            string logLine = formatter.Format(entry);

            try { _EventLog.WriteEntry(logLine, logType); }
            catch { return; }
        }
Exemple #8
0
        public void RedirectsToCommonLogging()
        {
            CapturingLoggerFactoryAdapter testLoggerFactoryAdapter = new CapturingLoggerFactoryAdapter();

            LogManager.Adapter = testLoggerFactoryAdapter;

            // force entlib logging init
            Logger.Write("init");

            var listener = (CommonLoggingEntlibTraceListener)((TraceListenerWrapper)EnterpriseLibraryContainer.Current.GetInstance <TraceListener>("Test Capturing Listener")).InnerTraceListener;

            // ensure external configuration didn't change
            // change to starts with because entlib now wraps all listeners and changes the name
            Assert.IsTrue(listener.Name.StartsWith("Test Capturing Listener"));
            LogEntry logEntry = new LogEntry();

            logEntry.Categories.Add("mycategory");
            logEntry.Message = "testmessage";
            ILogFormatter formatter = listener.Formatter;
            string        s         = formatter.Format(logEntry);

            Assert.AreEqual("Category: mycategory, Message: testmessage", s);
            // note that output depends on the formatter configured for the entlib listener!
            Logger.Write("message1");
            Assert.AreEqual("Category: General, Message: message1", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
            Assert.AreEqual(LogLevel.Info, testLoggerFactoryAdapter.LastEvent.Level);

            Logger.Write("message2", "custom category", -1, -1, TraceEventType.Warning);
            Assert.AreEqual("Category: custom category, Message: message2", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
            Assert.AreEqual("Test Capturing Listener/All Events", testLoggerFactoryAdapter.LastEvent.Source.Name);
            Assert.AreEqual(LogLevel.Warn, testLoggerFactoryAdapter.LastEvent.Level);
        }
Exemple #9
0
        /// <summary>
        /// Creates a full populated new <see cref="ApplicationLogEntity"/> from a given <see cref="LogEntry"/>
        /// </summary>
        /// <param name="logEntry"></param>
        /// <param name="formatter"></param>
        /// <returns></returns>
        public static ApplicationLogEntity CreateFromLogEntry(LogEntry logEntry, ILogFormatter formatter)
        {
            Guard.ArgumentNotNull(logEntry, "logEntry");
            ApplicationLogEntity entity = new ApplicationLogEntity
            {
                AppDomainName   = logEntry.AppDomainName,
                ApplicationName = logEntry.ApplicationName,
                Category        = logEntry.Categories.Join(","),
                EventId         = logEntry.EventId,
                MachineName     = Environment.MachineName,
                Message         = logEntry.Message,
                Priority        = logEntry.Priority,
                ProcessId       = logEntry.ProcessId,
                ProcessName     = logEntry.ProcessName,
                Severity        = logEntry.Severity.ToString(),
                ThreadName      = logEntry.ManagedThreadName,
                Title           = logEntry.Title,
                Win32ThreadId   = logEntry.Win32ThreadId
            };

            entity.Timestamp        = new DateTimeOffset(logEntry.TimeStamp, TimeSpan.Zero);
            entity.PartitionKey     = CreatePartitionKey(entity.ApplicationName, entity.Timestamp);
            entity.RowKey           = ApplicationLogEntityManager.CreateRowKey(SortOrder.Descending);
            entity.FormattedMessage = formatter != null?formatter.Format(logEntry) : logEntry.Message;

            return(entity);
        }
Exemple #10
0
        public void RedirectsToCommonLogging()
        {
            CapturingLoggerFactoryAdapter testLoggerFactoryAdapter = new CapturingLoggerFactoryAdapter();

            LogManager.Adapter = testLoggerFactoryAdapter;

            // force entlib logging init
            Logger.Write("init");

            // ensure external configuration didn't change
            Assert.AreEqual("Test Capturing Listener", TestCommonLoggingEntlibTraceListener.Instance.Name);
            LogEntry logEntry = new LogEntry();

            logEntry.Categories.Add("mycategory");
            logEntry.Message = "testmessage";
            ILogFormatter formatter = TestCommonLoggingEntlibTraceListener.Instance.Formatter;
            string        s         = formatter.Format(logEntry);

            Assert.AreEqual("Category: mycategory, Message: testmessage", s);

            using (TestCommonLoggingEntlibTraceListener.Instance.Capture())
            {
                // note that output depends on the formatter configured for the entlib listener!
                Logger.Write("message1");
                Assert.AreEqual("Category: General, Message: message1", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
                Assert.AreEqual(LogLevel.Info, testLoggerFactoryAdapter.LastEvent.Level);

                Logger.Write("message2", "custom category", -1, -1, TraceEventType.Warning);
                Assert.AreEqual("Category: custom category, Message: message2", testLoggerFactoryAdapter.LastEvent.RenderedMessage);
                Assert.AreEqual("Test Capturing Listener/All Events", testLoggerFactoryAdapter.LastEvent.Source.Name);
                Assert.AreEqual(LogLevel.Warn, testLoggerFactoryAdapter.LastEvent.Level);
            }
        }
Exemple #11
0
        public void Write(string MsgStr)
        {
            string _MsgStr = _format.Format(MsgStr);

            _MsgStr += _target;
            //Output Message
            Console.WriteLine("Output " + _MsgStr);
        }
Exemple #12
0
 private async Task WriteFile()
 {
     await foreach (var log in _queue.Reader.ReadAllAsync(_cts.Token))
     {
         _formatter.Format(log, _fs);
         _fs.Flush();
     }
 }
        public string Format(int scopeLevel, string name, LogLevel logLevel, EventId eventId, string message, Exception exception)
        {
            var formatted = formatter.Format(scopeLevel, name, logLevel, eventId, message, exception);

            var sanitized = formatted.Replace(apiKeyToRemove, RemovedApiKey);

            return(sanitized);
        }
Exemple #14
0
        void Write(string message, LogLevel level)
        {
            if (_defaultLogLevel > level)
            {
                return;
            }
            var logItem = new LogItem
            {
                LogLevel  = level, LoggerName = _name,
                TimeStamp = DateTime.Now,
                Thread    = string.IsNullOrEmpty(Thread.CurrentThread.Name) ? Thread.CurrentThread.ManagedThreadId.ToString() : Thread.CurrentThread.Name,
                AppDomain = AppDomain.CurrentDomain.FriendlyName,
                Message   = message
            };

            _logTarget.WriteMessage(_logFormatter.Format(logItem));
        }
Exemple #15
0
 public void Flush()
 {
     while (_queue.TryDequeue(out var logEntry))
     {
         var text = _formatter.Format(logEntry);
         _logFile.Write(logEntry.CreationTime, text);
     }
 }
        public void Append(string scopeName, LogLevel level, object model)
        {
            ILogger log = GetLog(scopeName);

            // If requested level is not enabled, do nothing.
            if (!IsEnabled(log, level))
            {
                return;
            }

            object    message;
            Exception exception = null;

            // If we have formatter, use formatter.
            if (formatter != null)
            {
                message = formatter.Format(scopeName, level, model);
            }
            else if (!Converts.Try(model.GetType(), typeof(string), model, out message))
            {
                // Try convert to exception model.
                ExceptionModel exceptionModel = model as ExceptionModel;
                if (exceptionModel != null)
                {
                    message   = exceptionModel.Message;
                    exception = exceptionModel.Exception;
                }
                else
                {
                    // Use model as message.
                    message = model;
                }
            }

            // Log to defined level.
            switch (level)
            {
            case LogLevel.Debug:
                log.Debug(model, exception);
                break;

            case LogLevel.Info:
                log.Info(model);
                break;

            case LogLevel.Warning:
                log.Warn(model, exception);
                break;

            case LogLevel.Error:
                log.Error(model, exception);
                break;

            case LogLevel.Fatal:
                log.Fatal(model, exception);
                break;
            }
        }
Exemple #17
0
 public void Log(LogLevel logLevel, EventId eventId, string message, object state)
 {
     if (IsEnabled(logLevel))
     {
         string entry = _logFormatter.Format(logLevel, eventId, message, state);
         LockQueue(() => _entryQueue.Enqueue(entry));
         StartWriteTask();
     }
 }
Exemple #18
0
        private void FormatAndWrite(Level level, Exception exception, string message)
        {
            var formattedLog = _formatter.Format(level, exception, message);
            var rules        = _config.GetRules(DestinationType.File);

            foreach (var rule in rules)
            {
                _writer.Write(rule.Destination, formattedLog);
            }
        }
        private void WritesLogToConsole(ILogFormatter formatter)
        {
            var logInfo          = new LogInfo(LogLevel.INFO, new InvokerModel("", ""), "");
            var consoleLogWriter = new ConsoleLogWriter(formatter);

            TestConsoleOutput(
                () => consoleLogWriter.Write(logInfo),
                (output) => Assert.AreEqual(formatter.Format(logInfo), output)
                );
        }
Exemple #20
0
        /// <summary>
        /// Initializes a new instance of <see cref="AsyncConsoleSink"/>.
        /// </summary>
        /// <param name="formatter">Log formatter.</param>
        /// <param name="renderer">Renderer factory method.</param>
        public AsyncConsoleSink(ILogFormatter formatter, Func <IDataRenderer> renderer)
        {
            Formatter     = formatter;
            this.renderer = renderer;

            asyncWriter = new AsyncWriter((level, entries) =>
            {
                System.Console.WriteLine(Formatter.Format(level, entries, renderer()));
            });
            asyncWriter.Start();
        }
Exemple #21
0
 /// <summary>
 /// When called, logs to the file.
 /// </summary>
 /// <param name="level"></param>
 /// <param name="caller"></param>
 /// <param name="message"></param>
 public void OnLog(LogLevel level, object caller, string message)
 {
     try
     {
         _writer?.Write(_formatter.Format(level, caller, message));
     }
     catch
     {
         //
     }
 }
Exemple #22
0
        public void Write(string msg)
        {
            StringBuilder sb = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(_message))
            {
                sb.Append(_message);
            }
            sb.Append(_iLogFormatter.Format(msg));
            System.IO.File.AppendAllText(_filePath, sb.ToString(), Encoding.UTF8);
        }
        /// <summary>
        /// Formats the given <see cref="LogEntry"></see> through the given <see cref="ILogFormatter"></see>
        /// </summary>
        /// <param name="formatter">Instance of class implementing the <see cref="ILogFormatter"></see> interface</param>
        /// <param name="logEntry">The <see cref="LogEntry"></see> to format</param>
        /// <returns>The formatted <see cref="LogEntry"></see></returns>
        protected virtual string FormatEntry(ILogFormatter formatter, LogEntry logEntry)
        {
            string formattedMessage = formatter.Format(logEntry);

            if (logEntry.ErrorMessages != null)
            {
                formattedMessage = logEntry.ErrorMessages.ToString() + "Message: " +
                                   Environment.NewLine + formattedMessage;
            }

            return(formattedMessage);
        }
Exemple #24
0
        /// <inheritdoc cref="ILogTarget"/>
        public void OnLog(LogLevel level, object caller, string message, object meta)
        {
            if (level < Filter)
            {
                return;
            }

            Debug.WriteLine(_formatter.Format(
                                level,
                                caller,
                                message));
        }
Exemple #25
0
        public string ToString(ILogFormatter formatter)
        {
            if (formatter == null) return ToString();

            try
            {
                return formatter.Format(this);
            }
            catch
            {
                return ToString();
            }
        }
Exemple #26
0
 public string ToString(ILogFormatter formatter)
 {
     if (formatter == null)
     {
         return(ToString());
     }
     try
     {
         return(formatter.Format(this));
     }
     catch
     {
         return(ToString());
     }
 }
Exemple #27
0
 public override string ToString()
 {
     if (_cachedResult == null)
     {
         if (_logFormatter == null)
         {
             _cachedResult = _logEntry.ToString();
         }
         else
         {
             _cachedResult = _logFormatter.Format(_logEntry);
         }
     }
     return(_cachedResult);
 }
        /// <summary>
        /// Logs the specified entry.
        /// </summary>
        /// <param name="entry">The entry.</param>
        /// <param name="formatter">The formatter.</param>
        public void Log(LogEntry entry, ILogFormatter formatter)
        {
            if (!_Enabled)
            {
                return;
            }
            SplitLog();

            try
            {
                string logLine = formatter.Format(entry) + "\r\n";
                File.AppendAllText(_Location, logLine);
            }
            catch { return; }
        }
 public override string ToString()
 {
     if (cachedResult == null)
     {
         if (logFormatter == null)
         {
             cachedResult = logEntry.ToString();
         }
         else
         {
             cachedResult = logFormatter.Format(logEntry);
         }
     }
     return(cachedResult);
 }
Exemple #30
0
        /// <summary>
        /// When called, logs to the file.
        /// </summary>
        /// <param name="level"></param>
        /// <param name="caller"></param>
        /// <param name="message"></param>
        public void OnLog(LogLevel level, object caller, string message, object meta)
        {
            if (level < Filter)
            {
                return;
            }

            try
            {
                _writer?.Write(_formatter.Format(level, caller, message));
            }
            catch
            {
                //
            }
        }
Exemple #31
0
        private MailMessage CreateMailMessage()
        {
            string header = GenerateSubjectPrefix(configurationData.SubjectLineStarter);
            string footer = GenerateSubjectSuffix(configurationData.SubjectLineEnder);

            string sendToSmtpSubject = header + logEntry.Severity + footer;

            MailMessage message = new MailMessage();

            message.Body         = formatter.Format(logEntry);
            message.From         = configurationData.FromAddress;
            message.To           = configurationData.ToAddress;
            message.Subject      = sendToSmtpSubject;
            message.BodyEncoding = Encoding.UTF8;

            return(message);
        }
 public void Log(string message, LogLevel logLevel, ILogFormatter logFormatter)
 {
     Debug.WriteLine(logFormatter.Format(message, logLevel, DateTime.Now));
 }
		/// <summary>
		/// Escreve o resultado de um <see cref="LogEntry"/> no <see cref="System.Console"/>.
		/// </summary>
		/// <param name="logger">O logger</param>
		/// <param name="formatter">O formatador</param>
		/// <param name="entry">A entrada no log</param>
		public void Append(ILogger logger, ILogFormatter formatter, LogEntry entry)
		{
			Console.WriteLine(formatter.Format(entry));
		}
        /// <summary>
        /// Formats the given <see cref="LogEntry"></see> through the given <see cref="ILogFormatter"></see>
        /// </summary>
        /// <param name="formatter">Instance of class implementing the <see cref="ILogFormatter"></see> interface</param>
        /// <param name="logEntry">The <see cref="LogEntry"></see> to format</param>
        /// <returns>The formatted <see cref="LogEntry"></see></returns>
        protected virtual string FormatEntry(ILogFormatter formatter, LogEntry logEntry)
        {
            string formattedMessage = formatter.Format(logEntry);

            if (logEntry.ErrorMessages != null)
            {
                formattedMessage = logEntry.ErrorMessages.ToString() + "Message: " +
                    Environment.NewLine + formattedMessage;
            }

            return formattedMessage;
        }
Exemple #35
0
        public void Log(LogEntry entry, ILogFormatter formatter)
        {
            if (!_Enabled) return;
            SplitLog();

            try
            {
                string logLine = formatter.Format(entry) + "\r\n";
                File.AppendAllText(_Location, logLine);
            }
            catch { return; }
        }
Exemple #36
0
        private void Log(LogEntry entry, EventLogEntryType logType, ILogFormatter formatter)
        {
            string logLine = formatter.Format(entry);

            try { _EventLog.WriteEntry(logLine, logType); }
            catch { return; }
        }
Exemple #37
0
 public void Log(LogEntry entry, ILogFormatter formatter)
 {
     Console.WriteLine(formatter.Format(entry));
 }
Exemple #38
0
 public void Log(string message, LogLevel logLevel, ILogFormatter logFormatter)
 {
     this.LastMessage = logFormatter.Format(message, logLevel, LogTime);
     this.LastLogLevel = logLevel;
     this.LastLogFormatter = logFormatter;
 }
 internal static void AssertSerializingLogFormatter(ILogFormatter logFormatter, Mock<ISerializer> mockSerializer)
 {
     Assert.That(logFormatter.Format(null), Is.EqualTo("Hello, world!"));
     mockSerializer.Verify(m => m.SerializeToString(It.IsAny<object>(), It.IsAny<Type>()), Times.Once());
 }