Beispiel #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:log4net.Core.LoggingEvent" /> class
 /// using specific data.
 /// </summary>
 /// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
 /// the stack boundary into the logging system for this call.</param>
 /// <param name="repository">The repository this event is logged in.</param>
 /// <param name="data">Data used to initialize the logging event.</param>
 /// <param name="fixedData">The fields in the <paranref name="data" /> struct that have already been fixed.</param>
 /// <remarks>
 /// <para>
 /// This constructor is provided to allow a <see cref="T:log4net.Core.LoggingEvent" />
 /// to be created independently of the log4net framework. This can
 /// be useful if you require a custom serialization scheme.
 /// </para>
 /// <para>
 /// Use the <see cref="M:GetLoggingEventData(FixFlags)" /> method to obtain an
 /// instance of the <see cref="T:log4net.Core.LoggingEventData" /> class.
 /// </para>
 /// <para>
 /// The <paramref name="fixedData" /> parameter should be used to specify which fields in the
 /// <paramref name="data" /> struct have been preset. Fields not specified in the <paramref name="fixedData" />
 /// will be captured from the environment if requested or fixed.
 /// </para>
 /// </remarks>
 public LoggingEvent(Type callerStackBoundaryDeclaringType, ILoggerRepository repository, LoggingEventData data, FixFlags fixedData)
 {
     m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType;
     m_repository = repository;
     m_data       = data;
     m_fixFlags   = fixedData;
 }
Beispiel #2
0
        public void Log(LogLevel logLevel, Exception exception, Type loggingType, bool notifyAdministrator, string stringFormat, params object[] args)
        {
            ParamValidator.AssertIsNotEmpty(stringFormat, "stringFormat");

            try
            {
                LoggingEventData logData = new LoggingEventData()
                                                   {
                                                       Level = TransformToLevel(logLevel),
                                                       ExceptionString = exception != null
                                                                            ? string.Format("{0}|StackTrace: {1}",
                                                                                            exception.Message,
                                                                                            exception.StackTrace)
                                                                            : null,
                                                       ThreadName = loggingType != null
                                                                        ? loggingType.ToString()
                                                                        : null,
                                                       TimeStamp = _clock.Now,
                                                       Message = string.Format(stringFormat, args)
                                                   };

                LoggingEvent logEvent = new LoggingEvent(logData);

                _logger.Logger.Log(logEvent);
            }
            catch
            {
                //// Don't do nothing, logger classes don't have to throw any exceptions.
            }
        }
