Inheritance: ISerializable
Esempio n. 1
0
        protected HttpWebRequest GetRequest(LoggingEvent[] loggingEvents)
        {
            var request = (HttpWebRequest)WebRequest.Create(Url);
            request.KeepAlive = false;
            request.Timeout = 5000;
            request.ServicePoint.ConnectionLeaseTimeout = 5000;
            request.ServicePoint.MaxIdleTime = 5000;
            request.ServicePoint.ConnectionLimit = 50;
            request.Accept = "application/json";
            request.UserAgent = "Pulsus " + Constants.Version;
            request.Method = "POST";
            request.ContentType = "application/json";

            var bytes = GetRequestBody(loggingEvents, Compress);
            request.ContentLength = bytes.Length;
            if (Compress)
                request.Headers.Add("Content-Encoding", "gzip");

            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

            return request;
        }
        public void PushingWithNoTargetsShouldThrow()
        {
            var eventDispatcher = new DefaultEventDispatcher();

            var loggingEvent = new LoggingEvent { Text = "Event" };
            Executing.This(() => eventDispatcher.Push(loggingEvent, false)).Should().Throw<InvalidOperationException>();
        }
		/// <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="Mammothcode.Public.Core.Util.PatternConverter.Option"/>
		/// property.
		/// </para>
		/// </remarks>
		protected override void Convert(TextWriter writer, LoggingEvent loggingEvent, HttpContext httpContext)
		{
		    HttpRequest request = null;
		    try {
			request = httpContext.Request;
		    } catch (HttpException) {
			// likely a case of running in IIS integrated mode
			// when inside an Application_Start event.
			// treat it like a case of the Request
			// property returning null
		    }

			if (request != null)
			{
				if (Option != null)
				{
					WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params[Option]);
				}
				else
				{
					WriteObject(writer, loggingEvent.Repository, httpContext.Request.Params);
				}
			}
			else
			{
				writer.Write(SystemInfo.NotAvailableText);
			}
		}
        public override void Push(LoggingEvent[] loggingEvents)
        {
            if (loggingEvents == null)
                throw new ArgumentNullException("loggingEvents");

            _queue.Enqueue(loggingEvents);
        }
  protected override void Append (LoggingEvent loggingEvent)
  {
    try
    {
      base.Append (loggingEvent);
      if (maximumEntries == 0)
      {
        return;
      }

      lock (m_eventsList.SyncRoot)
      {
        int elementsToRemove = m_eventsList.Count - maximumEntries;
        if (elementsToRemove > 0)
        {
          UnityEngine.Debug.Log ("Removing " + elementsToRemove + " elements.");
          m_eventsList.RemoveRange (0, elementsToRemove);
        }
      }
    }
    catch(Exception e)
    {
      UnityEngine.Debug.LogError(e);
    }
  }
Esempio n. 6
0
 public override void Push(LoggingEvent[] loggingEvents)
 {
     foreach (var loggingEvent in loggingEvents)
     {
         Console.WriteLine(Format.Format(loggingEvent));
     }
 }
		/// <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;
		}
