Exemple #1
0
        /// <summary>
        /// Retrieves the column names to use when saving log data to SQL
        /// </summary>
        /// <param name="loggerEntry">The entry to save to SQL</param>
        private void SetColumnNames(ILoggerEntry loggerEntry)
        {
            // Use cached values when possible
            if (lastEntryType != null && lastEntryType == loggerEntry.GetType())
            {
                return;
            }
            else
            {
                lastEntryType = loggerEntry.GetType();
            }

            // Update values
            var logDate     = (lastEntryType.GetProperty(nameof(loggerEntry.Timestamp)) as MemberInfo).GetCustomAttribute <ColumnAttribute>().Name ?? "LogDate";
            var logTag      = (lastEntryType.GetProperty(nameof(loggerEntry.Tag)) as MemberInfo).GetCustomAttribute <ColumnAttribute>().Name ?? "LogTag";
            var logMessage  = (lastEntryType.GetProperty(nameof(loggerEntry.Message)) as MemberInfo).GetCustomAttribute <ColumnAttribute>().Name ?? "LogMessage";
            var logSeverity = (lastEntryType.GetProperty(nameof(loggerEntry.Severity)) as MemberInfo).GetCustomAttribute <ColumnAttribute>().Name ?? "LogSeverity";

            columnNames = new Dictionary <string, string>()
            {
                ["LogDate"]     = logDate,
                ["LogTag"]      = logTag,
                ["LogMessage"]  = logMessage,
                ["LogSeverity"] = logSeverity
            };
        }
Exemple #2
0
        public override void Write(ILoggerEntry entry)
        {
            try
            {
                if (base._enabled)
                {
                    String fileName      = ProcessFileName(FileName);
                    String directoryPath = Path.GetDirectoryName(fileName);
                    if (!String.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }

                    using (FileStream stream = new FileStream(fileName, FileMode.Append, FileAccess.Write))
                    {
                        using (TextWriter writer = new StreamWriter(stream, Encoding))
                        {
                            writer.WriteLine(entry.ToString());
                        }
                    }
                }
            }
            catch (IOException ex)
            {
                throw new InvalidOperationException("Unable to write entry!", ex);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Unable to write entry!", ex);
            }
        }
Exemple #3
0
        /// <inheritdoc/>
        public bool SaveToLog(ILoggerEntry loggerEntry)
        {
            var directory = GetTextLogDirectory(loggerEntry.Timestamp, Settings);
            var filename  = GetTextLogFilename(loggerEntry.Timestamp, Settings);

            var path = Path.Combine(directory, $"{filename}.txt");

            string message;

            if (OverridesToString(loggerEntry))
            {
                message = loggerEntry.ToString();
            }
            else
            {
                message = $"{loggerEntry.Timestamp:yyyy-MM-dd HH:mm:ss.fff} " +
                          $"Severity :: {loggerEntry.Severity} ;; " +
                          $"{loggerEntry.Tag} :: {loggerEntry.Message} ;; " +
                          Environment.NewLine;
            }

            SaveToLog(path, message);

            return(true);
        }
Exemple #4
0
        /// <inheritdoc/>
        public bool SaveToLog(ILoggerEntry loggerEntry)
        {
            try
            {
                SetColumnNames(loggerEntry);

                var query = $"INSERT INTO {Settings.LogSqlTable} " +
                            $"({columnNames["LogDate"]}, {columnNames["LogTag"]}, {columnNames["LogMessage"]}, {columnNames["LogSeverity"]}) " +
                            "VALUES (@LogDate, @LogTag, @LogMessage, @LogSeverity)";

                parameters.Add(new SqlParameter("@LogDate", SqlDbType.DateTime2)
                {
                    Value = loggerEntry.Timestamp
                });
                parameters.Add(new SqlParameter("@LogTag", SqlDbType.VarChar)
                {
                    Value = loggerEntry.Tag
                });
                parameters.Add(new SqlParameter("@LogMessage", SqlDbType.VarChar)
                {
                    Value = loggerEntry.Message
                });
                parameters.Add(new SqlParameter("@LogSeverity", SqlDbType.Int)
                {
                    Value = loggerEntry.Severity
                });

                return(sql.ExecuteNonQuery(query, parameters) == 1);
            }
            catch
            {
                return(false);
            }
        }
Exemple #5
0
        /// <inheritdoc/>
        public bool SaveToLog(ILoggerEntry loggerEntry)
        {
            var directory = GetTextLogDirectory(loggerEntry.Timestamp, Settings);
            var filename  = GetTextLogFilename(loggerEntry.Timestamp, Settings);

            var path = Path.Combine(directory, $"{filename}.json");

            SaveToLog(path, loggerEntry);

            return(true);
        }
