コード例 #1
0
        private void Publish(LogEntrySeverity type, string message, params object[] parameters)
        {
            if (parameters != null && parameters.Any())
            {
                try
                {
                    message = string.Format(message, parameters);
                }
                catch (FormatException)
                {
                    message = message + " (" + string.Join(",", parameters) + ")";
                }
            }

            PrintNotification(type, message);

            // TODO: Refactor to use IHomeAutomationTimer.CurrentDateTime;
            var logEntry = new LogEntry(_currentId, DateTime.Now, Environment.CurrentManagedThreadId, type, string.Empty, message);

            lock (_syncRoot)
            {
                _items.Add(logEntry);
                _currentId++;

                UpdateHistory(logEntry);
            }
        }
コード例 #2
0
        private void Write(LogEntrySeverity severity, string source, Func <string> messageGenerator)
        {
            var timestamp        = DateTimeOffset.UtcNow;
            var generatorWrapper = new Lazy <string>(delegate
            {
                try
                {
                    return(messageGenerator());
                }
                catch (Exception ex)
                {
                    return($"Failed to generate log message: {ex}");
                }
            });

            // The lock is here just to ensure that no listener gets removed/disposed while it is being written to.
            lock (_lock)
            {
                foreach (var listener in _listeners)
                {
                    try
                    {
                        listener.OnWrite(timestamp, severity, source, () => generatorWrapper.Value);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex);
                    }
                }
                ;
            }
        }
コード例 #3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LogEntry"/> class.
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="severity">The severity.</param>
 /// <param name="source">The source.</param>
 public LogEntry(string text, LogEntrySeverity severity, LogEntrySource source)
 {
     this.logText  = text;
     this.logStamp = DateTime.Now;
     this.Severity = severity;
     this.Source   = source;
 }
コード例 #4
0
        private void Publish(LogEntrySeverity type, string text, params object[] parameters)
        {
            if (parameters != null && parameters.Any())
            {
                try
                {
                    text = string.Format(text, parameters);
                }
                catch (FormatException)
                {
                    text = text + " (" + string.Join(",", parameters) + ")";
                }
            }

            PrintNotification(type, text);

            // TODO: Refactor to use IHomeAutomationTimer.CurrentDateTime;
            var logEntry = new LogEntry(_currentId, DateTime.Now, Environment.CurrentManagedThreadId, type, text);

            lock (_syncRoot)
            {
                _items.Add(logEntry);
                _currentId++;

                if (logEntry.Severity != LogEntrySeverity.Verbose)
                {
                    _history.Add(logEntry);

                    if (_history.Count > 100)
                    {
                        _history.RemoveAt(0);
                    }
                }
            }
        }
コード例 #5
0
 public ComparisonMessage(MessageTemplate template, string path, LogEntrySeverity severity, params object[] formatArguments)
 {
     Severity = severity;
     Id       = template.Id;
     Path     = path;
     Message  = string.Format(CultureInfo.CurrentCulture, template.Message, formatArguments);
 }
コード例 #6
0
 public ComparisonMessage(MessageTemplate template, string path, LogEntrySeverity severity, params object[] formatArguments)
 {
     Severity = severity;
     Id = template.Id;
     Path = path;
     Message = string.Format(CultureInfo.CurrentCulture, template.Message, formatArguments);
 }
コード例 #7
0
        public void OnWrite(DateTimeOffset timestamp, LogEntrySeverity severity, string source, Func <string> messageGenerator)
        {
            var message = string.Format("{0} {1:u} [{2}]" + Environment.NewLine + "{3}",
                                        severity, timestamp, source, messageGenerator());

            switch (severity)
            {
            case LogEntrySeverity.Error:
            case LogEntrySeverity.Wtf:
                Trace.TraceError(message);
                break;

            case LogEntrySeverity.Warning:
                Trace.TraceWarning(message);
                break;

            case LogEntrySeverity.Info:
                Trace.TraceInformation(message);
                break;

            default:
                Trace.WriteLine(message);
                break;
            }
        }