Esempio n. 8
0
        public void Post(LoggingEvent[] loggingEvents)
        {
            var request = GetRequest(loggingEvents);

            try
            {
                var response = request.GetResponse() as HttpWebResponse;

                if (response == null)
                    throw new Exception("There was an error posting the server");

                if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.Accepted)
                    throw new Exception(string.Format("The server returned a {0} status with the message: {1}", response.StatusCode, response.StatusDescription));
            }
            catch (WebException ex)
            {
                if (ex.Response == null)
                    throw new Exception(string.Format("Response Status: {0}, Description: {1}", ex.Status, ex.Message), ex);

                var responseStream = ex.Response.GetResponseStream();
                if (responseStream == null)
                    throw new Exception("GetResponseStream() returned null", ex);

                var reader = new StreamReader(responseStream);
                var responseContent = reader.ReadToEnd();

                throw new Exception(string.Format("Response Status: {0}, Content: {1}", ex.Status, responseContent), ex);
            }
        }
        public EmailTemplateModel(LoggingEvent loggingEvent)
        {
            if (loggingEvent == null)
                throw new ArgumentNullException("loggingEvent");

            LoggingEvent = loggingEvent;
            HttpContextInformation = loggingEvent.GetData<HttpContextInformation>(Constants.DataKeys.HttpContext);
            StackTrace = loggingEvent.GetData<string>(Constants.DataKeys.StackTrace);
            SqlInformation = loggingEvent.GetData<SqlInformation>(Constants.DataKeys.SQL);
            ExceptionInformation = loggingEvent.GetData<ExceptionInformation>(Constants.DataKeys.Exception);

            GeneralSection = new Dictionary<string, object>();
            LoadGeneralSection();

            CustomData = loggingEvent.Data.Where(x => !x.Key.StartsWith("MS_", StringComparison.InvariantCultureIgnoreCase)).ToDictionary(x => x.Key, x => x.Value);
            if (!CustomData.Any())
                CustomData = null;

            RequestSection = new Dictionary<string, object>();
            LoadRequestSection();

            LevelText = Enum.GetName(typeof (LoggingEventLevel), LoggingEvent.Level);
            LevelClass = "green";
            var loggingEventLevelValue = (int) loggingEvent.Level;
            if (loggingEventLevelValue >= 40000 && loggingEventLevelValue <= 60000)
                LevelClass = "yellow";
            else if (loggingEventLevelValue > 60000)
                LevelClass = "red";

            Footer = string.Format(CultureInfo.InvariantCulture, "Pulsus | {0} | {1}", Constants.Version, Constants.WebSite);
        }
Esempio n. 10
0
        public void NullDataValueShouldReturnDefaultValue()
        {
            var loggingEvent = new LoggingEvent();
            loggingEvent.Data.Add("test", null);

            var value = loggingEvent.GetData<string>("test");

            value.Should().Be.Null();
        }
        protected override void Append(LoggingEvent loggingEvent)
        {
            if (string.Empty.Equals(loggingEvent.MessageObject))
                return;

            if (loggingEvent.MessageObject != null)
            {
                Messages.Add(loggingEvent.MessageObject.ToString());
            }
        }
		protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
		{
			if (HttpContext.Current == null)
			{
				writer.Write(SystemInfo.NotAvailableText);
			}
			else
			{
				Convert(writer, loggingEvent, HttpContext.Current);
			}
		}
		/// <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);
			}
		}
Esempio n. 14
0
        public void SerializedDataShoudBeCorrectlyDeserialized()
        {
            const string serializedData = "{ \"custom-data\" : { \"StringField\" : \"test\", \"IntField\" : 9 } }";
            var loggingEvent = new LoggingEvent();
            loggingEvent.Data = JsonConvert.DeserializeObject<IDictionary<string, object>>(serializedData);

            var result = loggingEvent.GetData<CustomData>("custom-data");
            result.Should().Not.Be.Null();
            result.StringField.Should().Be("test");
            result.IntField.Should().Be(9);
        }
 public override FilterDecision Decide(LoggingEvent loggingEvent)
 {
     if (loggingEvent.LoggerName.StartsWith("NServiceBus."))
     {
         if (loggingEvent.Level < Level.Warn)
         {
             return FilterDecision.Deny;
         }
     }
     return FilterDecision.Accept;
 }
		/// <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="Mammothcode.Public.Core.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);
			}
		}
 public void Log(LoggingEvent.LogLevels logLevel, string processName, string subProcessName, string logCategory, string logMessage)
 {
     LoggingEvent logEvent = new LoggingEvent();
     logEvent.LogLevel = logLevel;
     logEvent.DateTimeSource = DateTime.Now;
     logEvent.ProcessName = processName;
     logEvent.SubProcessName = subProcessName;
     logEvent.LogCategory = logCategory;
     logEvent.LogMessage = logMessage;
     m_Queue.Enqueue(logEvent);
     m_EventContinue.Set();
 }
Esempio n. 18
0
        public void Enqueue(LoggingEvent[] loggingEvents)
        {
            lock (_locker)
            {
                // ignore new logging events
                if (_loggingEventQueue.Count >= MaxQueueSize)
                    return;

                foreach (var loggingEvent in loggingEvents)
                    _loggingEventQueue.Enqueue(loggingEvent);
            }
        }
    protected override void Append(LoggingEvent loggingEvent)
    {
        EventHandler<OnLog4NetLogEventArgs> temp = OnLog;

        if (temp != null)
        {
            lock (_syncRoot)
            {
                temp(null, new OnLog4NetLogEventArgs(loggingEvent));
            }
        }
    }