Beispiel #3
0
        public override IResult Execute(IResult previousResults)
        {
            try
            {
                var eventData = new LoggingEventData
                    {
                        Level = Event.GetAssociatedLevel(),
                        Message = Message,
                        TimeStamp = DateTime.Now
                    };

                if (eventData.Level == null)
                {
                    Log.Warn("Cannot upload log event; Level is null");
                    return new NextResult();
                }

                if (string.IsNullOrWhiteSpace(eventData.Message))
                    eventData.Message = "[no content]";

                var eventEntry = Asynchronous
                    ? new LoggingEvent(eventData)
                    : new BlockingLoggingEvent(eventData);

                Log.Logger.Log(eventEntry);

                return new NextResult();
            }
            catch (Exception e)
            {
                Log.WarnFormat("An exception occurred while attempting to record a log event: {0}", e.Message);
                return new NextResult();
            }
        }
        private static LoggingEvent MakeEvent()
        {
            var loggingEventData = new LoggingEventData
            {
                Domain = "testDomain",
                Identity = "testIdentity",
                Level = Level.Critical,
                LoggerName = "testLoggerName",
                Message = "testMessage",
                ThreadName = "testThreadName",
                TimeStamp = DateTime.UtcNow,
                UserName = "******",
                Properties = new PropertiesDictionary(),
                LocationInfo = new LocationInfo("className", "methodName", "fileName", "lineNumber")
            };

            loggingEventData.Properties["test1"] = DateTime.UtcNow;
            loggingEventData.Properties["Url"] = "http://google.de";
            loggingEventData.Properties["requestId"] = Guid.NewGuid();


            return new LoggingEvent(
                loggingEventData
                );
        }
        private static LoggingEvent GetLoggingEvent()
        {
            LoggingEventData loggingEventData1 = new LoggingEventData();
            loggingEventData1.LoggerName = typeof (PatternParserTests).FullName;
            loggingEventData1.Level = Level.Warn;
            loggingEventData1.Message = "Tw.o.Dots";
            loggingEventData1.Domain = "ReallySimpleApp";
            loggingEventData1.LocationInfo = new LocationInfo(typeof (PatternParserTests).Name, "Main", "Class1.cs", "29");
                //Completely arbitary
            loggingEventData1.ThreadName = Thread.CurrentThread.Name;
            loggingEventData1.TimeStamp = DateTime.Today;
            loggingEventData1.ExceptionString = "Exception occured here";
            loggingEventData1.UserName = "******";
            LoggingEventData loggingEventData = loggingEventData1;

            // LoggingEvents occur at distinct points in time
            LoggingEvent loggingEvent = new LoggingEvent(
                loggingEventData.LocationInfo.GetType(),
                LogManager.CreateRepository(Guid.NewGuid().ToString()),
                loggingEventData.LoggerName,
                loggingEventData.Level,
                loggingEventData.Message,
                new Exception("This is the exception"));
            return loggingEvent;
        }
Beispiel #6
0
        public async Task LogToLocalHost()
        {
            //---------------Set up test pack-------------------

            const string indexName = "splunk4net";
            var service = await CreateLoggedOnSplunkServiceForIndex(indexName);
            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var transmitter = service.Transmitter;
            var someLog = new LoggingEventData()
            {
                Level = Level.Info,
                LoggerName = "SomeClassInSomeApplication",
                Message = "The time now is: " + DateTime.Now.ToString("HH:mm:ss"),
                TimeStamp = DateTime.Now
            };

            var json = JsonConvert.SerializeObject(someLog);

            var result = await transmitter.SendAsync(json, indexName);

            //---------------Test Result -----------------------
            var bytes = int.Parse(result.GetValue("bytes"));
            Assert.AreEqual(bytes, json.Length);
        }
        public void AppendTest()
        {
            var gelfAppender = new TestGelf4NetAppenderWrapper();
            gelfAppender.Layout = new PatternLayout("%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n");
            gelfAppender.Transport = new FakeTransport();
            gelfAppender.ActivateOptions();

            var data = new LoggingEventData
            {
                Domain = this.GetType().Name,
                Level = Level.Debug,
                LoggerName = "Tester",
                Message = "GrayLog4Net!!!",
                TimeStamp = DateTime.Now,
                UserName = "******"
            };

            var logEvent = new LoggingEvent(data);
            gelfAppender.TestAppend(logEvent);

            var fakeTransport = gelfAppender.Transport as FakeTransport;
            if (fakeTransport != null)
            {
                var outputType = new { level = 0, short_message = ""};
                var output = JsonConvert.DeserializeAnonymousType(fakeTransport.SentMessage, outputType);

                Assert.IsTrue(output.short_message.Contains("GrayLog4Net!!!"));
                Assert.AreEqual(Level.Debug, SeverityLevelConverter.SysLogLevelSeverityToLogLevelSeverity(output.level));
            }
        }
Beispiel #8
0
        public void WriteCrap(string message)
        {
            var data = new log4net.Core.LoggingEventData();

            data.Message = message;
            data.Level   = Level.Error;
            Append(new log4net.Core.LoggingEvent(data));
        }
Beispiel #9
0
 public LoggingEvent(Type callerStackBoundaryDeclaringType, ILoggerRepository repository, LoggingEventData data, FixFlags fixedData)
 {
     this.m_cacheUpdatable = true;
     this.m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType;
     this.m_repository = repository;
     this.m_data       = data;
     this.m_fixFlags   = fixedData;
 }