コード例 #8
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="LogEntry" /> class.
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="severity">The severity.</param>
 /// <param name="source">The source.</param>
 /// <param name="path">The path where something happened</param>
 public LogEntry(string text, LogEntrySeverity severity, LogEntrySource source, string path)
 {
     LogText = text;
     LogStamp = DateTime.Now;
     Severity = severity;
     Source = source;
     Path = path;
 }
コード例 #9
0
 public LogEntry(long id, DateTime timestamp, int threadId, LogEntrySeverity severity, string message)
 {
     Id        = id;
     Timestamp = timestamp;
     ThreadId  = threadId;
     Severity  = severity;
     Message   = message;
 }
コード例 #10
0
        public void OnWrite(DateTimeOffset timestamp, LogEntrySeverity severity, string source, Func <string> messageGenerator)
        {
            var message = string.Format("{0} {1:u} [{2}]" + Environment.NewLine + "{3}",
                                        severity, timestamp, source, messageGenerator());

            _writer.WriteLine(message);
            _writer.WriteLine();
        }
コード例 #11
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="LogEntry" /> class.
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="severity">The severity.</param>
 /// <param name="source">The source.</param>
 /// <param name="path">The path where something happened</param>
 public LogEntry(string text, LogEntrySeverity severity, LogEntrySource source, string path)
 {
     LogText  = text;
     LogStamp = DateTime.Now;
     Severity = severity;
     Source   = source;
     Path     = path;
 }
コード例 #12
0
ファイル: AnalysisLogger.cs プロジェクト: Vanlightly/Graphode
        public void Log(LogEntrySeverity severity, string source, string message, string assemblyName, LogEntryType entryType)
        {
            //var line = severity + "," + CsvWriter.Escape(assemblyName) + "," + entryType + "," + CsvWriter.Escape(source) + "," + CsvWriter.Escape(message) + Environment.NewLine;

            //lock (_syncObj)
            //{
            //File.AppendAllText(_filePath, line);
            //}
        }
コード例 #13
0
        public void OnWrite(DateTimeOffset timestamp, LogEntrySeverity severity, string source, Func <string> messageGenerator)
        {
            if (severity < MinimumSeverity)
            {
                return;
            }

            _inner.OnWrite(timestamp, severity, source, messageGenerator);
        }
コード例 #14
0
        public LogEntry(long id, DateTime timestamp, int threadId, LogEntrySeverity severity, string source, string message)
        {
            Id = id;
            Timestamp = timestamp;
            ThreadId = threadId;
            Severity = severity;

            Source = source;
            Message = message;
        }
コード例 #15
0
ファイル: LogService.cs プロジェクト: wuzhenda/HA4IoT
        public void Publish(LogEntrySeverity severity, string source, string message, Exception exception)
        {
            var id       = Interlocked.Increment(ref _id);
            var logEntry = new LogEntry(id, DateTime.Now, System.Environment.CurrentManagedThreadId, severity, source ?? "System", message, exception?.ToString());

            lock (_pendingLogEntries)
            {
                _pendingLogEntries.Add(logEntry);
            }
        }
コード例 #16
0
 public void WriteTrace(string key, DateTime timestamp, LogEntrySeverity severity, string message, string[] tags)
 {
     WriteEntry(key, new ProgressEntry
                         {
                             Kind = ProgressEntryKind.Trace,
                             Timestamp = timestamp,
                             Severity = severity,
                             Message = message
                         });
 }
コード例 #17
0
        /// <summary>
        /// Get the console color associated with the severity of the message
        /// </summary>
        /// <param name="severity">Severity of the log message.</param>
        /// <returns>The color to set the console for messages of this severity</returns>
        public static ConsoleColor GetColorForSeverity(this LogEntrySeverity severity)
        {
            ConsoleColor color;

            if (!_dict.TryGetValue(severity, out color))
            {
                throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No color defined for severity {0}", severity));
            }
            return(color);
        }
コード例 #18
0
        public ComparisonMessage(MessageTemplate template, string path, LogEntrySeverity severity)
        {
            if (template == null)
                throw new ArgumentNullException("template");

            Severity = severity;
            Id = template.Id;
            Path = path;
            Message = template.Message;
        }