Esempio n. 20
0
File: server.cs Progetto: mono/gert
		public void LogEvents (LoggingEvent [] events)
		{
			if (events != null) {
				foreach (LoggingEvent logEvent in events) {
					string logFile = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
						"log");
					using (StreamWriter sw = File.AppendText (logFile)) {
						sw.WriteLine (logEvent.Message);
					}
				}
			}
		}
		/// <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="Mammothcode.Public.Core.Util.PatternConverter.Option"/>
		/// property.
		/// </para>
		/// <para>
		/// If the <see cref="Mammothcode.Public.Core.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());
			}
		}
        public void CanPushToDefaultTargets()
        {
            var target1Mock = new Mock<ITarget>();
            var target2Mock = new Mock<ITarget>();

            var eventDispatcher = new DefaultEventDispatcher { DefaultTargets = new[] { target1Mock.Object, target2Mock.Object } };

            var loggingEvent = new LoggingEvent { Text = "Event" };
            eventDispatcher.Push(loggingEvent, false);

            target1Mock.Verify(o => o.Log(loggingEvent));
            target2Mock.Verify(o => o.Log(loggingEvent));
        }
Esempio n. 23
0
        public void NonSerializedDataShouldCorrectlyRetrieved()
        {
            var loggingEvent = new LoggingEvent();
            loggingEvent.Data["custom-data"] = new CustomData()
            {
                StringField = "test",
                IntField = 9
            };

            var result = loggingEvent.GetData<CustomData>("custom-data");
            result.Should().Not.Be.Null();
            result.StringField.Should().Be("test");
            result.IntField.Should().Be(9);
        }
Esempio n. 24
0
 public static LoggingEvent Deserialize(MsSqlLoggingEvent mssqlLoggingEvent)
 {
     var result = new LoggingEvent();
     result.EventId = mssqlLoggingEvent.EventId;
     result.Timestamp = mssqlLoggingEvent.Timestamp;
     result.Level = mssqlLoggingEvent.Level;
     result.Value = mssqlLoggingEvent.Value;
     result.Text = mssqlLoggingEvent.Text;
     result.Tags = Pulsus.Tags.Clean(mssqlLoggingEvent.Tags).ToList();
     result.Data = JsonConvert.DeserializeObject<Dictionary<string, object>>(mssqlLoggingEvent.Data);
     result.User = mssqlLoggingEvent.User;
     result.Source = mssqlLoggingEvent.Source;
     return result;
 }
Esempio n. 25
0
 public static MsSqlLoggingEvent Serialize(LoggingEvent loggingEvent)
 {
     var result = new MsSqlLoggingEvent();
     result.EventId = loggingEvent.EventId;
     result.Timestamp = loggingEvent.Timestamp;
     result.Level = loggingEvent.Level;
     result.Value = loggingEvent.Value;
     result.Text = loggingEvent.Text;
     result.Tags = string.Join(" ", loggingEvent.Tags.ToArray());
     result.Data = JsonConvert.SerializeObject(loggingEvent.Data);
     result.User = loggingEvent.User;
     result.Source = loggingEvent.Source;
     return result;
 }
Esempio n. 26
0
        public override void Push(LoggingEvent[] loggingEvents)
        {
            if (loggingEvents == null)
                throw new ArgumentNullException("loggingEvents");

            if (string.IsNullOrEmpty(Url))
                throw new Exception("There is no URL defined for the server target.");

            Uri uri;
            if (!Uri.TryCreate(Url, UriKind.Absolute, out uri))
                throw new Exception("The URL defined for the server target is not valid");

            Post(loggingEvents);
        }
        public void CanAddAndPushToTargets()
        {
            var target1Mock = new Mock<ITarget>();
            var target2Mock = new Mock<ITarget>();

            var eventDispatcher = new DefaultEventDispatcher();

            eventDispatcher.AddTarget(target1Mock.Object);
            eventDispatcher.AddTarget(target2Mock.Object);

            var loggingEvent = new LoggingEvent { Text = "Event" };
            eventDispatcher.Push(loggingEvent, false);

            target1Mock.Verify(o => o.Log(loggingEvent));
            target2Mock.Verify(o => o.Log(loggingEvent));
        }