Beispiel #10
0
        public LogEntry()
        {
            this.Data = new LoggingEventData();
            Data.ExceptionString = string.Empty;
            Data.Domain = string.Empty;
            Data.UserName = string.Empty;
            Data.Message = string.Empty;
            Data.ThreadName = string.Empty;

            Data.TimeStamp = new DateTime(1970, 1, 1, 0, 0, 0, 0);
        }
Beispiel #11
0
 public LoggingData(log4net.Core.LoggingEventData data)
 {
     this.identity        = data.Identity;
     this.loggerName      = data.LoggerName;
     this.level           = LogLevel.Normal;
     this.message         = data.Message;
     this.threadName      = data.ThreadName;
     this.timeStampTicks  = data.TimeStamp.Ticks;
     this.locationInfo    = new LocationInfo(data.LocationInfo);
     this.exceptionString = data.ExceptionString;
     this.domain          = data.Domain;
     this.level           = ConvertLevel(data.Level.Value);
     this.timeStamp       = new DateTime(this.timeStampTicks);
     this.userName        = GetDeviceName();
 }
Beispiel #12
0
        private LoggingEvent Convert(LogObject log)
        {
            LoggingEventData led = new LoggingEventData()
            {
                LoggerName = log.Namespace,
                TimeStamp = log.Timestamp,
                ExceptionString = log.Exception,
                Message = log.Message,
                UserName = log.UserName,
                Level = ToLog4netLevel(log.Level),
                Properties = GetLog4netProperties(log)
            };

            return new LoggingEvent(led);
        }
Beispiel #13
0
        public void Log_exception_string_without_object()
        {
            var eventData = new LoggingEventData()
            {
                LoggerName = "logger",
                Message = "the message",
                ExceptionString = "Exception string",
            };
            var loggingEvent = new LoggingEvent(eventData);

            var logEvent = _logEventFactory.CreateLogEvent(loggingEvent);
            Assert.AreEqual(loggingEvent.RenderedMessage, logEvent["Message"]);
            Assert.AreEqual(loggingEvent.GetExceptionString(), logEvent["Exception"]);
            Assert.IsFalse(logEvent.ContainsKey("ExceptionObject"));
        }
        public void Format_FailedJsonSerializationProperty_ShouldNotObstructOtherPropertiesFromBeingLogged()
        {
            var layout = new PropertyBagLayout();
            var loggingEventData = new LoggingEventData {Properties = new PropertiesDictionary()};
            loggingEventData.Properties["AcceptableProperty"] = "Just some data to be logged";
            loggingEventData.Properties["AnonymousObjectToString"] = new
            {
                FirstProperty = "Some data.",
                SecondProperty = 123,
            }.ToString();
            var loggingEvent = new LoggingEvent(loggingEventData);
            var output = layout.Format(loggingEvent);

            output.GetType().Should().Be(typeof (BsonDocument));
            ((BsonDocument) output).Names.Should().Contain("AcceptableProperty");
        }
Beispiel #15
0
		/// <summary>
		/// Build a basic <see cref="LoggingEventData"/> object with some default values.
		/// </summary>
		/// <returns>A useful LoggingEventData object</returns>
		private LoggingEventData CreateBaseEvent()
		{
			LoggingEventData ed = new LoggingEventData();
			ed.Domain = "Tests";
			ed.ExceptionString = "";
			ed.Identity = "TestRunner";
			ed.Level = Level.Info;
			ed.LocationInfo = new LocationInfo(GetType());
			ed.LoggerName = "TestLogger";
			ed.Message = "Test message";
			ed.ThreadName = "TestThread";
			ed.TimeStamp = DateTime.Today;
			ed.UserName = "******";
			ed.Properties = new PropertiesDictionary();

			return ed;
		}
