示例#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
            };
        }
示例#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);
            }
        }
示例#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);
        }
示例#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);
            }
        }
示例#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);
        }
示例#6
0
        public static void Write(ILoggerEntry entry)
        {
            Initialize();

            lock (_lock)
            {
                foreach (ILogger logger in _loggers)
                {
                    logger.Write(entry);
                }
            }
        }
示例#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);
     }
 }
示例#8
0
        public static void WriteToEventLog(ILoggerEntry entry)
        {
            Initialize();

            lock (_lock)
            {
                foreach (ILogger logger in _loggers)
                {
                    if (logger is EventLogLogger)
                    {
                        logger.Write(entry);
                    }
                }
            }
        }
示例#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;
        }
示例#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;
 }
示例#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);
     }
 }
示例#12
0
        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);
            }
        }
示例#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);
            }
        }
示例#14
0
 public ConsoleLogger(ILoggerEntry consoleLoggerEnrtry, int reportLevel = int.MaxValue)
 {
     _reportLevel = reportLevel;
     _loggerEntry = consoleLoggerEnrtry;
 }
示例#15
0
 public abstract void Write(ILoggerEntry entry);
示例#16
0
 /// <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)));
 }
示例#17
0
 public FileProvider(ILoggerEntry loggerEntry)
 {
     _loggerEntry = loggerEntry;
 }
示例#18
0
 public DataBaseProvider(ILoggerEntry loggerEntry)
 {
     _loggerEntry = loggerEntry;
 }
示例#19
0
 public ConsoleLogger(ILoggerEntry consoleLoggerEnrtry, int reportLevel = int.MaxValue)
 {
     _reportLevel = reportLevel;
     _loggerEntry = consoleLoggerEnrtry;
 }
示例#20
0
 public void Add(ILoggerEntry loggerEntry)
 {
     _loggerEntry.Add(loggerEntry);
 }
示例#21
0
 public EventLogLoggerEntry(ILoggerEntry entry, EventLogEntryType entryType)
     : this(entry.TimeStamp, entry.Message, entryType)
 {
 }
示例#22
0
 public ConsoleLoggerEntry(ILoggerEntry entry, ConsoleColor color)
     : this(entry.TimeStamp, entry.Message, color)
 {
 }
示例#23
0
 public ConsoleLoggerEntry(ILoggerEntry entry)
     : this(entry.TimeStamp, entry.Message, ConsoleColor.Gray)
 {
 }
示例#24
0
 public ConsoleProvider(ILoggerEntry loggerEntry) {
     _loggerEntry = loggerEntry;
 }
示例#25
0
 public void Add(ILoggerEntry loggerEntry)
 {
     _loggerEntry.Add(loggerEntry);
 }
示例#26
0
 public EventLogLoggerEntry(ILoggerEntry entry)
     : this(entry.TimeStamp, entry.Message, EventLogEntryType.Information)
 {
 }