Exemple #6
0
        public static void Write(ILoggerEntry entry)
        {
            Initialize();

            lock (_lock)
            {
                foreach (ILogger logger in _loggers)
                {
                    logger.Write(entry);
                }
            }
        }
Exemple #7
0
 public override void Write(ILoggerEntry entry)
 {
     try
     {
         if (base._enabled)
         {
             this.SendMessage(entry.ToString());
         }
     }
     catch (Exception ex)
     {
         throw new InvalidOperationException("Unable to write entry!", ex);
     }
 }
Exemple #8
0
        public static void WriteToEventLog(ILoggerEntry entry)
        {
            Initialize();

            lock (_lock)
            {
                foreach (ILogger logger in _loggers)
                {
                    if (logger is EventLogLogger)
                    {
                        logger.Write(entry);
                    }
                }
            }
        }
Exemple #9
0
        public HtmlLogger(ILoggerEntry loggerEntry, string filePath)
        {
            _filePath    = filePath;
            _loggerEntry = loggerEntry;
            string directory = Path.GetDirectoryName(filePath);

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            CreateStylesheetAt(directory);
            File.Open(_filePath, FileMode.Create).Dispose();
            WriteHtml(
                "<!DOCTYPE html>",
                "<html>",
                "<head>",
                "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css'>",
                "<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js'></script>",
                "<link rel='stylesheet' type='text/css' href='ktestoutput.css'>",
                "</head>",
                "<body>",
                "<script>if (!(navigator.userAgent.toLowerCase().indexOf('chrome') > -1)) document.body.innerHTML += '<div><small>(Please view this document in Chrome)</small></div>';</script>",
                "<script>",
                "  document.addEventListener('DOMContentLoaded', function() {",
                "    var notifyParentOfError = function(parent, classNames) {",
                "      if (parent) {",
                "        if (parent.tagName === 'DETAILS') {	    ",
                "          var badge = parent.getElementsByClassName('badge')[0];",
                "          badge.className = classNames;",
                "        }",
                "        notifyParentOfError(parent.parentElement, classNames);",
                "      }",
                "    }",
                "    var slows = document.getElementsByClassName('slow-pass');    ",
                "    for (var i = 0; i < slows.length; i++) {",
                "      notifyParentOfError(slows[i].parentElement, 'badge badge-warning');",
                "    }",
                "    var errors = document.getElementsByClassName('fail');    ",
                "    for (var i = 0; i < errors.length; i++) {",
                "      notifyParentOfError(errors[i].parentElement, 'badge badge-danger');",
                "    }",
                "  }, false);",
                "</script>"
                );
            _createdFile = true;
        }
Exemple #10
0
 public HtmlLogger(ILoggerEntry loggerEntry, string filePath)
 {
     _filePath = filePath;
     _loggerEntry = loggerEntry;
     string directory = Path.GetDirectoryName(filePath);
     if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
     CreateStylesheetAt(directory);
     File.Open(_filePath, FileMode.Create).Dispose();
     WriteHtml(
         "<!DOCTYPE html>",
         "<html>",
         "<head>",
         "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css'>",
         "<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js'></script>",
         "<link rel='stylesheet' type='text/css' href='ktestoutput.css'>",
         "</head>",
         "<body>",
         "<script>if (!(navigator.userAgent.toLowerCase().indexOf('chrome') > -1)) document.body.innerHTML += '<div><small>(Please view this document in Chrome)</small></div>';</script>",
         "<script>",
         "  document.addEventListener('DOMContentLoaded', function() {",
         "    var notifyParentOfError = function(parent, classNames) {",
         "      if (parent) {",
         "        if (parent.tagName === 'DETAILS') {	    ",
         "          var badge = parent.getElementsByClassName('badge')[0];",
         "          badge.className = classNames;",
         "        }",
         "        notifyParentOfError(parent.parentElement, classNames);",
         "      }",
         "    }",
         "    var slows = document.getElementsByClassName('slow-pass');    ",
         "    for (var i = 0; i < slows.length; i++) {",
         "      notifyParentOfError(slows[i].parentElement, 'badge badge-warning');",
         "    }",
         "    var errors = document.getElementsByClassName('fail');    ",
         "    for (var i = 0; i < errors.length; i++) {",
         "      notifyParentOfError(errors[i].parentElement, 'badge badge-danger');",
         "    }",
         "  }, false);",
         "</script>"
         );
     _createdFile = true;
 }