Beispiel #16
0
		private LoggingEvent CreateLoggingEvent(Level level, string message, string category, object data, Exception exception)
		{
			LoggingEventData eventData = new LoggingEventData();
			eventData.LoggerName = this.Logger.Name;
			eventData.Level = level;
			eventData.TimeStamp = DateTime.Now;

			if (exception != null)
			{
				if (String.IsNullOrEmpty(message))
				{
					eventData.Message = data == null ? exception.Message : exception.Message + "\r\n相关数据: " + XMS.Core.Formatter.PlainObjectFormatter.Simplified.Format(data);
					eventData.ExceptionString = exception.GetFriendlyStackTrace();
				}
				else
				{
					eventData.Message = data == null ? message : message + "\r\n相关数据: " + XMS.Core.Formatter.PlainObjectFormatter.Simplified.Format(data);
					eventData.ExceptionString = exception.GetFriendlyToString();
				}
			}
			else
			{
				eventData.Message = data == null ? message : message + "\r\n相关数据: " + XMS.Core.Formatter.PlainObjectFormatter.Simplified.Format(data);
			}

			LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, this.Logger.Repository, eventData, FixFlags.None);
			
			// LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, this.Logger.Repository, this.Logger.Name, level, message, exception);
			
			//// 应用相关的信息
			//loggingEvent.Properties["RunMode"] = RunContext.Current.RunMode.ToString().ToLower();
			//loggingEvent.Properties["AppName"] = Container.ConfigService.AppName;
			//loggingEvent.Properties["AppVersion"] = Container.ConfigService.AppVersion;

			// 日志类别
			loggingEvent.Properties["Category"] = String.IsNullOrEmpty(category) ? "default" : category;

			// 访问者信息
			loggingEvent.Properties["UserIP"] = SecurityContext.Current.UserIP;
			loggingEvent.Properties["UserId"] = SecurityContext.Current.User.Identity.UserId;
			loggingEvent.Properties["UserName"] = SecurityContext.Current.User.Identity.Name;


			return loggingEvent;
		}
        public void AppendTest()
        {
            var gelfAppender = new Gelf4NetAppender();
            //def logEvent = new LoggingEvent(this.GetType().Name, new Category('catName'), System.currentTimeMillis(), Priority.WARN, "Some Short Message", new Exception('Exception Message'))
            var data = new LoggingEventData
            {
                Domain = this.GetType().Name,
                Level = Level.Debug,
                LoggerName = "Tester",
                Message = "GrayLog4Net!!!",
                TimeStamp = DateTime.Now,
                UserName = "******"
            };

            var logEvent = new LoggingEvent(data);
            gelfAppender.GrayLogServerHost = "public-graylog2.taulia.com";
            gelfAppender.TestAppend(logEvent);
        }