コード例 #19
0
        private void Log(LogEntrySeverity severity, string message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var entry = new LogEntry(severity, DateTime.Now, message);

            Logged?.Invoke(this, new LoggedEventArgs(entry));
        }
コード例 #20
0
ファイル: LogEntry.cs プロジェクト: wuzhenda/HA4IoT
        public LogEntry(long id, DateTime timestamp, int threadId, LogEntrySeverity severity, string source, string message, string exception)
        {
            Id        = id;
            Timestamp = timestamp;
            ThreadId  = threadId;
            Severity  = severity;

            Source    = source;
            Message   = message;
            Exception = exception;
        }
コード例 #21
0
        public LogEntry(LogEntrySeverity severity, DateTime timestamp, string message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            Severity  = severity;
            Timestamp = timestamp;
            Message   = message;
        }
コード例 #22
0
ファイル: Log.cs プロジェクト: nickmertin/Erebus
        /// <summary>
        /// Records an entry.
        /// </summary>
        /// <param name="sender">The object that created the entry.</param>
        /// <param name="message">The entry's message.</param>
        /// <param name="severity">The severity level of the entry.</param>
        public static void RecordEvent(object sender, string message, LogEntrySeverity severity)
        {
            var e = new LogEventArgs(message, severity);

            tsm.RunSafe(() =>
            {
                foreach (var h in handlers)
                {
                    h(sender, e);
                }
            });
        }
コード例 #23
0
        public ComparisonMessage(MessageTemplate template, string path, LogEntrySeverity severity)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            Severity = severity;
            Id       = template.Id;
            Path     = path;
            Message  = template.Message;
        }
コード例 #24
0
ファイル: LogService.cs プロジェクト: mikegerts/EIS-System
        public void Add(LogEntrySeverity severity, LogEntryType entryType, string description, string stackTrace)
        {
            using (var context = new EisInventoryContext())
            {
                context.logs.Add(new log
                {
                    Created     = DateTime.Now,
                    Severity    = (int)severity,
                    EntryType   = (int)entryType,
                    Description = description,
                    StackTrace  = stackTrace
                });

                context.SaveChanges();
            }
        }