Esempio n. 28
0
        public void ThrottlingMustBeActivatedWhenThresholdIsReached()
        {
            var loggingEvent = new LoggingEvent()
            {
                Text = "Test"
            };

            var emailTarget = new EmailTargetTester();
            emailTarget.ThrottlingWindow = 1;
            emailTarget.ThrottlingThreshold = 60;
            emailTarget.ThrottlingDuration = 10;

            for (var i = 0; i < 100; i++)
                emailTarget.Push(new[] { loggingEvent });

            emailTarget.Counter.Should().Be(60);
        }
Esempio n. 29
0
        public override void Push(LoggingEvent[] loggingEvents)
        {
            if (HostingEnvironment.IsHosted)
            {
                lock (_locker)
                {
                    if (_shuttingDown)
                        return;

                    PushInternal(loggingEvents);
                }
            }
            else
            {
                PushInternal(loggingEvents);
            }
        }
Esempio n. 30
0
        public override void Push(LoggingEvent[] loggingEvents)
        {
            if (loggingEvents == null)
                throw new ArgumentNullException("loggingEvents");

            if (string.IsNullOrEmpty(AccessKey))
                throw new Exception("You must define an AccessKey");

            if (string.IsNullOrEmpty(SecretKey))
                throw new Exception("You must specify a SecretKey");

            if (string.IsNullOrEmpty(BucketName))
                throw new Exception("You must specify a BucketName");

            foreach (var loggingEvent in loggingEvents)
                Post(loggingEvent);
        }
Esempio n. 31
0
        private void UpdateControl(LoggingEvent loggingEvent)
        {
            if (loggingEvent.Level != Level.Info)
            {
                return;
            }

            if (_listView == null)
            {
                return;
            }

            if (_listView.IsDisposed)
            {
                return;
            }


            // There may be performance issues if the buffer gets too long
            // So periodically clear the buffer
            if (_listView.Items.Count > maxTextLength)
            {
                _listView.Items.Clear();
            }

            ListViewItem lvi = new ListViewItem();

            //switch (loggingEvent.Level.ToString())
            //{
            //    case "INFO":
            //        lvi.ForeColor = System.Drawing.Color.Blue;
            //        break;
            //    case "WARN":
            //        lvi.ForeColor = System.Drawing.Color.Orange;
            //        break;
            //    case "ERROR":
            //        lvi.ForeColor = System.Drawing.Color.Red;
            //        break;
            //    case "FATAL":
            //        lvi.ForeColor = System.Drawing.Color.DarkOrange;
            //        break;
            //    case "DEBUG":
            //        lvi.ForeColor = System.Drawing.Color.DarkGreen;
            //        break;
            //    default:
            //        lvi.ForeColor = System.Drawing.Color.Black;
            //        break;
            //}

            //if (this._listView.Items.Count % 2 == 0)
            //{
            //    lvi.BackColor = System.Drawing.Color.Silver;
            //}
            //else
            //{
            //    lvi.BackColor = System.Drawing.Color.LightBlue;
            //}


            lvi.Text = loggingEvent.TimeStamp.ToString("HH:mm:ss");
            // lvi.SubItems.Add(loggingEvent.UserName);
            //lvi.SubItems.Add(loggingEvent.Level.DisplayName);
            //lvi.SubItems.Add(loggingEvent.LoggerName);
            // lvi.SubItems.Add(string.Format("{0}.{1}.{2}", loggingEvent.LocationInformation.ClassName, loggingEvent.LocationInformation.MethodName, loggingEvent.LocationInformation.LineNumber));
            lvi.SubItems.Add(loggingEvent.RenderedMessage);
            _listView.Items.Add(lvi);
            lvi.EnsureVisible();
            //_listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
        }
 /// <summary>
 /// Call the getter
 /// </summary>
 /// <param name="loggingEvent">the event to get a value for/from</param>
 /// <returns>the value gotten</returns>
 public object Format(LoggingEvent loggingEvent)
 {
     return(m_getter == null ? null : m_getter(loggingEvent));
 }
        protected override void Append(LoggingEvent loggingEvent)
        {
            if (RavenClient == null)
            {
                RavenClient = new RavenClient(DSN)
                {
                    Logger      = Logger,
                    Compression = CompressionEnabled,
                    Environment = Environment,

                    // If something goes wrong when sending the event to Sentry, make sure this is written to log4net's internal
                    // log. See <add key="log4net.Internal.Debug" value="true"/>
                    ErrorOnCapture = ex => LogLog.Error(typeof(SentryAppender), "[" + Name + "] " + ex.Message, ex)
                };
            }

            var    httpExtra = HttpExtra.GetHttpExtra();
            object extra;

            if (httpExtra != null)
            {
                extra = new
                {
                    Environment = new EnvironmentExtra(),
                    Http        = httpExtra
                };
            }
            else
            {
                extra = new
                {
                    Environment = new EnvironmentExtra()
                };
            }

            var tags      = _tagLayouts.ToDictionary(t => t.Name, t => (t.Layout.Format(loggingEvent) ?? "").ToString());
            var exception = loggingEvent.ExceptionObject ?? loggingEvent.MessageObject as Exception;
            var level     = Translate(loggingEvent.Level);

            if (loggingEvent.ExceptionObject != null)
            {
                // We should capture buth the exception and the message passed
                var @event = new SentryEvent(loggingEvent.RenderedMessage)
                {
                    Extra = extra,
                    Level = level,
                    Tags  = tags
                };
                RavenClient.Capture(@event);
            }
            else if (loggingEvent.MessageObject is Exception)
            {
                // We should capture the exception with no custom message
                var @event = new SentryEvent(exception)
                {
                    Extra = extra,
                    Level = level,
                    Tags  = tags
                };
                RavenClient.Capture(@event);
            }
            else
            {
                // Just capture message
                var message = loggingEvent.RenderedMessage;

                if (message != null)
                {
                    var @event = new SentryEvent(loggingEvent.RenderedMessage)
                    {
                        Extra = extra,
                        Level = level,
                        Tags  = tags
                    };
                    RavenClient.Capture(@event);
                }
            }
        }
