/// <summary> /// Appends a <paramref name="loggingEvent"/> to the buffer. /// </summary> /// <param name="loggingEvent">The event to append to the buffer.</param> /// <returns>The event discarded from the buffer, if the buffer is full, otherwise <c>null</c>.</returns> /// <remarks> /// <para> /// Append an event to the buffer. If the buffer still contains free space then /// <c>null</c> is returned. If the buffer is full then an event will be dropped /// to make space for the new event, the event dropped is returned. /// </para> /// </remarks> public LoggingEvent Append(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } lock (this) { // save the discarded event LoggingEvent discardedLoggingEvent = m_events[m_last]; // overwrite the last event position m_events[m_last] = loggingEvent; if (++m_last == m_maxSize) { m_last = 0; } if (m_numElems < m_maxSize) { m_numElems++; } else if (++m_first == m_maxSize) { m_first = 0; } if (m_numElems < m_maxSize) { // Space remaining return null; } else { // Buffer is full and discarding an event return discardedLoggingEvent; } } }
/// <summary> /// Write the exception text to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// If an exception object is stored in the logging event /// it will be rendered into the pattern output with a /// trailing newline. /// </para> /// <para> /// If there is no exception or the exception property specified /// by the Option value does not exist then nothing will be output /// and no trailing newline will be appended. /// It is typical to put a newline before the exception /// and to have the exception as the last data in the pattern. /// </para> /// <para> /// Recognized values for the Option parameter are: /// </para> /// <list type="bullet"> /// <item> /// <description>Message</description> /// </item> /// <item> /// <description>Source</description> /// </item> /// <item> /// <description>StackTrace</description> /// </item> /// <item> /// <description>TargetSite</description> /// </item> /// <item> /// <description>HelpLink</description> /// </item> /// </list> /// </remarks> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (loggingEvent.ExceptionObject != null && Option != null && Option.Length > 0) { switch (Option.ToLower()) { case "message": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Message); break; #if !NETCF case "source": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.Source); break; case "stacktrace": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.StackTrace); break; case "targetsite": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.TargetSite); break; case "helplink": WriteObject(writer, loggingEvent.Repository, loggingEvent.ExceptionObject.HelpLink); break; #endif default: // do not output SystemInfo.NotAvailableText break; } } else { string exceptionString = loggingEvent.GetExceptionString(); if (exceptionString != null && exceptionString.Length > 0) { writer.WriteLine(exceptionString); } else { // do not output SystemInfo.NotAvailableText } } }
/// <summary> /// Gets the exception text from the logging event /// </summary> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// Write the exception string to the <see cref="TextWriter"/>. /// The exception string is retrieved from <see cref="LoggingEvent.GetExceptionString()"/>. /// </para> /// </remarks> override public void Format(TextWriter writer, LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } writer.Write(loggingEvent.GetExceptionString()); }
/// <summary> /// Append on on all attached appenders. /// </summary> /// <param name="loggingEvents">The array of events being logged.</param> /// <returns>The number of appenders called.</returns> /// <remarks> /// <para> /// Calls the <see cref="IAppender.DoAppend" /> method on all /// attached appenders. /// </para> /// </remarks> public int AppendLoopOnAppenders(LoggingEvent[] loggingEvents) { if (loggingEvents == null) { throw new ArgumentNullException("loggingEvents"); } if (loggingEvents.Length == 0) { throw new ArgumentException("loggingEvents array must not be empty", "loggingEvents"); } if (loggingEvents.Length == 1) { // Fall back to single event path return AppendLoopOnAppenders(loggingEvents[0]); } // m_appenderList is null when empty if (m_appenderList == null) { return 0; } if (m_appenderArray == null) { m_appenderArray = m_appenderList.ToArray(); } foreach (IAppender appender in m_appenderArray) { try { CallAppend(appender, loggingEvents); } catch (Exception ex) { LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); } } return m_appenderList.Count; }
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (HttpContext.Current == null) { writer.Write(SystemInfo.NotAvailableText); } else { Convert(writer, loggingEvent, HttpContext.Current); } }
/// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes the event to the console. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> override protected void Append(GodLesZ.Library.Logging.Core.LoggingEvent loggingEvent) { string loggingMessage = RenderLoggingEvent(loggingEvent); // see if there is a specified lookup. LevelColors levelColors = m_levelMapping.Lookup(loggingEvent.Level) as LevelColors; if (levelColors != null) { // Prepend the Ansi Color code loggingMessage = levelColors.CombinedColor + loggingMessage; } // on most terminals there are weird effects if we don't clear the background color // before the new line. This checks to see if it ends with a newline, and if // so, inserts the clear codes before the newline, otherwise the clear codes // are inserted afterwards. if (loggingMessage.Length > 1) { if (loggingMessage.EndsWith("\r\n") || loggingMessage.EndsWith("\n\r")) { loggingMessage = loggingMessage.Insert(loggingMessage.Length - 2, PostEventCodes); } else if (loggingMessage.EndsWith("\n") || loggingMessage.EndsWith("\r")) { loggingMessage = loggingMessage.Insert(loggingMessage.Length - 1, PostEventCodes); } else { loggingMessage = loggingMessage + PostEventCodes; } } else { if (loggingMessage[0] == '\n' || loggingMessage[0] == '\r') { loggingMessage = PostEventCodes + loggingMessage; } else { loggingMessage = loggingMessage + PostEventCodes; } } #if NETCF_1_0 // Write to the output stream Console.Write(loggingMessage); #else if (m_writeToErrorStream) { // Write to the error stream Console.Error.Write(loggingMessage); } else { // Write to the output stream Console.Write(loggingMessage); } #endif }
/// <summary> /// Write the ASP.Net HttpContext item to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">The <see cref="LoggingEvent" /> on which the pattern converter should be executed.</param> /// <param name="httpContext">The <see cref="HttpContext" /> under which the ASP.Net request is running.</param> /// <remarks> /// <para> /// Writes out the value of a named property. The property name /// should be set in the <see cref="GodLesZ.Library.Logging.Util.PatternConverter.Option"/> /// property. /// </para> /// </remarks> protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) { if (Option != null) { WriteObject(writer, loggingEvent.Repository, httpContext.Items[Option]); } else { WriteObject(writer, loggingEvent.Repository, httpContext.Items); } }
/// <summary> /// Write the TimeStamp to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// Pass the <see cref="LoggingEvent.TimeStamp"/> to the <see cref="IDateFormatter"/> /// for it to render it to the writer. /// </para> /// <para> /// The <see cref="LoggingEvent.TimeStamp"/> passed is in the local time zone, this is converted /// to Universal time before it is rendered. /// </para> /// </remarks> /// <seealso cref="DatePatternConverter"/> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { try { m_dateFormatter.FormatDate(loggingEvent.TimeStamp.ToUniversalTime(), writer); } catch (Exception ex) { LogLog.Error(declaringType, "Error occurred while converting date.", ex); } }
/// <summary> /// Write the property value to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// Writes out the value of a named property. The property name /// should be set in the <see cref="GodLesZ.Library.Logging.Util.PatternConverter.Option"/> /// property. /// </para> /// <para> /// If the <see cref="GodLesZ.Library.Logging.Util.PatternConverter.Option"/> is set to <c>null</c> /// then all the properties are written as key value pairs. /// </para> /// </remarks> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { if (Option != null) { // Write the value for the specified key WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(Option)); } else { // Write all the key value pairs WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties()); } }
/// <summary> /// Produces a simple formatted output. /// </summary> /// <param name="loggingEvent">the event being logged</param> /// <param name="writer">The TextWriter to write the formatted event to</param> /// <remarks> /// <para> /// Formats the event as the level of the even, /// followed by " - " and then the log message itself. The /// output is terminated by a newline. /// </para> /// </remarks> override public void Format(TextWriter writer, LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } writer.Write(loggingEvent.Level.DisplayName); writer.Write(" - "); loggingEvent.WriteRenderedMessage(writer); writer.WriteLine(); }
/// <summary> /// Write the ASP.Net Cache item to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">The <see cref="LoggingEvent" /> on which the pattern converter should be executed.</param> /// <param name="httpContext">The <see cref="HttpContext" /> under which the ASP.Net request is running.</param> /// <remarks> /// <para> /// Writes out the value of a named property. The property name /// should be set in the <see cref="GodLesZ.Library.Logging.Util.PatternConverter.Option"/> /// property. If no property has been set, all key value pairs from the Cache will /// be written to the output. /// </para> /// </remarks> protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) { if (HttpRuntime.Cache != null) { if (Option != null) { WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache[Option]); } else { WriteObject(writer, loggingEvent.Repository, HttpRuntime.Cache.GetEnumerator()); } } else { writer.Write(SystemInfo.NotAvailableText); } }
/// <summary> /// Constructor /// </summary> /// <param name="maxSize">The maximum number of logging events in the buffer.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="CyclicBuffer" /> class with /// the specified maximum number of buffered logging events. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="maxSize"/> argument is not a positive integer.</exception> public CyclicBuffer(int maxSize) { if (maxSize < 1) { throw SystemInfo.CreateArgumentOutOfRangeException("maxSize", (object)maxSize, "Parameter: maxSize, Value: [" + maxSize + "] out of range. Non zero positive integer required"); } m_maxSize = maxSize; m_events = new LoggingEvent[maxSize]; m_first = 0; m_last = 0; m_numElems = 0; }
/// <summary> /// Write the ASP.Net Cache item to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">The <see cref="LoggingEvent" /> on which the pattern converter should be executed.</param> /// <param name="httpContext">The <see cref="HttpContext" /> under which the ASP.Net request is running.</param> /// <remarks> /// <para> /// Writes out the value of a named property. The property name /// should be set in the <see cref="GodLesZ.Library.Logging.Util.PatternConverter.Option"/> /// property. If no property has been set, all key value pairs from the Session will /// be written to the output. /// </para> /// </remarks> protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext) { if (httpContext.Session != null) { if (Option != null) { WriteObject(writer, loggingEvent.Repository, httpContext.Session.Contents[Option]); } else { WriteObject(writer, loggingEvent.Repository, httpContext.Session); } } else { writer.Write(SystemInfo.NotAvailableText); } }
/// <summary> /// Write the logging event to the ASP.NET trace /// </summary> /// <param name="loggingEvent">the event to log</param> /// <remarks> /// <para> /// Write the logging event to the ASP.NET trace /// <c>HttpContext.Current.Trace</c> /// (<see cref="TraceContext"/>). /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { // check if GodLesZ.Library.Logging is running in the context of an ASP.NET application if (HttpContext.Current != null) { // check if tracing is enabled for the current context if (HttpContext.Current.Trace.IsEnabled) { if (loggingEvent.Level >= Level.Warn) { HttpContext.Current.Trace.Warn(m_category.Format(loggingEvent), RenderLoggingEvent(loggingEvent)); } else { HttpContext.Current.Trace.Write(m_category.Format(loggingEvent), RenderLoggingEvent(loggingEvent)); } } } }
/// <summary> /// Is this <paramref name="loggingEvent"/> the triggering event? /// </summary> /// <param name="loggingEvent">The event to check</param> /// <returns>This method returns <c>true</c>, if the logging event Exception /// Type is <see cref="ExceptionType"/>. /// Otherwise it returns <c>false</c></returns> /// <remarks> /// <para> /// This evaluator will trigger if the Exception Type of the event /// passed to <see cref="IsTriggeringEvent(LoggingEvent)"/> /// is <see cref="ExceptionType"/>. /// </para> /// </remarks> public bool IsTriggeringEvent(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } if (m_triggerOnSubclass && loggingEvent.ExceptionObject != null) { // check if loggingEvent.ExceptionObject is of type ExceptionType or subclass of ExceptionType Type exceptionObjectType = loggingEvent.ExceptionObject.GetType(); return exceptionObjectType == m_type || exceptionObjectType.IsSubclassOf(m_type); } else if (!m_triggerOnSubclass && loggingEvent.ExceptionObject != null) { // check if loggingEvent.ExceptionObject is of type ExceptionType return loggingEvent.ExceptionObject.GetType() == m_type; } else { // loggingEvent.ExceptionObject is null return false; } }
/// <summary> /// Write the strack frames to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// Writes the <see cref="LocationInfo.StackFrames"/> to the output writer. /// </para> /// </remarks> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { StackFrame[] stackframes = loggingEvent.LocationInformation.StackFrames; if ((stackframes == null) || (stackframes.Length <= 0)) { LogLog.Error(declaringType, "loggingEvent.LocationInformation.StackFrames was null or empty."); return; } int stackFrameIndex = m_stackFrameLevel - 1; while (stackFrameIndex >= 0) { if (stackFrameIndex > stackframes.Length) { stackFrameIndex--; continue; } StackFrame stackFrame = stackframes[stackFrameIndex]; writer.Write("{0}.{1}", stackFrame.GetMethod().DeclaringType.Name, GetMethodInformation(stackFrame.GetMethod())); if (stackFrameIndex > 0) { // TODO: make this user settable? writer.Write(" > "); } stackFrameIndex--; } }
/// <summary> /// Append on on all attached appenders. /// </summary> /// <param name="loggingEvent">The event being logged.</param> /// <returns>The number of appenders called.</returns> /// <remarks> /// <para> /// Calls the <see cref="IAppender.DoAppend" /> method on all /// attached appenders. /// </para> /// </remarks> public int AppendLoopOnAppenders(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } // m_appenderList is null when empty if (m_appenderList == null) { return 0; } if (m_appenderArray == null) { m_appenderArray = m_appenderList.ToArray(); } foreach (IAppender appender in m_appenderArray) { try { appender.DoAppend(loggingEvent); } catch (Exception ex) { LogLog.Error(declaringType, "Failed to append to appender [" + appender.Name + "]", ex); } } return m_appenderList.Count; }
/// <summary> /// Sends the events. /// </summary> /// <param name="events">The events that need to be send.</param> /// <remarks> /// <para> /// The subclass must override this method to process the buffered events. /// </para> /// </remarks> abstract protected void SendBuffer(LoggingEvent[] events);
/// <summary> /// Sends the contents of the buffer. /// </summary> /// <param name="firstLoggingEvent">The first logging event.</param> /// <param name="buffer">The buffer containing the events that need to be send.</param> /// <remarks> /// <para> /// The subclass must override <see cref="SendBuffer(LoggingEvent[])"/>. /// </para> /// </remarks> virtual protected void SendFromBuffer(LoggingEvent firstLoggingEvent, CyclicBuffer buffer) { LoggingEvent[] bufferEvents = buffer.PopAll(); if (firstLoggingEvent == null) { SendBuffer(bufferEvents); } else if (bufferEvents.Length == 0) { SendBuffer(new LoggingEvent[] { firstLoggingEvent }); } else { // Create new array with the firstLoggingEvent at the head LoggingEvent[] events = new LoggingEvent[bufferEvents.Length + 1]; Array.Copy(bufferEvents, 0, events, 1, bufferEvents.Length); events[0] = firstLoggingEvent; SendBuffer(events); } }
/// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">the event to log</param> /// <remarks> /// <para> /// Stores the <paramref name="loggingEvent"/> in the cyclic buffer. /// </para> /// <para> /// The buffer will be sent (i.e. passed to the <see cref="SendBuffer"/> /// method) if one of the following conditions is met: /// </para> /// <list type="bullet"> /// <item> /// <description>The cyclic buffer is full and this appender is /// marked as not lossy (see <see cref="Lossy"/>)</description> /// </item> /// <item> /// <description>An <see cref="Evaluator"/> is set and /// it is triggered for the <paramref name="loggingEvent"/> /// specified.</description> /// </item> /// </list> /// <para> /// Before the event is stored in the buffer it is fixed /// (see <see cref="LoggingEvent.FixVolatileData(FixFlags)"/>) to ensure that /// any data referenced by the event will be valid when the buffer /// is processed. /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { // If the buffer size is set to 1 or less then the buffer will be // sent immediately because there is not enough space in the buffer // to buffer up more than 1 event. Therefore as a special case // we don't use the buffer at all. if (m_cb == null || m_bufferSize <= 1) { // Only send the event if we are in non lossy mode or the event is a triggering event if ((!m_lossy) || (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent)) || (m_lossyEvaluator != null && m_lossyEvaluator.IsTriggeringEvent(loggingEvent))) { if (m_eventMustBeFixed) { // Derive class expects fixed events loggingEvent.Fix = this.Fix; } // Not buffering events, send immediately SendBuffer(new LoggingEvent[] { loggingEvent }); } } else { // Because we are caching the LoggingEvent beyond the // lifetime of the Append() method we must fix any // volatile data in the event. loggingEvent.Fix = this.Fix; // Add to the buffer, returns the event discarded from the buffer if there is no space remaining after the append LoggingEvent discardedLoggingEvent = m_cb.Append(loggingEvent); if (discardedLoggingEvent != null) { // Buffer is full and has had to discard an event if (!m_lossy) { // Not lossy, must send all events SendFromBuffer(discardedLoggingEvent, m_cb); } else { // Check if the discarded event should not be logged if (m_lossyEvaluator == null || !m_lossyEvaluator.IsTriggeringEvent(discardedLoggingEvent)) { // Clear the discarded event as we should not forward it discardedLoggingEvent = null; } // Check if the event should trigger the whole buffer to be sent if (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent)) { SendFromBuffer(discardedLoggingEvent, m_cb); } else if (discardedLoggingEvent != null) { // Just send the discarded event SendBuffer(new LoggingEvent[] { discardedLoggingEvent }); } } } else { // Buffer is not yet full // Check if the event should trigger the whole buffer to be sent if (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent)) { SendFromBuffer(null, m_cb); } } } }
/// <summary> /// Is this <paramref name="loggingEvent"/> the triggering event? /// </summary> /// <param name="loggingEvent">The event to check</param> /// <returns>This method returns <c>true</c>, if the event level /// is equal or higher than the <see cref="Threshold"/>. /// Otherwise it returns <c>false</c></returns> /// <remarks> /// <para> /// This evaluator will trigger if the level of the event /// passed to <see cref="IsTriggeringEvent(LoggingEvent)"/> /// is equal to or greater than the <see cref="Threshold"/> /// level. /// </para> /// </remarks> public bool IsTriggeringEvent(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } return (loggingEvent.Level >= m_threshold); }
/// <summary> /// Formats the log message into database statement text. /// </summary> /// <param name="logEvent">The event being logged.</param> /// <remarks> /// This method can be overridden by subclasses to provide /// more control over the format of the database statement. /// </remarks> /// <returns> /// Text that can be passed to a <see cref="System.Data.IDbCommand"/>. /// </returns> virtual protected string GetLogStatement(LoggingEvent logEvent) { if (Layout == null) { ErrorHandler.Error("AdoNetAppender: No Layout specified."); return ""; } else { StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); Layout.Format(writer, logEvent); return writer.ToString(); } }
/// <summary> /// Writes the events to the database using the transaction specified. /// </summary> /// <param name="dbTran">The transaction that the events will be executed under.</param> /// <param name="events">The array of events to insert into the database.</param> /// <remarks> /// <para> /// The transaction argument can be <c>null</c> if the appender has been /// configured not to use transactions. See <see cref="UseTransactions"/> /// property for more information. /// </para> /// </remarks> virtual protected void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events) { if (m_usePreparedCommand) { // Send buffer using the prepared command object if (m_dbCommand != null) { if (dbTran != null) { m_dbCommand.Transaction = dbTran; } // run for all events foreach (LoggingEvent e in events) { // Set the parameter values foreach (AdoNetAppenderParameter param in m_parameters) { param.FormatValue(m_dbCommand, e); } // Execute the query m_dbCommand.ExecuteNonQuery(); } } } else { // create a new command using (IDbCommand dbCmd = m_dbConnection.CreateCommand()) { if (dbTran != null) { dbCmd.Transaction = dbTran; } // run for all events foreach (LoggingEvent e in events) { // Get the command text from the Layout string logStatement = GetLogStatement(e); LogLog.Debug(declaringType, "LogStatement [" + logStatement + "]"); dbCmd.CommandText = logStatement; dbCmd.ExecuteNonQuery(); } } } }
/// <summary> /// Inserts the events into the database. /// </summary> /// <param name="events">The events to insert into the database.</param> /// <remarks> /// <para> /// Insert all the events specified in the <paramref name="events"/> /// array into the database. /// </para> /// </remarks> override protected void SendBuffer(LoggingEvent[] events) { if (m_reconnectOnError && (m_dbConnection == null || m_dbConnection.State != ConnectionState.Open)) { LogLog.Debug(declaringType, "Attempting to reconnect to database. Current Connection State: " + ((m_dbConnection == null) ? SystemInfo.NullText : m_dbConnection.State.ToString())); InitializeDatabaseConnection(); InitializeDatabaseCommand(); } // Check that the connection exists and is open if (m_dbConnection != null && m_dbConnection.State == ConnectionState.Open) { if (m_useTransactions) { // Create transaction // NJC - Do this on 2 lines because it can confuse the debugger IDbTransaction dbTran = null; try { dbTran = m_dbConnection.BeginTransaction(); SendBuffer(dbTran, events); // commit transaction dbTran.Commit(); } catch (Exception ex) { // rollback the transaction if (dbTran != null) { try { dbTran.Rollback(); } catch (Exception) { // Ignore exception } } // Can't insert into the database. That's a bad thing ErrorHandler.Error("Exception while writing to database", ex); } } else { // Send without transaction SendBuffer(null, events); } } }
/// <summary> /// Renders the logging event and set the parameter value in the command. /// </summary> /// <param name="command">The command containing the parameter.</param> /// <param name="loggingEvent">The event to be rendered.</param> /// <remarks> /// <para> /// Renders the logging event using this parameters layout /// object. Sets the value of the parameter on the command object. /// </para> /// </remarks> virtual public void FormatValue(IDbCommand command, LoggingEvent loggingEvent) { // Lookup the parameter IDbDataParameter param = (IDbDataParameter)command.Parameters[m_parameterName]; // Format the value object formattedValue = Layout.Format(loggingEvent); // If the value is null then convert to a DBNull if (formattedValue == null) { formattedValue = DBNull.Value; } param.Value = formattedValue; }
/// <summary> /// Write the method name to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// Writes the caller location <see cref="LocationInfo.MethodName"/> to /// the output. /// </para> /// </remarks> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { writer.Write(loggingEvent.LocationInformation.MethodName); }
/// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">the event to log</param> /// <remarks> /// <para>Stores the <paramref name="loggingEvent"/> in the events list.</para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { // Because we are caching the LoggingEvent beyond the // lifetime of the Append() method we must fix any // volatile data in the event. loggingEvent.Fix = this.Fix; lock (m_eventsList.SyncRoot) { m_eventsList.Add(loggingEvent); } }
/// <summary> /// Writes the event message to the output /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> /// <remarks> /// <para> /// Uses the <see cref="LoggingEvent.WriteRenderedMessage"/> method /// to write out the event message. /// </para> /// </remarks> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { loggingEvent.WriteRenderedMessage(writer); }
/// <summary> /// Does the actual writing of the XML. /// </summary> /// <param name="writer">The writer to use to output the event to.</param> /// <param name="loggingEvent">The event to write.</param> /// <remarks> /// <para> /// Override the base class <see cref="XmlLayoutBase.FormatXml"/> method /// to write the <see cref="LoggingEvent"/> to the <see cref="XmlWriter"/>. /// </para> /// </remarks> override protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) { writer.WriteStartElement(m_elmEvent); writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName); #if NET_2_0 || NETCF_2_0 || MONO_2_0 writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local)); #else writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp)); #endif writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName); writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName); if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) { writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain); } if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0) { writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity); } if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0) { writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName); } // Append the message text writer.WriteStartElement(m_elmMessage); if (!this.Base64EncodeMessage) { Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); } else { byte[] messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage); string base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length); Transform.WriteEscapedXmlString(writer, base64Message, this.InvalidCharReplacement); } writer.WriteEndElement(); PropertiesDictionary properties = loggingEvent.GetProperties(); // Append the properties text if (properties.Count > 0) { writer.WriteStartElement(m_elmProperties); foreach (System.Collections.DictionaryEntry entry in properties) { writer.WriteStartElement(m_elmData); writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key, this.InvalidCharReplacement)); // Use an ObjectRenderer to convert the object to a string string valueStr = null; if (!this.Base64EncodeProperties) { valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value), this.InvalidCharReplacement); } else { byte[] propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value)); valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length); } writer.WriteAttributeString(ATTR_VALUE, valueStr); writer.WriteEndElement(); } writer.WriteEndElement(); } string exceptionStr = loggingEvent.GetExceptionString(); if (exceptionStr != null && exceptionStr.Length > 0) { // Append the stack trace line writer.WriteStartElement(m_elmException); Transform.WriteEscapedXmlString(writer, exceptionStr, this.InvalidCharReplacement); writer.WriteEndElement(); } if (LocationInfo) { LocationInfo locationInfo = loggingEvent.LocationInformation; writer.WriteStartElement(m_elmLocation); writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName); writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName); writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName); writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber); writer.WriteEndElement(); } writer.WriteEndElement(); }
/// <summary> /// Convert the pattern to the rendered message /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="loggingEvent">the event being logged</param> override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { writer.Write(loggingEvent.UserName); }
/// <summary> /// Creates a new logging event and logs the event without further checks. /// </summary> /// <param name="logEvent">The event being logged.</param> /// <remarks> /// <para> /// Delivers the logging event to the attached appenders. /// </para> /// </remarks> virtual protected void ForcedLog(LoggingEvent logEvent) { // The logging event may not have been created by this logger // the Repository may not be correctly set on the event. This // is required for the appenders to correctly lookup renderers etc... logEvent.EnsureRepository(this.Hierarchy); CallAppenders(logEvent); }