コード例 #25
0
        private void log(LogEntrySeverity severity, LogEntryType entryType, string description, string stackTrace)
        {
            using (var conn = new MySql.Data.MySqlClient.MySqlConnection(_connectionString))
            {
                var parameters = new Dictionary <string, object>
                {
                    { "@Severity", severity },
                    { "@EntryType", entryType },
                    { "@Description", description },
                    { "@StackTrace", stackTrace },
                    { "@Created", DateTime.UtcNow },
                };

                MySqlHelper.ExecuteNonQuery(conn, @"INSERT INTO logs(Severity,EntryType,Description,StackTrace,Created)
                VALUES(@Severity,@EntryType,@Description,@StackTrace,@Created)", parameters);
            }
        }
コード例 #26
0
        private void Put(LogEntrySeverity level, string message, Exception ex = null, Dictionary <string, string> otherData = null)
        {
            //only log if the current desired level calls for it
            if (_logLevel < level)
            {
                return;
            }

            //add "global" OtherData to otherData
            AddGlobalOtherDataToOtherData(this.OtherData, ref otherData);

            //build the request
            var jsonRequest = new JsonRequest
            {
                JsonRpc = "2.0",
                Id      = Guid.NewGuid(),
                Method  = LoggingServiceMethod,
                Params  = new
                {
                    Host                  = Environment.MachineName,
                    Application           = _applicationName,
                    ApplicationParameters = _applicationParameters,
                    PID              = Process.GetCurrentProcess().Id,
                    Level            = level,
                    Language         = ".NET",
                    Message          = message,
                    ContextPrimary   = _contextPrimary,
                    ContextSecondary = _contextSecondary,
                    Other            = otherData
                }
            };

            //serialize
            var loggingMessage = JsonConvert.SerializeObject(jsonRequest);

            //send it
            Task.Factory.StartNew(() =>
            {
                bool putSuccess = this._mqQueueController.Put(_loggingQueueSettings, loggingMessage);

                System.Diagnostics.Trace.Write(message);
            }); //task
        }
コード例 #27
0
        /// <summary>
        /// Logs the specified text. This is marshalled to the UI thread if necessary.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="severity">The severity.</param>
        /// <param name="source">The source.</param>
        private void Log(string text, LogEntrySeverity severity, LogEntrySource source)
        {
            if (String.IsNullOrEmpty(text))
            {
                return;
            }

            this.MarshallMethod(() =>
            {
                //Hack to catch error messages from the converter
                if (text.StartsWith("Error: "))
                {
                    this.Options.Logger.AddLogEntry(new LogEntry(text, LogEntrySeverity.Error, LogEntrySource.Converter));
                    return;
                }

                this.Options.Logger.AddLogEntry(new LogEntry(text, severity, source));
            }, DispatcherPriority.Send);
        }
コード例 #28
0
ファイル: LogView.xaml.cs プロジェクト: chkr1011/LightPi
        private Brush GetBrushForSeverity(LogEntrySeverity severity)
        {
            switch (severity)
            {
            case LogEntrySeverity.Verbose:
                return(Brushes.Gray);

            case LogEntrySeverity.Information:
                return(Brushes.LightGreen);

            case LogEntrySeverity.Warning:
                return(Brushes.Yellow);

            case LogEntrySeverity.Error:
                return(Brushes.Red);

            default: throw new NotSupportedException();
            }
        }
コード例 #29
0
ファイル: Logger.cs プロジェクト: vishalishere/autorest
 public static void WriteMessages(TextWriter writer, LogEntrySeverity severity, bool verbose)
 {
     if (writer == null)
     {
         throw new ArgumentNullException("writer");
     }
     foreach (var logEntry in Entries.Where(e => e.Severity == severity))
     {
         // Write the severity and message to console
         writer.WriteLine("{0}: {1}",
                          logEntry.Severity.ToString().ToUpperInvariant(),
                          logEntry.Message);
         // If verbose is on and the entry has an exception, show it
         if (logEntry.Exception != null && verbose)
         {
             writer.WriteLine("{0}", logEntry.Exception);
         }
     }
 }
コード例 #30
0
        public void OnWrite(DateTimeOffset timestamp, LogEntrySeverity severity, string source, Func <string> messageGenerator)
        {
            // We pad the severity string so that all entries are nicely aligned.
            var severityString = severity.ToString().PadRight(_maxSeverityStringLength);

            var message = string.Format("{0} {1:u} [{2}] {3}",
                                        severityString, timestamp, source, messageGenerator());

            switch (severity)
            {
            case LogEntrySeverity.Error:
            case LogEntrySeverity.Wtf:
            case LogEntrySeverity.Warning:
                Console.Error.WriteLine(message);
                break;

            default:
                Console.Out.WriteLine(message);
                break;
            }
        }
コード例 #31
0
        private void PrintNotification(LogEntrySeverity type, string message)
        {
            if (!_isDebuggerAttached)
            {
                return;
            }

            string typeText = string.Empty;

            switch (type)
            {
            case LogEntrySeverity.Error:
            {
                typeText = "ERROR";
                break;
            }

            case LogEntrySeverity.Info:
            {
                typeText = "INFO";
                break;
            }

            case LogEntrySeverity.Warning:
            {
                typeText = "WARNING";
                break;
            }

            case LogEntrySeverity.Verbose:
            {
                typeText = "VERBOSE";
                break;
            }
            }

            Debug.WriteLine(typeText + ": " + message);
        }
コード例 #32
0
        /// <summary>
        /// A factory method to create a logger instance.
        /// </summary>
        /// <param name="loggerType">Type of the logger to be created. If not specified, <see cref="LoggerType.Null"/> logger is assumed</param>
        /// <param name="logDescription">Description of the process being logged to be placed in the logger header.</param>
        /// <param name="loggingThreshold">The least severe severity level to be logged. If not specified, severity level of <see cref="LogEntrySeverity.None"/> is assumed.</param>
        /// <param name="loggerInfo">Additional information required to initialize the logger; specific to a particular logger type. In case of a <see cref="LoggerType.LogFile"/> logger, it is a path to the log file (if LogFile path absent, then DataConveyer.log file in the current folder will be assumed).</param>
        /// <returns>The newly created logger instance.</returns>
        public static ILogger CreateLogger(LoggerType loggerType             = LoggerType.Null,
                                           string logDescription             = "",
                                           LogEntrySeverity loggingThreshold = LogEntrySeverity.None,
                                           string loggerInfo = null)
        {
            switch (loggerType)
            {
            case LoggerType.Null:
                return(CurrentLogger = new NullLogger());

            case LoggerType.LogFile:
                StreamWriter logWriter;
                try { logWriter = File.AppendText(loggerInfo ?? "DataConveyer.log"); }
                catch (Exception) { return(CurrentLogger = new NullLogger()); } //not much we can do other than downgrade to null logger
                return(CurrentLogger = new FileLogger(loggingThreshold, logDescription, logWriter));

            case LoggerType.NLog:
                throw new NotImplementedException("NLog logger type has not yet been implemented.");

            default:
                return(CurrentLogger = new NullLogger());
            }
        }
コード例 #33
0
        private LogLevel TranslateLogLevel(LogEntrySeverity level)
        {
            switch (level)
            {
            case LogEntrySeverity.Debug:
                return(LogLevel.Debug);

            case LogEntrySeverity.Info:
                return(LogLevel.Info);

            case LogEntrySeverity.Warning:
                return(LogLevel.Warn);

            case LogEntrySeverity.Error:
                return(LogLevel.Error);

            case LogEntrySeverity.Wtf:
                return(LogLevel.Fatal);

            default:
                throw new ArgumentOutOfRangeException("level");
            }
        }
コード例 #34
0
        private void Add(LogEntrySeverity severity, string source, string message, Exception exception)
        {
            LogEntry logEntry;

            lock (_logEntries)
            {
                _id     += 1L;
                logEntry = new LogEntry(_id, _dateTimeService.Now, Environment.CurrentManagedThreadId, severity, source, message, exception?.ToString());

                EnqueueLogEntry(logEntry, _logEntries, LogHistorySize);
            }

            if (severity == LogEntrySeverity.Warning)
            {
                lock (_warningLogEntries)
                {
                    EnqueueLogEntry(logEntry, _warningLogEntries, LogWarningHistorySize);
                }
            }
            else if (severity == LogEntrySeverity.Error)
            {
                lock (_errorLogEntries)
                {
                    EnqueueLogEntry(logEntry, _errorLogEntries, LogErrorHistorySize);
                }
            }

            LogEntryPublished?.Invoke(this, new LogEntryPublishedEventArgs(logEntry));
            Log.ForwardPublishedLogEntry(logEntry);

            if (!Debugger.IsAttached)
            {
                return;
            }

            Debug.WriteLine($"[{logEntry.Severity}] [{logEntry.Source}] [{logEntry.ThreadId}]: {message}");
        }
コード例 #35
0
        private void Put(LogEntrySeverity level, string message, string contextPrimary, string contextSecondary, Exception ex = null, Dictionary <string, string> otherData = null)
        {
            //only log if the current desired level calls for it
            if (_logLevel < level)
            {
                return;
            }

            //add exception details to otherData (if they don't already exist)
            AddExceptionToOtherData(ex, ref otherData);

            //add "global" OtherData to otherData
            AddGlobalOtherDataToOtherData(this.OtherData, ref otherData);

            //send it
            Task.Factory.StartNew(() =>
            {
                var loggingWriteResponse = _loggingServiceBusClient.Write(
                    Host: Environment.MachineName,
                    Application: _applicationName,
                    ApplicationParameters: _applicationParameters,
                    PID: Process.GetCurrentProcess().Id,
                    Level: level,
                    Message: message,
                    Language: ".NET",
                    ContextPrimary: contextPrimary,
                    ContextSecondary: contextSecondary,
                    Other: otherData
                    );

                if (!loggingWriteResponse.Success)
                {
                    Console.Write(message);
                }
            }); //task
        }
コード例 #36
0
ファイル: Logger.cs プロジェクト: jhancock93/autorest
 public static void WriteMessages(TextWriter writer, LogEntrySeverity severity)
 {
     WriteMessages(writer, severity, false);
 }
コード例 #37
0
ファイル: Logger.cs プロジェクト: jhancock93/autorest
 public static void WriteMessages(TextWriter writer, LogEntrySeverity severity, bool verbose)
 {
     if (writer == null)
     {
         throw new ArgumentNullException("writer");
     }
     foreach (var logEntry in Entries.Where(e => e.Severity == severity))
     {
         // Write the severity and message to console
         writer.WriteLine("{0}: {1}",
             logEntry.Severity.ToString().ToUpperInvariant(),
             logEntry.Message);
         // If verbose is on and the entry has an exception, show it
         if (logEntry.Exception != null && verbose)
         {
             writer.WriteLine("{0}", logEntry.Exception);
         }
     }
 }
コード例 #38
0
        private void PrintNotification(LogEntrySeverity type, string message)
        {
            if (!_isDebuggerAttached)
            {
                return;
            }

            string typeText = string.Empty;
            switch (type)
            {
                case LogEntrySeverity.Error:
                    {
                        typeText = "ERROR";
                        break;
                    }

                case LogEntrySeverity.Info:
                    {
                        typeText = "INFO";
                        break;
                    }

                case LogEntrySeverity.Warning:
                    {
                        typeText = "WARNING";
                        break;
                    }

                case LogEntrySeverity.Verbose:
                    {
                        typeText = "VERBOSE";
                        break;
                    }
            }

            Debug.WriteLine(typeText + ": " + message);
        }
コード例 #39
0
        /// <summary>
        /// Logs the specified text. This is marshalled to the UI thread if necessary.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="severity">The severity.</param>
        /// <param name="source">The source.</param>
        private void Log(string text, LogEntrySeverity severity, LogEntrySource source)
        {
            if (String.IsNullOrEmpty(text))
            {
                return;
            }

            this.MarshallMethod(() =>
                {
                    //Hack to catch error messages from the converter
                    if (text.StartsWith("Error: "))
                    {
                        this.Options.Logger.AddLogEntry(new LogEntry(text, LogEntrySeverity.Error, LogEntrySource.Converter));
                        return;
                    }

                    this.Options.Logger.AddLogEntry(new LogEntry(text, severity, source));
                }, DispatcherPriority.Send);
        }
コード例 #40
0
 public void Publish(LogEntrySeverity type, string message)
 {
     Debug.WriteLine(type + ": " + message);
 }
コード例 #41
0
        private void Publish(LogEntrySeverity type, string message, params object[] parameters)
        {
            if (parameters != null && parameters.Any())
            {
                try
                {
                    message = string.Format(message, parameters);
                }
                catch (FormatException)
                {
                    message = message + " (" + string.Join(",", parameters) + ")";
                }
            }

            PrintNotification(type, message);

            // TODO: Refactor to use IHomeAutomationTimer.CurrentDateTime;
            var logEntry = new LogEntry(_currentId, DateTime.Now, Environment.CurrentManagedThreadId, type, string.Empty, message);
            lock (_syncRoot)
            {
                _items.Add(logEntry);
                _currentId++;

                UpdateHistory(logEntry);
            }
        }
コード例 #42
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="LogEntry" /> class.
 /// </summary>
 /// <param name="text">The text.</param>
 /// <param name="severity">The severity.</param>
 /// <param name="source">The source.</param>
 public LogEntry(string text, LogEntrySeverity severity, LogEntrySource source)
     : this(text, severity, source, string.Empty)
 {
 }
コード例 #43
0
ファイル: LogEntry.cs プロジェクト: Ranjana1996/autorest
 /// <summary>
 /// Instantiates a new instance of the LogEntry class
 /// </summary>
 /// <param name="severity">The LogEntrySeverity of the LogEntry instance.</param>
 /// <param name="message">The message of the LogEntry instance.</param>
 public LogEntry(LogEntrySeverity severity, string message)
 {
     Severity = severity;
     Message = message;
 }