Beispiel #18
0
        private long GetLog4NetTimestamp(DateTime dateTime)
        {
            var logXmlBuilder = new StringBuilder ();
            using (var writer = new StringWriter (logXmlBuilder))
            {
                var layout = new XmlLayoutSchemaLog4j ();
                var appender = new TextWriterAppender
                {
                    ImmediateFlush = true,
                    Layout = layout,
                    Writer = writer
                };
                var repository = LogManager.GetRepository (Assembly.GetCallingAssembly ());

                var eventData = new LoggingEventData
                {
                    LoggerName = "TestLogger",
                    TimeStamp = dateTime,
                    Level = log4net.Core.Level.Debug,
                    ThreadName = "TestThread",
                    Message = "Test message."
                };
                var @event = new LoggingEvent (typeof (TimestampTests), repository, eventData);
                appender.DoAppend (@event);

                writer.Flush ();

                appender.Close ();
            }

            var logXml = logXmlBuilder.ToString ();

            const string timestampStartMarker = "timestamp=\"";
            var timestampStart = logXml.IndexOf (timestampStartMarker) + timestampStartMarker.Length;
            Assume.That (timestampStart, Is.GreaterThanOrEqualTo (0));
            var timestampEnd = logXml.IndexOf ('"', timestampStart);
            Assume.That (timestampEnd, Is.GreaterThanOrEqualTo (0));

            var timestampString = logXml.Substring (timestampStart, timestampEnd - timestampStart);

            var timestamp = Int64.Parse (timestampString);

            return timestamp;
        }
        public void BeforeAll()
        {
            var notificationService = MockRepository.GenerateStub<AmazonSimpleNotificationService>();
            notificationService
                .Stub(s => s.Publish(Arg<PublishRequest>.Is.Anything))
                .WhenCalled(p => SentRequests.Add((PublishRequest) p.Arguments[0]));

            var appender = new AmazonSimpleNotificationServiceAppender()
                               {
                                   NotificationService = notificationService,
                                   Layout = new PatternLayout("%message")
                               };

            LogMessage = "Testing 123";
            var loggingEventData = new LoggingEventData {Message = this.LogMessage};
            var loggingEvent = new LoggingEvent(loggingEventData);

            appender.DoAppend(loggingEvent);
        }
        public void BuildFromLoggingEvent_CanAcessThreadContextProperties()
        {
            var data = new LoggingEventData
            {
                Domain = this.GetType().Name,
                Level = Level.Debug,
                LoggerName = "Tester",
                Message = "GrayLog4Net!!!",
                TimeStamp = DateTime.Now,
                UserName = "******"
            };

            const string threadContextString = "IAmAThreadContextValue";
            ThreadContext.Properties["somekey"] = threadContextString;

            var logEvent = new LoggingEvent(data);
            var builder = new GelfJsonBuilder();
            var result = builder.BuildFromLoggingEvent("message", logEvent, "hostname", "facility", false, null);

            Assert.True(result.Contains(threadContextString));
        }
        public void AppendTestChunkMessage()
        {
            var gelfAppender = new Gelf4NetAppender();
            //def logEvent = new LoggingEvent(this.GetType().Name, new Category('catName'), System.currentTimeMillis(), Priority.WARN, "Some Short Message", new Exception('Exception Message'))
            var data = new LoggingEventData
            {
                Domain = this.GetType().Name,
                Level = Level.Debug,
                LoggerName = "Big Tester",
                Message = LoremIpsum.Text,
                TimeStamp = DateTime.Now,
                UserName = "******"
            };

            var logEvent = new LoggingEvent(data);
            gelfAppender.GrayLogServerHost = graylogServerHost;
            gelfAppender.MaxChunkSize = 50;
            gelfAppender.AdditionalFields = "nombre:pedro,apellido:jimenez";
            logEvent.Properties["customProperty"] = "My Custom Property Woho";

            gelfAppender.TestAppend(logEvent);
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            Console.WriteLine("Write a sentence, q to quit");

            var text = Console.ReadLine();

            while (text != "q")
            {
                var loggingEventDataCC = new LoggingEventData
                {
                    Message = text,
                    LoggerName = "Test.Logger.Class",
                    Level = Level.Debug,
                    TimeStamp = DateTime.Now
                };
                var loggingEventCC = new LoggingEvent(loggingEventDataCC);

                var loggingEventData = new LoggingEventData
                {
                    Message = JsonConvert.SerializeObject(new { Message = text, Open = DateTime.UtcNow }),
                    LoggerName = "Test.Logger.Class",
                    Level = Level.Debug,
                    TimeStamp = DateTime.Now
                };
                var loggingEvent = new LoggingEvent(loggingEventData);

                var gelfCC = LogManager.GetRepository().GetAppenders().FirstOrDefault(x => x.Name == "GelfUdpAppenderCC");
                var gelf = LogManager.GetRepository().GetAppenders().FirstOrDefault(x => x.Name == "GelfUdpAppender");

                gelf.DoAppend(loggingEvent);
                gelfCC.DoAppend(loggingEventCC);

                text = Console.ReadLine();

                Console.WriteLine("Sent");
            }
        }
        public void AppendTestChunkMessage()
        {
            var gelfAppender = new TestGelf4NetAppenderWrapper();
            gelfAppender.Layout = new PatternLayout("%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n");
            gelfAppender.Transport = BuildTestUdpTransport();
            gelfAppender.MaxChunkSize = 50;
            gelfAppender.AdditionalFields = "nombre:pedro,apellido:jimenez";
            gelfAppender.ActivateOptions();

            var data = new LoggingEventData
            {
                Domain = this.GetType().Name,
                Level = Level.Debug,
                LoggerName = "Big Tester",
                Message = LoremIpsum.Text,
                TimeStamp = DateTime.Now,
                UserName = "******"
            };

            var logEvent = new LoggingEvent(data);
            logEvent.Properties["customProperty"] = "My Custom Property Woho";

            gelfAppender.TestAppend(logEvent);
        }
        public void Log_exception_string_without_object()
        {
            var exceptionString = "Exception string";
            var eventData = new LoggingEventData
            {
                LoggerName = _log.Logger.Name,
                ExceptionString = exceptionString,
                Level = Level.Error,
                Message = "loggingtest",
                TimeStamp = DateTime.Now,
                Domain = "Domain",
            };
            var loggingEvent = new LoggingEvent(eventData);

            _log.Logger.Repository.Log(loggingEvent);

            Client.Refresh();

            var searchResults = Client.Search<JObject>(s => s.AllTypes().Query(q => q.Term("Message", "loggingtest")));

            Assert.AreEqual(1, searchResults.Total);
            var doc = searchResults.Documents.First();
            Assert.AreEqual(exceptionString, doc["Exception"].ToString());
        }
