/// <summary>
        /// Writes a new Web specific entry into the log file
        ///
        /// Assumes that your log file is set up to be a Web Log file
        /// </summary>
        /// <param name="webEntry"></param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">Thrown if the insert operation fails</exception>
        public bool WriteEntry(WebLogEntry entry)
        {
            if (entry.Id == 0)
            {
                entry.Id = Guid.NewGuid().GetHashCode();
            }

            return(MongoBusiness.Save(entry));
        }
Example #2
0
        /// <summary>
        /// Writes a Web specific log entry into the log
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public bool Log(WebLogEntry entry, bool logHttpInfo = false)
        {
            if (logHttpInfo)
            {
                entry.UpdateFromRequest();
            }

            return(LogAdapter.WriteEntry(entry));
        }
 public void DataReaderToObjectTest()
 {
     using (SqlDataAccess data = new SqlDataAccess(STR_TestDataConnection))
     {
         IDataReader reader = data.ExecuteReader("select top 1 * from ApplicationLog");
         Assert.IsNotNull(reader, "Couldn't access Data reader. " + data.ErrorMessage);
         Assert.IsTrue(reader.Read(), "Couldn't read from DataReader");
         WebLogEntry entry = new WebLogEntry();
         DataUtils.DataReaderToObject(reader, entry, null);
         Assert.IsNotNull(entry.Message, "Entry Message should not be null");
         Assert.IsTrue(entry.ErrorLevel != ErrorLevels.None, "Entry Error level should not be None (error)");
     }
 } 
        public void WriteEntry()
        {
            var entry = new WebLogEntry()
            {
                Message = "Test at " + DateTime.Now,
                ErrorLevel = ErrorLevels.Info
            };

            var log = CreateLogManager();

            Assert.IsTrue(log.WriteEntry(entry));
            Assert.IsTrue(LogManager.Current.WriteEntry(entry));
        }
Example #5
0
        /// <summary>
        /// Returns an individual Web log entry from the log table
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public WebLogEntry GetEntry(int id)
        {
            using (SqlDataAccess data = CreateDal())
            {
                WebLogEntry entry = new WebLogEntry();
                if (!data.GetEntity(entry, LogFilename, "Id", id, null))
                {
                    return(null);
                }

                return(entry);
            }
        }
        /// <summary>
        /// Writes an Error message entry to the log
        /// </summary>
        /// <param name="message"></param>
        /// <param name="details"></param>
        /// <param name="stackTrace"></param>
        /// <returns></returns>
        public bool LogError(string message,
                             string details    = null,
                             string stackTrace = null)
        {
            var entry = new WebLogEntry()
            {
                ErrorLevel = ErrorLevels.Error,
                Message    = message,
                Details    = details,
                StackTrace = stackTrace
            };

            return(Log(entry));
        }