Esempio n. 34
0
        /// <inheritdoc/>
        protected override void Append(LoggingEvent loggingEvent)
        {
            var entries = new[] { BuildLogEntry(loggingEvent) };

            Write(entries);
        }
 /// <summary>
 /// Get the fully qualified string data
 /// </summary>
 /// <param name="loggingEvent">the event being logged</param>
 /// <returns>the fully qualified name</returns>
 /// <remarks>
 /// <para>
 /// Overridden by subclasses to get the fully qualified name before the
 /// precision is applied to it.
 /// </para>
 /// <para>
 /// Return the fully qualified <c>'.'</c> (dot/period) separated string.
 /// </para>
 /// </remarks>
 abstract protected string GetFullyQualifiedName(LoggingEvent loggingEvent);
Esempio n. 36
0
 protected override string GetFullyQualifiedName(LoggingEvent loggingEvent)
 {
     return(loggingEvent.MessageObject.ToString());
 }
Esempio n. 37
0
 /// <summary>
 /// Gets the fully qualified name of the logger
 /// </summary>
 /// <param name="loggingEvent">the event being logged</param>
 /// <returns>The fully qualified logger name</returns>
 /// <remarks>
 /// <para>
 /// Returns the <see cref="LoggingEvent.LoggerName"/> of the <paramref name="loggingEvent"/>.
 /// </para>
 /// </remarks>
 override protected string GetFullyQualifiedName(LoggingEvent loggingEvent)
 {
     return(loggingEvent.LoggerName);
 }
Esempio n. 38
0
 /// <summary>
 /// Lookup the property for <see cref="Key"/>
 /// </summary>
 /// <param name="loggingEvent">The event to format</param>
 /// <returns>returns property value</returns>
 /// <remarks>
 /// <para>
 /// Looks up and returns the object value of the property
 /// named <see cref="Key"/>. If there is no property defined
 /// with than name then <c>null</c> will be returned.
 /// </para>
 /// </remarks>
 public virtual object Format(LoggingEvent loggingEvent)
 {
     return(loggingEvent.LookupProperty(m_key));
 }
 protected override void Append(LoggingEvent loggingEvent)
 {
     loggingEvent.Fix = FixFlags.LocationInfo;
     LastLoggingEvent = loggingEvent;
 }
        protected override void Append(LoggingEvent loggingEvent)
        {
            var message = this.RenderLoggingEvent(loggingEvent);

            _twilio.SendSmsMessage(From, To, message);
        }