Beispiel #25
0
 public LoggingDataEventArgs(LoggingEventData data)
 {
     Data = data;
 }
Beispiel #26
0
		/// <summary>
		/// Initializes a new instance of the <see cref="LoggingEvent" /> class 
		/// using specific data.
		/// </summary>
		/// <param name="data">Data used to initialize the logging event.</param>
		/// <remarks>
		/// <para>
		/// This constructor is provided to allow a <see cref="LoggingEvent" />
		/// to be created independently of the log4net framework. This can
		/// be useful if you require a custom serialization scheme.
		/// </para>
		/// <para>
		/// Use the <see cref="GetLoggingEventData(FixFlags)"/> method to obtain an 
		/// instance of the <see cref="LoggingEventData"/> class.
		/// </para>
		/// <para>
		/// This constructor sets this objects <see cref="Fix"/> flags to <see cref="FixFlags.All"/>,
		/// this assumes that all the data relating to this event is passed in via the <paramref name="data"/>
		/// parameter and no other data should be captured from the environment.
		/// </para>
		/// </remarks>
		public LoggingEvent(LoggingEventData data) : this(null, null, data)
		{
		}
Beispiel #27
0
		/// <summary>
		/// Initializes a new instance of the <see cref="LoggingEvent" /> class 
		/// using specific data.
		/// </summary>
		/// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
		/// the stack boundary into the logging system for this call.</param>
		/// <param name="repository">The repository this event is logged in.</param>
		/// <param name="data">Data used to initialize the logging event.</param>
		/// <remarks>
		/// <para>
		/// This constructor is provided to allow a <see cref="LoggingEvent" />
		/// to be created independently of the log4net framework. This can
		/// be useful if you require a custom serialization scheme.
		/// </para>
		/// <para>
		/// Use the <see cref="GetLoggingEventData(FixFlags)"/> method to obtain an 
		/// instance of the <see cref="LoggingEventData"/> class.
		/// </para>
		/// <para>
		/// This constructor sets this objects <see cref="Fix"/> flags to <see cref="FixFlags.All"/>,
		/// this assumes that all the data relating to this event is passed in via the <paramref name="data"/>
		/// parameter and no other data should be captured from the environment.
		/// </para>
		/// </remarks>
		public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, LoggingEventData data) : this(callerStackBoundaryDeclaringType, repository, data, FixFlags.All)
		{
		}