Example #7
0
        /// <summary>
        /// Writes a new Web specific entry into the log file
        ///
        /// Assumes that your log file is set up to be a Web Log file
        /// </summary>
        /// <param name="webEntry"></param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">Thrown if the insert operation fails</exception>
        public bool WriteEntry(WebLogEntry entry)
        {
            using (SqlDataAccess data = CreateDal())
            {
                string sql = string.Format(@"
insert into [{0}] (Entered,Message,ErrorLevel,Details,ErrorType,StackTrace,IpAddress,UserAgent,Url,QueryString,Referrer,PostData,RequestDuration) values
                (@Entered,@Message,@ErrorLevel,@Details,@ErrorType,@StackTrace,@IpAddress,@UserAgent,@Url,@QueryString,@Referrer,@PostData,@RequestDuration)
select CAST(scope_identity() as integer)
", LogFilename);


                object result = data.ExecuteScalar(sql,
                                                   data.CreateParameter("@Entered", entry.Entered, DbType.DateTime),
                                                   data.CreateParameter("@Message", StringUtils.TrimTo(entry.Message, 255), 255),
                                                   data.CreateParameter("@ErrorLevel", entry.ErrorLevel),
                                                   data.CreateParameter("@Details", StringUtils.TrimTo(entry.Details, 4000), 4000),
                                                   data.CreateParameter("@ErrorType", entry.ErrorType),
                                                   data.CreateParameter("@StackTrace", StringUtils.TrimTo(entry.StackTrace, 1500), 1500),
                                                   data.CreateParameter("@IpAddress", entry.IpAddress),
                                                   data.CreateParameter("@UserAgent", StringUtils.TrimTo(entry.UserAgent, 255)),
                                                   data.CreateParameter("@Url", entry.Url),
                                                   data.CreateParameter("@QueryString", StringUtils.TrimTo(entry.QueryString, 255)),
                                                   data.CreateParameter("@Referrer", entry.Referrer),
                                                   data.CreateParameter("@PostData", StringUtils.TrimTo(entry.PostData, 2048), 2048),
                                                   data.CreateParameter("@RequestDuration", entry.RequestDuration)
                                                   );


                // check for table missing and retry
                if (data.ErrorNumber == 208)
                {
                    // if the table could be created try again
                    if (CreateLog())
                    {
                        return(WriteEntry(entry));
                    }
                }

                if (result == null || result == DBNull.Value)
                {
                    throw new InvalidOperationException("Unable add log entry into table " + LogFilename + ". " + data.ErrorMessage);
                }

                // Update id
                entry.Id = (int)result;

                return(true);
            }
        }
        /// <summary>
        /// Writes a warning message to the log
        /// </summary>
        /// <param name="message"></param>
        /// <param name="details"></param>
        /// <param name="stackTrace"></param>
        /// <param name="logHttpInfo"></param>
        /// <returns></returns>
        public bool LogWarning(string message,
                               string details    = null,
                               string stackTrace = null,
                               bool logHttpInfo  = false)
        {
            var entry = new WebLogEntry()
            {
                ErrorLevel = ErrorLevels.Warning,
                Message    = message,
                Details    = details,
                StackTrace = stackTrace
            };

            return(Log(entry, logHttpInfo));
        }
        /// <summary>
        /// Creates a new log table in the current database. If the table exists already it
        /// is dropped and recreated.
        ///
        /// Requires database admin access.
        /// </summary>
        /// <param name="logType"></param>
        /// <returns></returns>
        public bool CreateLog()
        {
            MongoBusiness.Database.DropCollection(LogFilename);

            var entry = new WebLogEntry()
            {
                Message    = "Log file created.",
                ErrorLevel = ErrorLevels.Info
            };

            bool result = MongoBusiness.Save(entry);

            MongoBusiness.Collection.CreateIndex(new string[] { "Entered" });

            return(result);
        }
        /// <summary>
        /// Returns an individual entry entity
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public WebLogEntry GetEntry(int id)
        {
            XElement doc   = XElement.Load(LogFilename);
            XElement match = doc.Descendants("LogEntry")
                             .Where(el => (int)el.Element("Id") == id)
                             .FirstOrDefault();

            DataTable dt = CreateEntryDataTable();
            DataRow   dr = dt.NewRow();

            UpdateDataRowFromElement(match, dr);
            dt.Rows.Add(dr);
            DataTableReader reader = new DataTableReader(dt);

            reader.Read();

            WebLogEntry entry = new WebLogEntry();

            DataUtils.DataReaderToObject(reader, entry, null);

            return(entry);
        }
        /// <summary>
        /// Not implemented yet
        /// </summary>
        /// <param name="errorLevel"></param>
        /// <param name="count"></param>
        /// <param name="dateFrom"></param>
        /// <param name="dateTo"></param>
        /// <param name="fieldList"></param>
        /// <returns></returns>
        public IEnumerable <WebLogEntry> GetEntryList(ErrorLevels errorLevel = ErrorLevels.All,
                                                      int count         = 200,
                                                      DateTime?dateFrom = null,
                                                      DateTime?dateTo   = null,
                                                      string fieldList  = null)
        {
            var reader = GetEntries(errorLevel, count, dateFrom, dateTo, fieldList);

            if (reader == null || reader.FieldCount < 1)
            {
                yield break;
            }

            var piList = new Dictionary <string, PropertyInfo>();

            while (reader.Read())
            {
                var entry = new WebLogEntry();
                DataUtils.DataReaderToObject(reader, entry, null, piList);
                yield return(entry);
            }
        }
Example #12
0
        /// <summary>
        /// Returns an individual entry entity
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public WebLogEntry GetEntry(int id)
        {
            XElement doc = XElement.Load(LogFilename);
            XElement match = doc.Descendants("LogEntry")
                                .Where( el => (int) el.Element("Id") == id )
                                .FirstOrDefault();

            DataTable dt = CreateEntryDataTable();
            DataRow dr = dt.NewRow();
            UpdateDataRowFromElement(match, dr);
            dt.Rows.Add(dr);
            DataTableReader reader = new DataTableReader(dt);
            reader.Read();

            WebLogEntry entry = new WebLogEntry();
            DataUtils.DataReaderToObject(reader, entry, null);

            return entry;
        }
        public void CreateLog()
        {
            LogManager manager = LogManager.Create();

            try
            {
                for (int i = 0; i < 250; i++)
                {
                    var entry = new WebLogEntry()
                    {
                        Entered = DateTime.Now.AddDays(i * -1),
                        ErrorLevel = ErrorLevels.Info,
                        Message = StringUtils.RandomString(50, true),
                        Details = StringUtils.RandomString(60, true),
                        QueryString = StringUtils.RandomString(20, true),
                        ErrorType = (i % 2 == 0 ? "Info" : "Error"),
                        IpAddress = StringUtils.RandomString(12),
                        RequestDuration = i * 1.10M

                    };
                    manager.WriteEntry(entry);
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }

        }
        /// <summary>
        /// Writes a new Web specific entry into the log file
        /// 
        /// Assumes that your log file is set up to be a Web Log file
        /// </summary>
        /// <param name="webEntry"></param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">Thrown if the insert operation fails</exception>
        public bool WriteEntry(WebLogEntry entry)
        {
            if (entry.Id == 0)
                entry.Id = Guid.NewGuid().GetHashCode();

            return MongoBusiness.Save(entry);
        }
Example #15
0
 /// <summary>
 /// Writes a Web specific log entry into the log
 /// </summary>
 /// <param name="entry"></param>
 /// <returns></returns>
 public bool WriteEntry(WebLogEntry entry)
 {
     return(LogAdapter.WriteEntry(entry));
 }
Example #16
0
        public void XmlLogAdapterTest()
        {
            XmlLogAdapter adapter = new XmlLogAdapter() { ConnectionString = TestContext.DeploymentDirectory + @"\applicationlog.xml" };

            WebLogEntry entry = new WebLogEntry()
            {
                Message = "Entered on: " + DateTime.Now.ToString(),
                ErrorLevel = ErrorLevels.Info,
                Details = StringUtils.RandomString(40,true)
            };

            Assert.IsTrue(adapter.WriteEntry(entry), "Failed to write entry to log");
        }
Example #17
0
        public void WriteLogEntryWithAdapterTest()
        {
            SqlLogAdapter adapter = new SqlLogAdapter(STR_ConnectionString);
            adapter.LogFilename = STR_TestLogFile;

            WebLogEntry entry = new WebLogEntry();
            entry.ErrorLevel = ErrorLevels.Info;
            entry.Message = "Testing " + DateTime.Now.ToString();

            bool res = adapter.WriteEntry(entry);

            //bool res = adapter.WriteEntry(entry);

            Assert.IsTrue(res, "Entry couldn't be written to database");

            LogEntry entry2 = adapter.GetEntry(entry.Id);

            Assert.IsTrue(entry.Message == entry2.Message);
            Assert.IsTrue(entry.ErrorLevel == entry2.ErrorLevel);
        }
Example #18
0
        public void LogManagerWriteEntryTest()
        {
            WebLogEntry entry = new WebLogEntry();
            entry.Message = "Testing " + DateTime.Now.ToString();
            entry.ErrorLevel = ErrorLevels.Info;
            entry.Details = "Bogus".PadRight(3000, '.');

            bool res = LogManager.Current.WriteEntry(entry);

            Assert.IsTrue(res, "WriteEntry failed");
        }
 public void FindByIdTest()
 {
     using (var data = new SqlDataAccess(STR_ConnectionString))
     {
         var entry = data.Find<WebLogEntry>(1, "ApplicationLog", "Id");
         Assert.IsNotNull(entry, data.ErrorMessage);
         Console.WriteLine(entry.Entered + " " + entry.Message);
         var entry2 = new WebLogEntry();
         data.GetEntity(entry2, "ApplicationLog", "Id", 1);
         Assert.IsNotNull(entry2);
         Assert.AreEqual(entry2.Message, entry.Message);
         Console.WriteLine(entry2.Entered + " " + entry2.Message);
     }
 }
        /// <summary>
        /// Creates a new log table in the current database. If the table exists already it
        /// is dropped and recreated.
        /// 
        /// Requires database admin access.
        /// </summary>
        /// <param name="logType"></param>
        /// <returns></returns>
        public bool CreateLog()
        {

            MongoBusiness.Database.DropCollection(LogFilename);

            var entry = new WebLogEntry()
            {
                Message = "Log file created.",
                ErrorLevel = ErrorLevels.Info
            };

            bool result = MongoBusiness.Save(entry);

            MongoBusiness.Collection.CreateIndex(new string[] { "Entered" });

            return result;
        }
Example #21
0
        /// <summary>
        /// Writes a new Web specific entry into the log file
        /// 
        /// Assumes that your log file is set up to be a Web Log file
        /// </summary>
        /// <param name="webEntry"></param>
        /// <returns></returns>
        /// <exception cref="System.InvalidOperationException">Thrown if the insert operation fails</exception>
        public bool WriteEntry(WebLogEntry entry)
        {
            using (SqlDataAccess data = CreateDal())
            {
                string sql = string.Format(@"
insert into [{0}] (Entered,Message,ErrorLevel,Details,ErrorType,StackTrace,IpAddress,UserAgent,Url,QueryString,Referrer,PostData,RequestDuration) values
                (@Entered,@Message,@ErrorLevel,@Details,@ErrorType,@StackTrace,@IpAddress,@UserAgent,@Url,@QueryString,@Referrer,@PostData,@RequestDuration)
select CAST(scope_identity() as integer)
", LogFilename);


                object result = data.ExecuteScalar(sql,
                    data.CreateParameter("@Entered", entry.Entered, DbType.DateTime),
                    data.CreateParameter("@Message", StringUtils.TrimTo(entry.Message, 255), 255),
                    data.CreateParameter("@ErrorLevel", entry.ErrorLevel),
                    data.CreateParameter("@Details", StringUtils.TrimTo(entry.Details, 4000), 4000),
                    data.CreateParameter("@ErrorType", entry.ErrorType),
                    data.CreateParameter("@StackTrace", StringUtils.TrimTo(entry.StackTrace, 1500), 1500),
                    data.CreateParameter("@IpAddress", entry.IpAddress),
                    data.CreateParameter("@UserAgent", StringUtils.TrimTo(entry.UserAgent, 255)),
                    data.CreateParameter("@Url", entry.Url),
                    data.CreateParameter("@QueryString", StringUtils.TrimTo(entry.QueryString, 255)),
                    data.CreateParameter("@Referrer", entry.Referrer),
                    data.CreateParameter("@PostData", StringUtils.TrimTo(entry.PostData, 2048), 2048),
                    data.CreateParameter("@RequestDuration", entry.RequestDuration)
                );


                // check for table missing and retry
                if (data.ErrorNumber == 208)
                {
                    // if the table could be created try again
                    if (CreateLog())
                        return WriteEntry(entry);
                }

                if (result == null || result == DBNull.Value)
                    throw new InvalidOperationException("Unable add log entry into table " + LogFilename + ". " + data.ErrorMessage);

                // Update id
                entry.Id = (int)result;

                return true;
            }
        }
Example #22
0
        /// <summary>
        /// Writes an error entry from an exception to the log
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="logHttpInfo"></param>
        /// <returns></returns>
        public bool LogError(Exception ex, bool logHttpInfo = false)
        {
            var entry = new WebLogEntry(ex);

            return(Log(entry, logHttpInfo));
        }
Example #23
0
        /// <summary>
        /// Returns an individual Web log entry from the log table
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public WebLogEntry GetEntry(int id)
        {
            using (SqlDataAccess data = CreateDal())
            {
                WebLogEntry entry = new WebLogEntry();
                if (!data.GetEntity(entry, LogFilename, "Id", id, null))
                    return null;

                return entry;
            }
        }
Example #24
0
        /// <summary>
        /// Not implemented yet
        /// </summary>
        /// <param name="errorLevel"></param>
        /// <param name="count"></param>
        /// <param name="dateFrom"></param>
        /// <param name="dateTo"></param>
        /// <param name="fieldList"></param>
        /// <returns></returns>
        public IEnumerable<WebLogEntry> GetEntryList(ErrorLevels errorLevel = ErrorLevels.All,
            int count = 200,
            DateTime? dateFrom = null,
            DateTime? dateTo = null,
            string fieldList = null)
        {
            var reader = GetEntries(errorLevel, count, dateFrom, dateTo, fieldList);
            if (reader == null || reader.FieldCount < 1)
            {
                yield break;
            }

            var piList = new Dictionary<string, PropertyInfo>();
            while (reader.Read())
            {
                var entry = new WebLogEntry();
                DataUtils.DataReaderToObject(reader, entry, null, piList);
                yield return entry;
            }
        }
Example #25
0
 protected void Application_EndRequest(Object sender, EventArgs e)
 {
     // Request Logging
     if (LogManagerConfiguration.Current.LogWebRequests)
     {
         try
         {
             WebLogEntry entry = new WebLogEntry()
             {
                 ErrorLevel = ErrorLevels.Info,
                 Message = this.Context.Request.FilePath,
                 RequestDuration = (decimal)DateTime.Now.Subtract(Context.Timestamp).TotalMilliseconds
             };
             entry.UpdateFromRequest(this.Context);
             LogManager.Current.WriteEntry(entry);
         }
         catch { ;}
     }
 }
Example #26
0
        /// <summary>
        /// Writes an entry to the log
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public bool WriteEntry(WebLogEntry entry)
        {
            lock (_writeLock)
            {
                if (entry.Id == 0)
                    entry.Id = entry.GetHashCode();

                string logFilename = ConnectionString;
                bool writeEndDoc = true;
                FileStream fileStream = null;
                try
                {
                    fileStream = new FileStream(logFilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
                    fileStream.Seek(0, SeekOrigin.End);

                    // *** If the file's not empty start writing over the end doc tag
                    // *** We'll rewrite it at the end
                    if (fileStream.Position > 0)
                        fileStream.Seek(-1 * "</ApplicationLog>\r\n".Length, SeekOrigin.End);
                }
                catch
                {
                    return false;
                }

                XmlTextWriter writer = new XmlTextWriter((Stream)fileStream, Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                writer.IndentChar = ' ';
                writer.Indentation = 4;

                // *** If the file is empty write the root element
                if (fileStream.Position == 0)
                {
                    writer.WriteStartElement("ApplicationLog");
                    writeEndDoc = false; // it'll automatically unwind the StartElement
                }

                writer.WriteStartElement("LogEntry");
                writer.WriteElementString("Id", entry.Id.ToString());

                writer.WriteStartElement("Entered");
                writer.WriteValue(entry.Entered);
                writer.WriteEndElement();

                writer.WriteElementString("Message", entry.Message);
                writer.WriteElementString("ErrorLevel", entry.ErrorLevel.ToString());
                writer.WriteElementString("Details", entry.Details);

                writer.WriteElementString("Url", entry.Url);
                writer.WriteElementString("QueryString", entry.QueryString);
                writer.WriteElementString("UserAgent", entry.UserAgent);
                writer.WriteElementString("Referrer", entry.Referrer);
                writer.WriteElementString("PostData", entry.PostData);
                writer.WriteElementString("IpAddress", entry.IpAddress);
                writer.WriteElementString("RequestDuration", entry.RequestDuration.ToString());

                writer.WriteEndElement(); // error

                if (writeEndDoc)
                    writer.WriteRaw("\r\n</ApplicationLog>\r\n");
                else
                {
                    writer.WriteEndElement();
                    writer.WriteRaw("\r\n");
                }

                writer.Close();
                fileStream.Close();

                return true;
            }
        }
Example #27
0
 /// <summary>
 /// Writes an Error message entry to the log
 /// </summary>
 /// <param name="message"></param>
 /// <param name="details"></param>
 /// <param name="stackTrace"></param>
 /// <returns></returns>
 public bool LogError(string message, 
                     string details = null,
                     string stackTrace = null)
 {
     var entry = new WebLogEntry()
     {
         ErrorLevel = ErrorLevels.Error,
         Message = message,
         Details = details,
         StackTrace = stackTrace
     };
     return Log(entry);
 }                            
Example #28
0
        public void LogManagerWriteWebEntryTest()
        {
            WebLogEntry entry = new WebLogEntry();
            entry.Message = "Testing " + DateTime.Now.ToString();
            entry.ErrorLevel = ErrorLevels.Info;
            entry.Url = "/wwstore/admin.aspx";
            entry.QueryString = "action=show";
            entry.PostData = "Bogus".PadRight(3000, '.');

            bool res = LogManager.Current.WriteEntry(entry);

            Assert.IsTrue(res, "WriteWebEntry failed");
        }
Example #29
0
 /// <summary>
 /// Writes an error entry from an exception to the log
 /// </summary>
 /// <param name="ex"></param>
 /// <param name="logHttpInfo"></param>
 /// <returns></returns>
 public bool LogError(Exception ex, bool logHttpInfo = false)
 {
     var entry = new WebLogEntry(ex);
     return Log(entry, logHttpInfo);
 }
Example #30
0
        public void WriteWebLogEntryTest()
        {
            WebLogEntry entry = new WebLogEntry();
            entry.ErrorLevel = ErrorLevels.Info;
            entry.Message = "Testing " + DateTime.Now.ToString();
            entry.IpAddress = "127.0.0.1";
            entry.Referrer = "http://www.west-wind.com/";
            entry.Url = "/wwstore/default.aspx";
            entry.QueryString = "Logout=true";
            entry.RequestDuration = 0.12M;

            bool res = LogManager.Current.WriteEntry(entry);

            Assert.IsTrue(res, "Entry couldn't be written to database");

            LogEntry entry2 = LogManager.Current.GetWebLogEntry(entry.Id);

            Assert.IsTrue(entry.Message == entry2.Message);
            Assert.IsTrue(entry.ErrorLevel == entry2.ErrorLevel);
        }
Example #31
0
 /// <summary>
 /// Writes a warning message to the log
 /// </summary>
 /// <param name="message"></param>
 /// <param name="details"></param>
 /// <param name="stackTrace"></param>
 /// <param name="logHttpInfo"></param>
 /// <returns></returns>
 public bool LogWarning(string message, 
             string details = null,
             string stackTrace = null,
             bool logHttpInfo = false)
 {
     var entry = new WebLogEntry()
     {
         ErrorLevel = ErrorLevels.Warning,
         Message = message,
         Details = details,
         StackTrace = stackTrace
     };
     return Log(entry, logHttpInfo);
 } 
Example #32
0
 /// <summary>
 /// Writes a Web specific log entry into the log
 /// </summary>
 /// <param name="entry"></param>
 /// <returns></returns>        
 public bool WriteEntry(WebLogEntry entry)
 {
     return LogAdapter.WriteEntry(entry);
 }
        /// <summary>
        /// Writes an entry to the log
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public bool WriteEntry(WebLogEntry entry)
        {
            if (entry.Id == 0)
            {
                entry.Id = entry.GetHashCode();
            }


            string logFilename = ConnectionString;
            bool   writeEndDoc = true;

            lock (_writeLock)
            {
                try
                {
                    using (var fileStream = new FileStream(logFilename, FileMode.OpenOrCreate, FileAccess.Write))
                        using (var sw = new StreamWriter(fileStream))
                        {
                            fileStream.Seek(0, SeekOrigin.End);

                            sw.WriteLine($"Time:       {entry.Entered.ToString("yyyy-MM-dd HH:mm:ss")}");
                            sw.WriteLine($"Id:         {entry.Id}");
                            sw.WriteLine($"Message:    {entry.Message}");
                            sw.WriteLine($"ErrorLevel: {entry.ErrorLevel}");


                            if (!string.IsNullOrEmpty(entry.Url))
                            {
                                sw.WriteLine($"Url:        {entry.Url}");
                            }
                            if (!string.IsNullOrEmpty(entry.QueryString))
                            {
                                sw.WriteLine($"Query:      {entry.QueryString}");
                            }
                            if (!string.IsNullOrEmpty(entry.Referrer))
                            {
                                sw.WriteLine($"Referrer:   {entry.Referrer}");
                            }
                            if (!string.IsNullOrEmpty(entry.IpAddress))
                            {
                                sw.WriteLine($"IpAddress:  {entry.IpAddress}");
                            }
                            if (!string.IsNullOrEmpty(entry.UserAgent))
                            {
                                sw.WriteLine($"UserAgent:  {entry.UserAgent}");
                            }

                            if (!string.IsNullOrEmpty(entry.PostData))
                            {
                                sw.WriteLine($"PostData:   {entry.PostData.Replace("&","\r\n")}");
                            }

                            if (!string.IsNullOrEmpty(entry.Details))
                            {
                                sw.WriteLine($"Details:    {entry.Details}");
                            }

                            if (entry.RequestDuration > 0)
                            {
                                sw.WriteLine($"Duration:       {entry.RequestDuration}");
                            }


                            sw.WriteLine("----------------------------------------");
                        }
                }
                catch
                {
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Writes an entry to the log
        /// </summary>
        /// <param name="entry"></param>
        /// <returns></returns>
        public bool WriteEntry(WebLogEntry entry)
        {
            lock (_writeLock)
            {
                if (entry.Id == 0)
                {
                    entry.Id = entry.GetHashCode();
                }


                string     logFilename = ConnectionString;
                bool       writeEndDoc = true;
                FileStream fileStream  = null;
                try
                {
                    fileStream = new FileStream(logFilename, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);
                    fileStream.Seek(0, SeekOrigin.End);

                    // *** If the file's not empty start writing over the end doc tag
                    // *** We'll rewrite it at the end
                    if (fileStream.Position > 15)
                    {
                        try
                        {
                            fileStream.Seek(-1 * "</ApplicationLog>\r\n".Length, SeekOrigin.End);
                        }catch { }
                    }
                }
                catch
                {
                    return(false);
                }

                XmlTextWriter writer = new XmlTextWriter((Stream)fileStream, Encoding.UTF8);
                writer.Formatting  = Formatting.Indented;
                writer.IndentChar  = ' ';
                writer.Indentation = 4;

                // *** If the file is empty write the root element
                if (fileStream.Position == 0)
                {
                    writer.WriteStartElement("ApplicationLog");
                    writeEndDoc = false; // it'll automatically unwind the StartElement
                }

                writer.WriteStartElement("LogEntry");
                writer.WriteElementString("Id", entry.Id.ToString());

                writer.WriteStartElement("Entered");
                writer.WriteValue(entry.Entered);
                writer.WriteEndElement();

                writer.WriteElementString("Message", entry.Message);
                writer.WriteElementString("ErrorLevel", entry.ErrorLevel.ToString());
                writer.WriteElementString("Details", entry.Details);

                writer.WriteElementString("Url", entry.Url);
                writer.WriteElementString("QueryString", entry.QueryString);
                writer.WriteElementString("UserAgent", entry.UserAgent);
                writer.WriteElementString("Referrer", entry.Referrer);
                writer.WriteElementString("PostData", entry.PostData);
                writer.WriteElementString("IpAddress", entry.IpAddress);
                writer.WriteElementString("RequestDuration", entry.RequestDuration.ToString());

                writer.WriteEndElement(); // error


                if (writeEndDoc)
                {
                    writer.WriteRaw("\r\n</ApplicationLog>\r\n");
                }
                else
                {
                    writer.WriteEndElement();
                    writer.WriteRaw("\r\n");
                }

                writer.Close();
                fileStream.Close();

                return(true);
            }
        }
Example #35
0
 /// <summary>
 /// Writes a Web specific log entry into the log
 /// </summary>
 /// <param name="entry"></param>
 /// <returns></returns>
 public bool Log(WebLogEntry entry, bool logHttpInfo = false)
 {
     if (logHttpInfo)
         entry.UpdateFromRequest();
     
     return LogAdapter.WriteEntry(entry);            
 }
        public void ExecuteDataReaderToListManualTest()
        {
            SqlDataAccess data = new SqlDataAccess(STR_ConnectionString);

            var swatch = new Stopwatch();
            swatch.Start();

            var entries = new List<WebLogEntry>();
            var reader = data.ExecuteReader("select * from ApplicationLog");

            while (reader.Read())
            {
                WebLogEntry entry = new WebLogEntry();
                entry.Details = reader["Details"] as string;
                entry.Entered = (DateTime) reader["Entered"];
                entry.ErrorLevel = (ErrorLevels) reader["ErrorLevel"];
                entry.Id = (int) reader["id"];
                entry.IpAddress = reader["IpAddress"] as string;
                entry.Message = reader["Message"] as string;
                entry.PostData = reader["PostData"] as string;
                entry.QueryString = reader["QueryString"] as string;
                entry.Referrer = reader["Referrer"] as string;
                entry.RequestDuration = (decimal) reader["RequestDuration"];
                entry.Url = reader["Url"] as string;
                entry.UserAgent = reader["UserAgent"] as string;

                entries.Add(entry);
            }
            reader.Close();

            swatch.Stop();

            Console.WriteLine(swatch.ElapsedMilliseconds);
            Console.WriteLine(entries.Count);
        }
Example #37
0
        protected void Application_Error()
        {
            try
            {
                Exception serverException = Server.GetLastError();

                WebErrorHandler errorHandler;

                // Try to log the inner Exception since that's what
                // contains the 'real' error.
                if (serverException.InnerException != null)
                    serverException = serverException.InnerException;

                errorHandler = new WebErrorHandler(serverException);
                
                // MUST clear out any previous response in case error occurred in a view
                // that already started rendering
                Response.Clear();


                // Log the error if specified
                if (LogManagerConfiguration.Current.LogErrors)
                {
                    errorHandler.Parse();

                    //try
                    //{
                        WebLogEntry entry = new WebLogEntry(serverException, this.Context);
                        entry.Details = errorHandler.ToString();

                        LogManager.Current.WriteEntry(entry);
                    //}
                    //catch {  /* Log Error shouldn't kill the error handler */ }
                }

                // Retrieve the detailed String information of the Error
                string ErrorDetail = errorHandler.ToString();

                // Optionally email it to the Admin contacts set up in WebStoreConfig
                if (!string.IsNullOrEmpty(App.Configuration.ErrorEmailAddress))
                    AppWebUtils.SendAdminEmail(App.Configuration.ApplicationTitle + "Error: " + Request.RawUrl, ErrorDetail, "", 
                                               App.Configuration.ErrorEmailAddress);


                // Debug modes handle different error display mechanisms
                // Default  - default ASP.Net - depends on web.config settings
                // Developer  - display a generic application error message with no error info
                // User  - display a detailed error message with full error info independent of web.config setting
                if (App.Configuration.DebugMode == DebugModes.DeveloperErrorMessage)
                {

                    Server.ClearError();
                    Response.TrySkipIisCustomErrors = true;
                    ErrorController.ShowErrorPage("Application Error", "<div class='codedisplay'><pre id='Code'>" + HttpUtility.HtmlEncode(ErrorDetail) + "</pre></div>");
                    return;
                }

                else if (App.Configuration.DebugMode == DebugModes.ApplicationErrorMessage)
                {
                    string StockMessage =
                            "The Server Administrator has been notified and the error logged.<p>" +
                            "Please continue by either clicking the back button or by returning to the home page.</p>" +
                            "<p><b><a href='" + Request.ApplicationPath + "'>Click here to continue...</a></b></p>";

                    // Handle some stock errors that may require special error pages
                    HttpException httpException = serverException as HttpException;
                    if (httpException != null)
                    {
                        int HttpCode = httpException.GetHttpCode();
                        Server.ClearError();

                        if (HttpCode == 404) // Page Not Found 
                        {
                            Response.StatusCode = 404;
                            ErrorController.ShowErrorPage("Page not found",
                                "You've accessed an invalid page on this Web server. " +
                                StockMessage,null);
                            return;
                        }
                        if (HttpCode == 401) // Access Denied 
                        {
                            Response.StatusCode = 401;
                            ErrorController.ShowErrorPage("Access Denied",
                                "You've accessed a resource that requires a valid login. " +
                                StockMessage);
                            return;
                        }
                    }

                    // Display a generic error message
                    Server.ClearError();
                    Response.StatusCode = 500;

                    Response.TrySkipIisCustomErrors = true;
                    
                    ErrorController.ShowErrorPage("Application Error",
                        "We're sorry, but an unhandled error occurred on the server. " +
                        StockMessage);

                    return;
                }

                return;
            }
            catch (Exception ex)
            {
                // Failure in the attempt to report failure - try to email
                if (!string.IsNullOrEmpty(App.Configuration.ErrorEmailAddress))
                {
                    AppWebUtils.SendAdminEmail(App.Configuration.ApplicationTitle + "Error: " + Request.RawUrl,
                            "Application_Error failed!\r\n\r\n" +
                            ex.ToString(), "",App.Configuration.ErrorEmailAddress);
                }

                // and display an error message
                Server.ClearError();
                Response.StatusCode = 500;
                Response.TrySkipIisCustomErrors = true;
                
                ErrorController.ShowErrorPage("Application Error Handler Failed",
                        "The application Error Handler failed with an exception." +
                        (App.Configuration.DebugMode == DebugModes.DeveloperErrorMessage ? "<pre>" + ex.ToString() + "</pre>" : ""),null);

            }
        }