Esempio n. 41
0
 protected override void HttpConvert(TextWriter writer, LoggingEvent loggingEvent, HttpContext currentContext)
 {
     writer.Write(currentContext.Request.UrlReferrer);
 }
Esempio n. 42
0
        private LogEntrySourceLocation BuildLogEntryLocation(LoggingEvent loggingEvent)
        {
            string file     = null;
            long?  line     = null;
            string function = null;

            if (loggingEvent.LocationInformation?.FileName != null)
            {
                file = loggingEvent.LocationInformation?.FileName;
            }
            long lineNumber;

            if (long.TryParse(loggingEvent.LocationInformation?.LineNumber, out lineNumber))
            {
                line = lineNumber;
            }
            string function0    = null;
            string fullTypeName = loggingEvent.LocationInformation?.ClassName;

            if (fullTypeName != null)
            {
                var type = _typeCache.GetOrAdd(fullTypeName, () =>
                {
                    try
                    {
                        return(AppDomain.CurrentDomain.GetAssemblies()
                               .SelectMany(a => a.GetTypes())
                               .FirstOrDefault(t => t.FullName == fullTypeName));
                    }
                    catch
                    {
                        // Ignore exceptions. This is best-effort only, and expected to fail in some situations.
                        // Returning null caches the failure.
                        return(null);
                    }
                });
                if (type != null)
                {
                    function0 = type.AssemblyQualifiedName;
                }
            }
            string function1 = loggingEvent.LocationInformation?.MethodName;

            if (function0 != null || function1 != null)
            {
                function = $"[{function0 ?? ""}].{function1 ?? ""}";
            }
            if (file != null || line != null || function != null)
            {
                var sourceLocation = new LogEntrySourceLocation();
                if (file != null)
                {
                    sourceLocation.File = file;
                }
                if (line != null)
                {
                    sourceLocation.Line = line.Value;
                }
                if (function != null)
                {
                    // Format of "function" is:
                    // "[<assembly-qualified type name>].<method name>"
                    // E.g. "[Google.Cloud.Logging.Log4Net.Tests.Log4NetTest, Google.Cloud.Logging.Log4Net.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=185c282632e132a0].LogInfo"
                    sourceLocation.Function = function;
                }
                return(sourceLocation);
            }
            return(null);
        }
 public void Format(TextWriter writer, LoggingEvent loggingEvent)
 {
     InnerLayout.Format(writer, loggingEvent);
 }
Esempio n. 44
0
 protected override void Append(LoggingEvent loggingEvent)
 {
     Logged?.Invoke(loggingEvent);
 }