Beispiel #28
0
		/// <summary>
		/// Initializes a new instance of the <see cref="LoggingEvent" /> class 
		/// using specific data.
		/// </summary>
		/// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
		/// the stack boundary into the logging system for this call.</param>
		/// <param name="repository">The repository this event is logged in.</param>
		/// <param name="data">Data used to initialize the logging event.</param>
		/// <param name="fixedData">The fields in the <paranref name="data"/> struct that have already been fixed.</param>
		/// <remarks>
		/// <para>
		/// This constructor is provided to allow a <see cref="LoggingEvent" />
		/// to be created independently of the log4net framework. This can
		/// be useful if you require a custom serialization scheme.
		/// </para>
		/// <para>
		/// Use the <see cref="GetLoggingEventData(FixFlags)"/> method to obtain an 
		/// instance of the <see cref="LoggingEventData"/> class.
		/// </para>
		/// <para>
		/// The <paramref name="fixedData"/> parameter should be used to specify which fields in the
		/// <paramref name="data"/> struct have been preset. Fields not specified in the <paramref name="fixedData"/>
		/// will be captured from the environment if requested or fixed.
		/// </para>
		/// </remarks>
		public LoggingEvent(Type callerStackBoundaryDeclaringType, log4net.Repository.ILoggerRepository repository, LoggingEventData data, FixFlags fixedData) 
		{
			m_callerStackBoundaryDeclaringType = callerStackBoundaryDeclaringType;
			m_repository = repository;

			m_data = data;
			m_fixFlags = fixedData;
		}
Beispiel #29
0
        public async Task LogAndTestThatItHappened()
        {
            //---------------Set up test pack-------------------
            var index = "splunk4net";
            var loggingService = await CreateLoggedOnSplunkServiceForIndex(index);
            var queryService = await CreateLoggedOnSplunkServiceForIndex(index);

            var searchFor = Guid.NewGuid().ToString();

            var transmitter = loggingService.Transmitter;
            var someLog = new LoggingEventData()
            {
                Level = Level.Info,
                LoggerName = searchFor,
                Message = "The time now is: " + DateTime.Now.ToString("HH:mm:ss"),
                TimeStamp = DateTime.Now
            };

            var json = JsonConvert.SerializeObject(someLog);
            var result = await transmitter.SendAsync(json, index);
            Assert.IsNotNull(result);

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var searchString = $"search index=\"{index}\" LoggerName=\"{searchFor}\"";
            var job = await queryService.Jobs.CreateAsync(searchString);
            using (var stream = await job.GetSearchResultsAsync())
            {
                var allResults = stream.SearchResults().ToArray();
                Assert.AreEqual(1, allResults.Length);
                var log = allResults.First();
                Console.WriteLine(log.SegmentedRaw.Value);
            }

            //---------------Test Result -----------------------
        }
Beispiel #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:log4net.Core.LoggingEvent" /> class
 /// using specific data.
 /// </summary>
 /// <param name="callerStackBoundaryDeclaringType">The declaring type of the method that is
 /// the stack boundary into the logging system for this call.</param>
 /// <param name="repository">The repository this event is logged in.</param>
 /// <param name="data">Data used to initialize the logging event.</param>
 /// <remarks>
 /// <para>
 /// This constructor is provided to allow a <see cref="T:log4net.Core.LoggingEvent" />
 /// to be created independently of the log4net framework. This can
 /// be useful if you require a custom serialization scheme.
 /// </para>
 /// <para>
 /// Use the <see cref="M:GetLoggingEventData(FixFlags)" /> method to obtain an
 /// instance of the <see cref="T:log4net.Core.LoggingEventData" /> class.
 /// </para>
 /// <para>
 /// This constructor sets this objects <see cref="P:log4net.Core.LoggingEvent.Fix" /> flags to <see cref="F:log4net.Core.FixFlags.All" />,
 /// this assumes that all the data relating to this event is passed in via the <paramref name="data" />
 /// parameter and no other data should be captured from the environment.
 /// </para>
 /// </remarks>
 public LoggingEvent(Type callerStackBoundaryDeclaringType, ILoggerRepository repository, LoggingEventData data)
     : this(callerStackBoundaryDeclaringType, repository, data, FixFlags.All)
 {
 }