Exemple #11
0
 public override void Write(ILoggerEntry entry)
 {
     try
     {
         if (base._enabled)
         {
             EventLogEntryType entryType = EventLogEntryType.Information;
             if (entry is EventLogLoggerEntry)
             {
                 EventLogLoggerEntry eventLoggerEntry = (EventLogLoggerEntry)entry;
                 entryType = eventLoggerEntry.EntryType;
             }
             this.EventLog.WriteEntry(entry.ToString(), entryType);
         }
     }
     catch (Exception ex)
     {
         throw new InvalidOperationException("Unable to write entry!", ex);
     }
 }
        public override void Write(ILoggerEntry entry)
        {
            try
            {
                if (base._enabled)
                {
                    ConsoleColor foregroundColor = ConsoleColor.Gray;

                    if (entry is ConsoleLoggerEntry)
                    {
                        ConsoleLoggerEntry consoleEntry = (ConsoleLoggerEntry)entry;
                        foregroundColor = consoleEntry.Color;
                    }
                    else
                    if (entry is ConsoleExceptionLoggerEntry)
                    {
                        ConsoleExceptionLoggerEntry consoleEntry = (ConsoleExceptionLoggerEntry)entry;
                        foregroundColor = consoleEntry.Color;
                    }
                    else
                    if (entry is ExceptionLoggerEntry)
                    {
                        ExceptionLoggerEntry consoleEntry = (ExceptionLoggerEntry)entry;
                        foregroundColor = ConsoleColor.Red;
                    }
                    else
                    if (entry is LoggerEntry)
                    {
                        LoggerEntry consoleEntry = (LoggerEntry)entry;
                        foregroundColor = ConsoleColor.Gray;
                    }

                    Console.ForegroundColor = foregroundColor;
                    Console.WriteLine(entry.ToString());
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Unable to write entry!", ex);
            }
        }
Exemple #13
0
        /// <summary>
        /// Saves the provided entry to the endpoint
        /// </summary>
        /// <param name="path">The full path to store the entry</param>
        /// <param name="entry">The log data to record</param>
        /// <param name="retries">The number of times to retry on failure</param>
        private void SaveToLog(string path, ILoggerEntry entry, int retries = 3)
        {
            try
            {
                // Write to log
                using var writer = new StreamWriter(File.Open(path, FileMode.Append));
                writer.WriteLine(JsonSerializer.Serialize(entry) + ',');
            }
            catch
            {
                // Check for out of tries
                if (retries == 0)
                {
                    throw;
                }

                // Delay and try again
                int delay;

                if (retries >= 3)
                {
                    delay = 100;
                }
                else if (retries == 2)
                {
                    delay = 500;
                }
                else
                {
                    delay = 1_000;
                }

                Task.Delay(delay).Wait();

                SaveToLog(path, entry, --retries);
            }
        }
Exemple #14
0
 public ConsoleLogger(ILoggerEntry consoleLoggerEnrtry, int reportLevel = int.MaxValue)
 {
     _reportLevel = reportLevel;
     _loggerEntry = consoleLoggerEnrtry;
 }
Exemple #15
0
 public abstract void Write(ILoggerEntry entry);
 /// <summary>
 /// Records the provided logging entry to the configured endpoints
 /// </summary>
 /// <param name="loggerEntry">The data to record to the log(s)</param>
 public bool SaveToLog(ILoggerEntry loggerEntry)
 {
     return(Endpoints.All(x => x.SaveToLog(loggerEntry)));
 }
Exemple #17
0
 public FileProvider(ILoggerEntry loggerEntry)
 {
     _loggerEntry = loggerEntry;
 }
 public DataBaseProvider(ILoggerEntry loggerEntry)
 {
     _loggerEntry = loggerEntry;
 }
Exemple #19
0
 public ConsoleLogger(ILoggerEntry consoleLoggerEnrtry, int reportLevel = int.MaxValue)
 {
     _reportLevel = reportLevel;
     _loggerEntry = consoleLoggerEnrtry;
 }
Exemple #20
0
 public void Add(ILoggerEntry loggerEntry)
 {
     _loggerEntry.Add(loggerEntry);
 }
Exemple #21
0
 public EventLogLoggerEntry(ILoggerEntry entry, EventLogEntryType entryType)
     : this(entry.TimeStamp, entry.Message, entryType)
 {
 }
Exemple #22
0
 public ConsoleLoggerEntry(ILoggerEntry entry, ConsoleColor color)
     : this(entry.TimeStamp, entry.Message, color)
 {
 }
Exemple #23
0
 public ConsoleLoggerEntry(ILoggerEntry entry)
     : this(entry.TimeStamp, entry.Message, ConsoleColor.Gray)
 {
 }
 public ConsoleProvider(ILoggerEntry loggerEntry) {
     _loggerEntry = loggerEntry;
 }
Exemple #25
0
 public void Add(ILoggerEntry loggerEntry)
 {
     _loggerEntry.Add(loggerEntry);
 }
Exemple #26
0
 public EventLogLoggerEntry(ILoggerEntry entry)
     : this(entry.TimeStamp, entry.Message, EventLogEntryType.Information)
 {
 }