Esempio n. 45
0
 /// <summary>
 /// Convert the pattern to the rendered message
 /// </summary>
 /// <param name="writer"><see cref="T:System.IO.TextWriter" /> that will receive the formatted result.</param>
 /// <param name="loggingEvent">the event being logged</param>
 protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
 {
     writer.Write(loggingEvent.UserName);
 }
 public AzureLoggingEventEntity(LoggingEvent e, PartitionKeyTypeEnum partitionKeyType, string message, int sequenceNumber) : this(e, partitionKeyType)
 {
     Message        = message;
     SequenceNumber = sequenceNumber;
 }
        /* Example log4j schema event
         *
         * <log4j:event logger="first logger" level="ERROR" thread="Thread-3" timestamp="1051494121460">
         * <log4j:message><![CDATA[errormsg 3]]></log4j:message>
         * <log4j:NDC><![CDATA[third]]></log4j:NDC>
         * <log4j:MDC>
         * <log4j:data name="some string" value="some valuethird"/>
         * </log4j:MDC>
         * <log4j:throwable><![CDATA[java.lang.Exception: someexception-third
         * at org.apache.log4j.chainsaw.Generator.run(Generator.java:94)
         * ]]></log4j:throwable>
         * <log4j:locationInfo class="org.apache.log4j.chainsaw.Generator"
         * method="run" file="Generator.java" line="94"/>
         * <log4j:properties>
         * <log4j:data name="log4jmachinename" value="windows"/>
         * <log4j:data name="log4japp" value="udp-generator"/>
         * </log4j:properties>
         * </log4j:event>
         *
         */

        /* Since log4j 1.3 the log4j:MDC has been combined into the log4j:properties element */

        /// <summary>
        /// Actually do the writing of the xml
        /// </summary>
        /// <param name="writer">the writer to use</param>
        /// <param name="loggingEvent">the event to write</param>
        /// <remarks>
        /// <para>
        /// Generate XML that is compatible with the log4j schema.
        /// </para>
        /// </remarks>
        override protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent)
        {
            // Translate logging events for log4j

            // Translate hostname property
            if (loggingEvent.LookupProperty(LoggingEvent.HostNameProperty) != null &&
                loggingEvent.LookupProperty("log4jmachinename") == null)
            {
                loggingEvent.GetProperties()["log4jmachinename"] = loggingEvent.LookupProperty(LoggingEvent.HostNameProperty);
            }

            // translate appdomain name
            if (loggingEvent.LookupProperty("log4japp") == null &&
                loggingEvent.Domain != null &&
                loggingEvent.Domain.Length > 0)
            {
                loggingEvent.GetProperties()["log4japp"] = loggingEvent.Domain;
            }

            // translate identity name
            if (loggingEvent.Identity != null &&
                loggingEvent.Identity.Length > 0 &&
                loggingEvent.LookupProperty(LoggingEvent.IdentityProperty) == null)
            {
                loggingEvent.GetProperties()[LoggingEvent.IdentityProperty] = loggingEvent.Identity;
            }

            // translate user name
            if (loggingEvent.UserName != null &&
                loggingEvent.UserName.Length > 0 &&
                loggingEvent.LookupProperty(LoggingEvent.UserNameProperty) == null)
            {
                loggingEvent.GetProperties()[LoggingEvent.UserNameProperty] = loggingEvent.UserName;
            }

            // Write the start element
            writer.WriteStartElement("log4j:event");
            writer.WriteAttributeString("logger", loggingEvent.LoggerName);

            // Calculate the timestamp as the number of milliseconds since january 1970
            //
            // We must convert the TimeStamp to UTC before performing any mathematical
            // operations. This allows use to take into account discontinuities
            // caused by daylight savings time transitions.
            TimeSpan timeSince1970 = loggingEvent.TimeStamp.ToUniversalTime() - s_date1970;

            writer.WriteAttributeString("timestamp", XmlConvert.ToString((long)timeSince1970.TotalMilliseconds));
            writer.WriteAttributeString("level", loggingEvent.Level.DisplayName);
            writer.WriteAttributeString("thread", loggingEvent.ThreadName);

            // Append the message text
            writer.WriteStartElement("log4j:message");
            Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement);
            writer.WriteEndElement();

            object ndcObj = loggingEvent.LookupProperty("NDC");

            if (ndcObj != null)
            {
                string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(ndcObj);

                if (valueStr != null && valueStr.Length > 0)
                {
                    // Append the NDC text
                    writer.WriteStartElement("log4j:NDC");
                    Transform.WriteEscapedXmlString(writer, valueStr, this.InvalidCharReplacement);
                    writer.WriteEndElement();
                }
            }

            // Append the properties text
            PropertiesDictionary properties = loggingEvent.GetProperties();

            if (properties.Count > 0)
            {
                writer.WriteStartElement("log4j:properties");
                foreach (System.Collections.DictionaryEntry entry in properties)
                {
                    writer.WriteStartElement("log4j:data");
                    writer.WriteAttributeString("name", (string)entry.Key);

                    // Use an ObjectRenderer to convert the object to a string
                    string valueStr = loggingEvent.Repository.RendererMap.FindAndRender(entry.Value);
                    writer.WriteAttributeString("value", valueStr);

                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }

            string exceptionStr = loggingEvent.GetExceptionString();

            if (exceptionStr != null && exceptionStr.Length > 0)
            {
                // Append the stack trace line
                writer.WriteStartElement("log4j:throwable");
                Transform.WriteEscapedXmlString(writer, exceptionStr, this.InvalidCharReplacement);
                writer.WriteEndElement();
            }

            if (LocationInfo)
            {
                LocationInfo locationInfo = loggingEvent.LocationInformation;

                writer.WriteStartElement("log4j:locationInfo");
                writer.WriteAttributeString("class", locationInfo.ClassName);
                writer.WriteAttributeString("method", locationInfo.MethodName);
                writer.WriteAttributeString("file", locationInfo.FileName);
                writer.WriteAttributeString("line", locationInfo.LineNumber);
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
Esempio n. 48
0
 protected override void Append(LoggingEvent loggingEvent)
 {
     this.concurrentQueue_0.Enqueue(loggingEvent);
 }
Esempio n. 49
0
        protected override void Append(LoggingEvent loggingEvent)
        {
            var message = RenderLoggingEvent(loggingEvent);

            OnUiLogReceived(new UiLogEventArgs(message));
        }
Esempio n. 50
0
 public void DoAppend(LoggingEvent loggingEvent)
 {
 }
Esempio n. 51
0
 /// <summary>
 /// Write the ThreadName 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="LoggingEvent.ThreadName"/> to the <paramref name="writer" />.
 /// </para>
 /// </remarks>
 override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
 {
     writer.Write(loggingEvent.ThreadName);
 }
Esempio n. 52
0
 protected override void Append(LoggingEvent loggingEvent)
 {
     string  renderedMessage = base.RenderLoggingEvent(loggingEvent);
     ILayout layout          = base.Layout;
     // do something here
 }
Esempio n. 53
0
    protected override void Append(LoggingEvent loggingEvent)
    {
        Action operation = () => { this.RichTextBox.AppendText(RenderLoggingEvent(loggingEvent)); };

        this.RichTextBox.Invoke(operation);
    }
Esempio n. 54
0
 /// <summary>
 /// Log the logEvent through this repository.
 /// </summary>
 /// <param name="logEvent">the event to log</param>
 /// <remarks>
 /// <para>
 /// This method should not normally be used to log.
 /// The <see cref="ILog"/> interface should be used
 /// for routine logging. This interface can be obtained
 /// using the <see cref="zlog4net.LogManager.GetLogger(string)"/> method.
 /// </para>
 /// <para>
 /// The <c>logEvent</c> is delivered to the appropriate logger and
 /// that logger is then responsible for logging the event.
 /// </para>
 /// </remarks>
 abstract public void Log(LoggingEvent logEvent);
Esempio n. 55
0
 public override FilterDecision Decide(LoggingEvent loggingEvent)
 {
     return(FilterDecision.Accept);
 }
 /// <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>
 /// Subclasses should override this method to format
 /// the <see cref="LoggingEvent"/> as XML.
 /// </para>
 /// </remarks>
 abstract protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent);
Esempio n. 57
0
 /// <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>
 /// <returns>the relevant location information</returns>
 protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
 {
     loggingEvent.WriteRenderedMessage(writer);
 }
Esempio n. 58
0
 public SerializableLogEvent(LoggingEvent loggingEvent)
 {
     _loggingEvent = loggingEvent;
 }
Esempio n. 59
0
 public RecordInfo(RecordHeader header, LoggingEvent data)
 {
     Header = header;
     Data   = data;
 }
Esempio n. 60
0
 /// <summary>
 /// Decide if the <see cref="LoggingEvent"/> should be logged through an appender.
 /// </summary>
 /// <param name="loggingEvent">The <see cref="LoggingEvent"/> to decide upon</param>
 /// <returns>The decision of the filter</returns>
 /// <remarks>
 /// <para>
 /// If the decision is <see cref="FilterDecision.Deny"/>, then the event will be
 /// dropped. If the decision is <see cref="FilterDecision.Neutral"/>, then the next
 /// filter, if any, will be invoked. If the decision is <see cref="FilterDecision.Accept"/> then
 /// the event will be logged without consulting with other filters in
 /// the chain.
 /// </para>
 /// <para>
 /// This method is marked <c>abstract</c> and must be implemented
 /// in a subclass.
 /// </para>
 /// </remarks>
 public abstract FilterDecision Decide(LoggingEvent loggingEvent);