Beispiel #31
0
 public LoggingEvent(Type a, ILoggerRepository b, LoggingEventData c, FixFlags d)
 {
 }
 /// <summary>
 /// save data to file
 /// </summary>
 /// <param name="data"></param>
 private void SaveToFile(String data)
 {
     if (null != m_BackupAppender)
     {
         try
         {
             LoggingEventData e = new LoggingEventData()
             {
                 TimeStamp = DateTime.Now,
                 Message = data,
             };
             m_BackupAppender.DoAppend(new LoggingEvent(e));
         }
         catch (System.Exception ex)
         {
             throw new Exception(String.Format("保存数据到备份文件失败. {0}", ex));
         }
     }
 }
 public void TestInitialize()
 {
     appender = new RollingSqlCEAppender();
     databaseFile = "test.log4net";
     appender.FileNameFormat = databaseFile;
     File.Delete(databaseFile);
     appender.ActivateOptions();
     LoggingEventData loggingEventData = new LoggingEventData();
     loggingEventData.Level = Level.Error;
     loggingEventData.Message = "foo";
     loggingEventData.TimeStamp = DateTime.Now;
     loggingEvent = new LoggingEvent(loggingEventData);
 }
Beispiel #34
0
 public LoggingEvent(Type a, ILoggerRepository b, LoggingEventData c)
 {
 }
 public BlockingLoggingEvent(LoggingEventData data)
     : base(data)
 {
 }
Beispiel #36
0
        private static LoggingEventData CreateLogData(string message)
        {
            StackFrame frame = new StackFrame(2);
            var method = frame.GetMethod();
            var type = method.DeclaringType;

            var logData = new LoggingEventData();
            logData.TimeStamp = DateTime.UtcNow;
            logData.ThreadName = Thread.CurrentThread.Name;
            logData.Message = message;
            logData.LoggerName = type.Name;
            logData.Properties = new log4net.Util.PropertiesDictionary();
            logData.Properties["correlationId"] = null;
            logData.Properties["value"] = null;
            logData.Properties["unitType"] = null;
            logData.Properties["exceptionMessage"] = null;

            return logData;
        }
Beispiel #37
0
        private void SetEvent(LoggingEventData logData, Exception exception = null)
        {
            var logEvent = new LoggingEvent(logData);

            ((log4net.Core.LoggerWrapperImpl)(log4NetLogger)).Logger.Log(logEvent);
        }
Beispiel #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:log4net.Core.LoggingEvent" /> class
 /// using specific data.
 /// </summary>
 /// <param name="data">Data used to initialize the logging event.</param>
 /// <remarks>
 /// <para>
 /// This constructor is provided to allow a <see cref="T:log4net.Core.LoggingEvent" />
 /// to be created independently of the log4net framework. This can
 /// be useful if you require a custom serialization scheme.
 /// </para>
 /// <para>
 /// Use the <see cref="M:GetLoggingEventData(FixFlags)" /> method to obtain an
 /// instance of the <see cref="T:log4net.Core.LoggingEventData" /> class.
 /// </para>
 /// <para>
 /// This constructor sets this objects <see cref="P:log4net.Core.LoggingEvent.Fix" /> flags to <see cref="F:log4net.Core.FixFlags.All" />,
 /// this assumes that all the data relating to this event is passed in via the <paramref name="data" />
 /// parameter and no other data should be captured from the environment.
 /// </para>
 /// </remarks>
 public LoggingEvent(LoggingEventData data)
     : this(null, null, data)
 {
 }