/// <summary>
            /// Processes the log messages.
            /// </summary>
            /// <param name="events">The events to process.</param>
            public void ProcessLogMessages(NLogEvents events)
            {
                var baseTimeUtc = new DateTime(events.BaseTimeUtc, DateTimeKind.Utc);
                var logEvents   = new LogEventInfo[events.Events.Length];

                // convert transport representation of log events into workable LogEventInfo[]
                for (int j = 0; j < events.Events.Length; ++j)
                {
                    var      ev         = events.Events[j];
                    LogLevel level      = LogLevel.FromOrdinal(ev.LevelOrdinal);
                    string   loggerName = events.Strings[ev.LoggerOrdinal];

                    var logEventInfo = new LogEventInfo();
                    logEventInfo.Level      = level;
                    logEventInfo.LoggerName = loggerName;
                    logEventInfo.TimeStamp  = baseTimeUtc.AddTicks(ev.TimeDelta);
                    logEventInfo.Message    = events.Strings[ev.MessageOrdinal];
                    logEventInfo.Properties.Add("ClientName", events.ClientName);
                    for (int i = 0; i < events.LayoutNames.Count; ++i)
                    {
                        logEventInfo.Properties.Add(events.LayoutNames[i], events.Strings[ev.ValueIndexes[i]]);
                    }

                    logEvents[j] = logEventInfo;
                }

                this.ProcessLogMessages(logEvents);
            }
        public void TranslateEventAndBack(string message)
        {
            // Arrange
            var service = new LogReceiverWebServiceTarget {
                IncludeEventProperties = true
            };

            var logEvent = new LogEventInfo(LogLevel.Debug, "logger1", message);

            var nLogEvents = new NLogEvents
            {
                Strings     = new StringCollection(),
                LayoutNames = new StringCollection(),
                BaseTimeUtc = DateTime.UtcNow.Ticks,
                ClientName  = "client1",
                Events      = new NLogEvent[0]
            };
            var dict2 = new Dictionary <string, int>();

            // Act
            var translateEvent = service.TranslateEvent(logEvent, nLogEvents, dict2);
            var result         = translateEvent.ToEventInfo(nLogEvents, "");

            // Assert
            Assert.Equal("logger1", result.LoggerName);
            Assert.Equal(message, result.Message);
        }
        private NLogEvents TranslateLogEvents(AsyncLogEventInfo[] logEvents)
        {
            string clientID = string.Empty;

            if (this.ClientId != null)
            {
                clientID = this.ClientId.Render(logEvents[0].LogEvent);
            }

            var networkLogEvents = new NLogEvents
            {
                ClientName  = clientID,
                LayoutNames = new StringCollection(),
                Strings     = new StringCollection(),
                BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks
            };

            var stringTable = new Dictionary <string, int>();

            for (int i = 0; i < this.Parameters.Count; ++i)
            {
                networkLogEvents.LayoutNames.Add(this.Parameters[i].Name);
            }

            networkLogEvents.Events = new NLogEvent[logEvents.Length];
            for (int i = 0; i < logEvents.Length; ++i)
            {
                networkLogEvents.Events[i] = this.TranslateEvent(logEvents[i].LogEvent, networkLogEvents, stringTable);
            }

            return(networkLogEvents);
        }
            /// <summary>
            /// Processes the log messages.
            /// </summary>
            /// <param name="events">The events to process.</param>
            public void ProcessLogMessages(NLogEvents events)
            {
                var baseTimeUtc = new DateTime(events.BaseTimeUtc, DateTimeKind.Utc);
                var logEvents = new LogEventInfo[events.Events.Length];

                // convert transport representation of log events into workable LogEventInfo[]
                for (int j = 0; j < events.Events.Length; ++j)
                {
                var ev = events.Events[j];
                LogLevel level = LogLevel.FromOrdinal(ev.LevelOrdinal);
                string loggerName = events.Strings[ev.LoggerOrdinal];

                var logEventInfo = new LogEventInfo();
                logEventInfo.Level = level;
                logEventInfo.LoggerName = loggerName;
                logEventInfo.TimeStamp = baseTimeUtc.AddTicks(ev.TimeDelta);
                logEventInfo.Message = events.Strings[ev.MessageOrdinal];
                logEventInfo.Properties.Add("ClientName", events.ClientName);
                for (int i = 0; i < events.LayoutNames.Count; ++i)
                {
                    logEventInfo.Properties.Add(events.LayoutNames[i], events.Strings[ev.ValueIndexes[i]]);
                }

                logEvents[j] = logEventInfo;
                }

                this.ProcessLogMessages(logEvents);
            }
Beispiel #5
0
        private static List <LogEvent> ExtractLogEvents(NLogEvents events, Batch batch)
        {
            var logEventInfoList = events.ToEventInfo().ToList();
            var timberMillEvents = logEventInfoList.ConvertAll(ei => TimberMillEventFactory(batch, ei));

            return(timberMillEvents);
        }
        private NLogEvents TranslateLogEvents(AsyncLogEventInfo[] logEvents)
        {
            if (logEvents.Length == 0 && !LogManager.ThrowExceptions)
            {
                InternalLogger.Error("LogEvents array is empty, sending empty event...");
                return(new NLogEvents());
            }

            string clientID = string.Empty;

            if (this.ClientId != null)
            {
                clientID = this.ClientId.Render(logEvents[0].LogEvent);
            }

            var networkLogEvents = new NLogEvents
            {
                ClientName  = clientID,
                LayoutNames = new StringCollection(),
                Strings     = new StringCollection(),
                BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks
            };

            var stringTable = new Dictionary <string, int>();

            for (int i = 0; i < this.Parameters.Count; ++i)
            {
                networkLogEvents.LayoutNames.Add(this.Parameters[i].Name);
            }

            if (this.IncludeEventProperties)
            {
                for (int i = 0; i < logEvents.Length; ++i)
                {
                    var ev = logEvents[i].LogEvent;

                    // add all event-level property names in 'LayoutNames' collection.
                    foreach (var prop in ev.Properties)
                    {
                        string propName = prop.Key as string;
                        if (propName != null)
                        {
                            if (!networkLogEvents.LayoutNames.Contains(propName))
                            {
                                networkLogEvents.LayoutNames.Add(propName);
                            }
                        }
                    }
                }
            }

            networkLogEvents.Events = new NLogEvent[logEvents.Length];
            for (int i = 0; i < logEvents.Length; ++i)
            {
                networkLogEvents.Events[i] = this.TranslateEvent(logEvents[i].LogEvent, networkLogEvents, stringTable);
            }

            return(networkLogEvents);
        }
 public IAsyncResult BeginProcessLogMessages(NLogEvents events, AsyncCallback callback, object asyncState)
 {
     return(this.BeginInvoke(
                "ProcessLogMessages",
                new object[] { events },
                callback,
                asyncState));
 }
        public void ToLogEventInfoTest()
        {
            LogManager.Configuration = CreateConfigurationFromString(@"
            <nlog>
                <targets>
                    <target name='debug1' type='Debug' layout='${message} ${event-context:foo} ${event-context:bar} ${event-context:baz}' />
                    <target name='debug2' type='Debug' layout='${message} ${event-context:foo} ${event-context:bar} ${event-context:baz}' />
                    <target name='debug3' type='Debug' layout='${message} ${event-context:foo} ${event-context:bar} ${event-context:baz}' />
                </targets>
                <rules>
                    <logger name='logger1' minlevel='Trace' writeTo='debug1' />
                    <logger name='logger2' minlevel='Trace' writeTo='debug2' />
                    <logger name='logger3' minlevel='Trace' writeTo='debug3' />
                </rules>
            </nlog>");

            var service = new LogReceiverForwardingService();
            var events  = new NLogEvents
            {
                BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
                ClientName  = "foo",
                LayoutNames = new StringCollection {
                    "foo", "bar", "baz"
                },
                Strings = new StringCollection {
                    "logger1", "logger2", "logger3", "zzz", "message1"
                },
                Events =
                    new[]
                {
                    new NLogEvent
                    {
                        Id             = 1,
                        LevelOrdinal   = 2,
                        LoggerOrdinal  = 0,
                        TimeDelta      = 30000000,
                        MessageOrdinal = 4,
                        Values         = "0|1|2"
                    },
                    new NLogEvent
                    {
                        Id             = 2,
                        LevelOrdinal   = 3,
                        LoggerOrdinal  = 2,
                        MessageOrdinal = 4,
                        TimeDelta      = 30050000,
                        Values         = "0|1|3",
                    }
                }
            };

            service.ProcessLogMessages(events);
            this.AssertDebugCounter("debug1", 1);
            this.AssertDebugCounter("debug2", 0);
            this.AssertDebugCounter("debug3", 1);
            this.AssertDebugLastMessage("debug1", "message1 logger1 logger2 logger3");
            this.AssertDebugLastMessage("debug3", "message1 logger1 logger2 zzz");
        }
 /// <summary>
 /// Processes the log messages asynchronously.
 /// </summary>
 /// <param name="events">The events to send.</param>
 /// <param name="userState">User-specific state.</param>
 public void ProcessLogMessagesAsync(NLogEvents events, object userState)
 {
     this.InvokeAsync(
         this.OnBeginProcessLogMessages,
         new object[] { events },
         this.OnEndProcessLogMessages,
         this.OnProcessLogMessagesCompleted,
         userState);
 }
            /// <summary>
            /// Processes the log messages.
            /// </summary>
            /// <param name="events">The events.</param>
            public void ProcessLogMessages(NLogEvents events)
            {
                if (CountdownEvent == null)
                {
                    throw new Exception("test not prepared well");
                }

                ReceivedEvents.Add(events);

                CountdownEvent.Signal();
            }
Beispiel #11
0
            protected internal override bool OnSend(NLogEvents events, IEnumerable <AsyncLogEventInfo> asyncContinuations)
            {
                this.LastPayload = events;

                foreach (var ac in asyncContinuations)
                {
                    ac.Continuation(null);
                }

                return(false);
            }
Beispiel #12
0
        public void ProcessLogMessages(NLogEvents nevents)
        {
            var events = nevents.ToEventInfo("Client.");

            Console.WriteLine("in: {0} {1}", nevents.Events.Length, events.Count);

            foreach (var ev in events)
            {
                var logger = LogManager.GetLogger(ev.LoggerName);
                logger.Log(ev);
            }
        }
        private static int GetStringOrdinal(NLogEvents context, Dictionary <string, int> stringTable, string value)
        {
            int stringIndex;

            if (!stringTable.TryGetValue(value, out stringIndex))
            {
                stringIndex = context.Strings.Count;
                stringTable.Add(value, stringIndex);
                context.Strings.Add(value);
            }

            return(stringIndex);
        }
        public void NoLayoutsTest()
        {
            var events = new NLogEvents
            {
                BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
                ClientName  = "foo",
                LayoutNames = new StringCollection(),
                Strings     = new StringCollection {
                    "logger1", "logger2", "logger3", "zzz", "message1"
                },
                Events =
                    new[]
                {
                    new NLogEvent
                    {
                        Id             = 1,
                        LevelOrdinal   = 2,
                        LoggerOrdinal  = 0,
                        TimeDelta      = 30000000,
                        MessageOrdinal = 4,
                        Values         = null,
                    },
                    new NLogEvent
                    {
                        Id             = 2,
                        LevelOrdinal   = 3,
                        LoggerOrdinal  = 2,
                        MessageOrdinal = 4,
                        TimeDelta      = 30050000,
                        Values         = null,
                    }
                }
            };

            var converted = events.ToEventInfo();

            Assert.Equal(2, converted.Count);
            Assert.Equal("message1", converted[0].FormattedMessage);
            Assert.Equal("message1", converted[1].FormattedMessage);

            Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime());
            Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime());

            Assert.Equal("logger1", converted[0].LoggerName);
            Assert.Equal("logger3", converted[1].LoggerName);

            Assert.Equal(LogLevel.Info, converted[0].Level);
            Assert.Equal(LogLevel.Warn, converted[1].Level);
        }
        /// <summary>
        /// Add value to the <see cref="NLogEvents.Strings"/>, returns ordinal in <see cref="NLogEvents.Strings"/>
        /// </summary>
        /// <param name="context"></param>
        /// <param name="stringTable">lookup so only unique items will be added to <see cref="NLogEvents.Strings"/></param>
        /// <param name="value">value to add</param>
        /// <returns></returns>
        private static int AddValueAndGetStringOrdinal(NLogEvents context, Dictionary <string, int> stringTable, string value)
        {
            if (value == null || !stringTable.TryGetValue(value, out var stringIndex))
            {
                stringIndex = context.Strings.Count;
                if (value != null)
                {
                    //don't add null to the string table, that would crash
                    stringTable.Add(value, stringIndex);
                }
                context.Strings.Add(value);
            }

            return(stringIndex);
        }
        internal NLogEvent TranslateEvent(LogEventInfo eventInfo, NLogEvents context, Dictionary <string, int> stringTable)
        {
            var nlogEvent = new NLogEvent();

            nlogEvent.Id             = eventInfo.SequenceID;
            nlogEvent.MessageOrdinal = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.FormattedMessage);
            nlogEvent.LevelOrdinal   = eventInfo.Level.Ordinal;
            nlogEvent.LoggerOrdinal  = AddValueAndGetStringOrdinal(context, stringTable, eventInfo.LoggerName);
            nlogEvent.TimeDelta      = eventInfo.TimeStamp.ToUniversalTime().Ticks - context.BaseTimeUtc;

            for (int i = 0; i < Parameters.Count; ++i)
            {
                var param       = Parameters[i];
                var value       = param.Layout.Render(eventInfo);
                int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value);

                nlogEvent.ValueIndexes.Add(stringIndex);
            }

            // layout names beyond Parameters.Count are per-event property names.
            for (int i = Parameters.Count; i < context.LayoutNames.Count; ++i)
            {
                string value;
                object propertyValue;

                if (eventInfo.HasProperties && eventInfo.Properties.TryGetValue(context.LayoutNames[i], out propertyValue))
                {
                    value = Convert.ToString(propertyValue, CultureInfo.InvariantCulture);
                }
                else
                {
                    value = string.Empty;
                }

                int stringIndex = AddValueAndGetStringOrdinal(context, stringTable, value);
                nlogEvent.ValueIndexes.Add(stringIndex);
            }

            if (eventInfo.Exception != null)
            {
                nlogEvent.ValueIndexes.Add(AddValueAndGetStringOrdinal(context, stringTable, eventInfo.Exception.ToString()));
            }

            return(nlogEvent);
        }
Beispiel #17
0
        public void LogEvents(NLogEvents events)
        {
            Source source = ParseAndCreateSource(events.ClientName);

            if (source == null)
            {
                Log.Error("Ignoring received events");
                return;
            }

            var batch = _batchRepository.Create(source);

            var timberMillEvents = ExtractLogEvents(events, batch);

            timberMillEvents.ForEach(_eventRepository.Save);

            Log.Info("Received {0} events from {1}", timberMillEvents.Count, source);
        }
        private NLogEvents TranslateLogEvents(IList <AsyncLogEventInfo> logEvents)
        {
            if (logEvents.Count == 0 && !LogManager.ThrowExceptions)
            {
                InternalLogger.Error("LogReceiverServiceTarget(Name={0}): LogEvents array is empty, sending empty event...", Name);
                return(new NLogEvents());
            }

            string clientID = string.Empty;

            if (ClientId != null)
            {
                clientID = ClientId.Render(logEvents[0].LogEvent);
            }

            var networkLogEvents = new NLogEvents
            {
                ClientName  = clientID,
                LayoutNames = new StringCollection(),
                Strings     = new StringCollection(),
                BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks
            };

            var stringTable = new Dictionary <string, int>();

            for (int i = 0; i < Parameters.Count; ++i)
            {
                networkLogEvents.LayoutNames.Add(Parameters[i].Name);
            }

            if (IncludeEventProperties)
            {
                AddEventProperties(logEvents, networkLogEvents);
            }

            networkLogEvents.Events = new NLogEvent[logEvents.Count];
            for (int i = 0; i < logEvents.Count; ++i)
            {
                AsyncLogEventInfo ev = logEvents[i];
                networkLogEvents.Events[i] = TranslateEvent(ev.LogEvent, networkLogEvents, stringTable);
            }

            return(networkLogEvents);
        }
        private static void AddEventProperties(IList <AsyncLogEventInfo> logEvents, NLogEvents networkLogEvents)
        {
            for (int i = 0; i < logEvents.Count; ++i)
            {
                var ev = logEvents[i].LogEvent;

                if (ev.HasProperties)
                {
                    // add all event-level property names in 'LayoutNames' collection.
                    foreach (var prop in ev.Properties)
                    {
                        if (prop.Key is string propName && !networkLogEvents.LayoutNames.Contains(propName))
                        {
                            networkLogEvents.LayoutNames.Add(propName);
                        }
                    }
                }
            }
        }
        private NLogEvent TranslateEvent(LogEventInfo eventInfo, NLogEvents context, Dictionary <string, int> stringTable)
        {
            var nlogEvent = new NLogEvent();

            nlogEvent.Id             = eventInfo.SequenceID;
            nlogEvent.MessageOrdinal = GetStringOrdinal(context, stringTable, eventInfo.FormattedMessage);
            nlogEvent.LevelOrdinal   = eventInfo.Level.Ordinal;
            nlogEvent.LoggerOrdinal  = GetStringOrdinal(context, stringTable, eventInfo.LoggerName);
            nlogEvent.TimeDelta      = eventInfo.TimeStamp.ToUniversalTime().Ticks - context.BaseTimeUtc;

            for (int i = 0; i < this.Parameters.Count; ++i)
            {
                var param       = this.Parameters[i];
                var value       = param.Layout.Render(eventInfo);
                int stringIndex = GetStringOrdinal(context, stringTable, value);

                nlogEvent.ValueIndexes.Add(stringIndex);
            }

            return(nlogEvent);
        }
Beispiel #21
0
        public void ProcessLogMessages(NLogEvents events)
        {
            DateTime baseTimeUtc = new DateTime(events.BaseTimeUtc, DateTimeKind.Utc);

            foreach (var ev in events.Events)
            {
                LogLevel level      = LogLevel.FromOrdinal(ev.LevelOrdinal);
                string   loggerName = events.LoggerNames[ev.LoggerOrdinal];

                Logger logger       = LogManager.GetLogger(loggerName);
                var    logEventInfo = new LogEventInfo();
                logEventInfo.Level      = level;
                logEventInfo.LoggerName = loggerName;
                logEventInfo.TimeStamp  = baseTimeUtc.AddTicks(ev.TimeDelta);
                logEventInfo.Properties.Add("ClientName", events.ClientName);
                for (int i = 0; i < events.LayoutNames.Count; ++i)
                {
                    logEventInfo.Properties.Add(events.LayoutNames[i], ev.Values[i]);
                }
                logger.Log(logEventInfo);
            }
        }
Beispiel #22
0
        private void Send(NLogEvents events, IList <AsyncLogEventInfo> asyncContinuations, AsyncContinuation flushContinuations)
        {
            if (!OnSend(events, asyncContinuations))
            {
                if (flushContinuations != null)
                {
                    flushContinuations(null);
                }
                return;
            }

            var client = CreateLogReceiver();

            client.ProcessLogMessagesCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    InternalLogger.Error(e.Error, "{0}: Error while sending", this);
                }

                // report error to the callers
                for (int i = 0; i < asyncContinuations.Count; ++i)
                {
                    asyncContinuations[i].Continuation(e.Error);
                }

                if (flushContinuations != null)
                {
                    flushContinuations(e.Error);
                }

                // send any buffered events
                SendBufferedEvents(null);
            };

            inCall = true;
            client.ProcessLogMessagesAsync(events);
        }
        private void Send(NLogEvents events, IList <AsyncLogEventInfo> asyncContinuations, AsyncContinuation flushContinuations)
        {
            if (!OnSend(events, asyncContinuations))
            {
                if (flushContinuations != null)
                {
                    flushContinuations(null);
                }
                return;
            }

#if WCF_SUPPORTED
            var client = CreateLogReceiver();

            client.ProcessLogMessagesCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    InternalLogger.Error(e.Error, "LogReceiverServiceTarget(Name={0}): Error while sending", Name);
                }

                // report error to the callers
                for (int i = 0; i < asyncContinuations.Count; ++i)
                {
                    asyncContinuations[i].Continuation(e.Error);
                }

                if (flushContinuations != null)
                {
                    flushContinuations(e.Error);
                }

                // send any buffered events
                SendBufferedEvents(null);
            };

            inCall = true;
#if SILVERLIGHT
            if (!Deployment.Current.Dispatcher.CheckAccess())
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events));
            }
            else
            {
                client.ProcessLogMessagesAsync(events);
            }
#else
            client.ProcessLogMessagesAsync(events);
#endif
#else
            var client = new SoapLogReceiverClient(this.EndpointAddress);
            this.inCall = true;
            client.BeginProcessLogMessages(
                events,
                result =>
            {
                Exception exception = null;

                try
                {
                    client.EndProcessLogMessages(result);
                }
                catch (Exception ex)
                {
                    InternalLogger.Error(ex, "LogReceiverServiceTarget(Name={0}): Error while sending", Name);
                    if (ex.MustBeRethrownImmediately())
                    {
                        throw;          // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
                    }

                    exception = ex;
                }

                // report error to the callers
                for (int i = 0; i < asyncContinuations.Count; ++i)
                {
                    asyncContinuations[i].Continuation(exception);
                }

                if (flushContinuations != null)
                {
                    flushContinuations(exception);
                }

                // send any buffered events
                this.SendBufferedEvents(null);
            },
                null);
#endif
        }
Beispiel #24
0
        public void ToLogEventInfoTest()
        {
            var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
            <nlog throwExceptions='true'>
                <targets>
                    <target name='debug1' type='Debug' layout='${message} ${event-context:foo} ${event-context:bar} ${event-context:baz}' />
                    <target name='debug2' type='Debug' layout='${message} ${event-context:foo} ${event-context:bar} ${event-context:baz}' />
                    <target name='debug3' type='Debug' layout='${message} ${event-context:foo} ${event-context:bar} ${event-context:baz}' />
                </targets>
                <rules>
                    <logger name='logger1' minlevel='Trace' writeTo='debug1' />
                    <logger name='logger2' minlevel='Trace' writeTo='debug2' />
                    <logger name='logger3' minlevel='Trace' writeTo='debug3' />
                </rules>
            </nlog>").LogFactory;
            var debug1     = logFactory.Configuration.FindTargetByName <NLog.Targets.DebugTarget>("debug1");
            var debug2     = logFactory.Configuration.FindTargetByName <NLog.Targets.DebugTarget>("debug2");
            var debug3     = logFactory.Configuration.FindTargetByName <NLog.Targets.DebugTarget>("debug3");

            var service = new LogReceiverForwardingService(logFactory);
            var events  = new NLogEvents
            {
                BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
                ClientName  = "foo",
                LayoutNames = new StringCollection {
                    "foo", "bar", "baz"
                },
                Strings = new StringCollection {
                    "logger1", "logger2", "logger3", "zzz", "message1"
                },
                Events =
                    new[]
                {
                    new NLogEvent
                    {
                        Id             = 1,
                        LevelOrdinal   = 2,
                        LoggerOrdinal  = 0,
                        TimeDelta      = 30000000,
                        MessageOrdinal = 4,
                        Values         = "0|1|2"
                    },
                    new NLogEvent
                    {
                        Id             = 2,
                        LevelOrdinal   = 3,
                        LoggerOrdinal  = 2,
                        MessageOrdinal = 4,
                        TimeDelta      = 30050000,
                        Values         = "0|1|3",
                    }
                }
            };

            service.ProcessLogMessages(events);

            Assert.Equal(1, debug1.Counter);
            Assert.Equal(0, debug2.Counter);
            Assert.Equal(1, debug3.Counter);
            Assert.Equal("message1 logger1 logger2 logger3", debug1.LastMessage);
            Assert.Equal("message1 logger1 logger2 zzz", debug3.LastMessage);

            logFactory.Shutdown();
        }
 /// <summary>
 /// Begins processing of log messages.
 /// </summary>
 /// <param name="events">The events to send.</param>
 /// <param name="callback">The callback.</param>
 /// <param name="asyncState">Asynchronous state.</param>
 /// <returns>
 /// IAsyncResult value which can be passed to <see cref="ILogReceiverClient.EndProcessLogMessages"/>.
 /// </returns>
 IAsyncResult ILogReceiverClient.BeginProcessLogMessages(NLogEvents events, AsyncCallback callback, object asyncState)
 {
     return(this.Channel.BeginProcessLogMessages(events, callback, asyncState));
 }
 /// <summary>
 /// Called when log events are being sent (test hook).
 /// </summary>
 /// <param name="events">The events.</param>
 /// <param name="asyncContinuations">The async continuations.</param>
 /// <returns>True if events should be sent, false to stop processing them.</returns>
 protected internal virtual bool OnSend(NLogEvents events, IEnumerable <AsyncLogEventInfo> asyncContinuations)
 {
     return(true);
 }
        public void ToLogEventInfoTest()
        {
            var events = new NLogEvents
            {
                BaseTimeUtc = new DateTime(2010, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks,
                ClientName  = "foo",
                LayoutNames = new StringCollection {
                    "foo", "bar", "baz"
                },
                Strings = new StringCollection {
                    "logger1", "logger2", "logger3", "zzz", "message1"
                },
                Events =
                    new[]
                {
                    new NLogEvent
                    {
                        Id             = 1,
                        LevelOrdinal   = 2,
                        LoggerOrdinal  = 0,
                        TimeDelta      = 30000000,
                        MessageOrdinal = 4,
                        Values         = "0|1|2"
                    },
                    new NLogEvent
                    {
                        Id             = 2,
                        LevelOrdinal   = 3,
                        LoggerOrdinal  = 2,
                        MessageOrdinal = 4,
                        TimeDelta      = 30050000,
                        Values         = "0|1|3",
                    }
                }
            };

            var converted = events.ToEventInfo();

            Assert.Equal(2, converted.Count);
            Assert.Equal("message1", converted[0].FormattedMessage);
            Assert.Equal("message1", converted[1].FormattedMessage);

            Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 0, DateTimeKind.Utc), converted[0].TimeStamp.ToUniversalTime());
            Assert.Equal(new DateTime(2010, 1, 1, 0, 0, 3, 5, DateTimeKind.Utc), converted[1].TimeStamp.ToUniversalTime());

            Assert.Equal("logger1", converted[0].LoggerName);
            Assert.Equal("logger3", converted[1].LoggerName);

            Assert.Equal(LogLevel.Info, converted[0].Level);
            Assert.Equal(LogLevel.Warn, converted[1].Level);

            Layout fooLayout = "${event-context:foo}";
            Layout barLayout = "${event-context:bar}";
            Layout bazLayout = "${event-context:baz}";

            Assert.Equal("logger1", fooLayout.Render(converted[0]));
            Assert.Equal("logger1", fooLayout.Render(converted[1]));

            Assert.Equal("logger2", barLayout.Render(converted[0]));
            Assert.Equal("logger2", barLayout.Render(converted[1]));

            Assert.Equal("logger3", bazLayout.Render(converted[0]));
            Assert.Equal("zzz", bazLayout.Render(converted[1]));
        }
Beispiel #28
0
 public void ProcessLogMessages(NLogEvents events)
 {
     throw new NotImplementedException();
 }
        private void Send(NLogEvents events, IEnumerable <AsyncLogEventInfo> asyncContinuations)
        {
            if (!this.OnSend(events, asyncContinuations))
            {
                return;
            }

#if WCF_SUPPORTED
            var client = CreateWcfLogReceiverClient();

            client.ProcessLogMessagesCompleted += (sender, e) =>
            {
                // report error to the callers
                foreach (var ev in asyncContinuations)
                {
                    ev.Continuation(e.Error);
                }

                // send any buffered events
                this.SendBufferedEvents();
            };

            this.inCall = true;
#if SILVERLIGHT
            if (!Deployment.Current.Dispatcher.CheckAccess())
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events));
            }
            else
            {
                client.ProcessLogMessagesAsync(events);
            }
#else
            client.ProcessLogMessagesAsync(events);
#endif
#else
            var client = new SoapLogReceiverClient(this.EndpointAddress);
            this.inCall = true;
            client.BeginProcessLogMessages(
                events,
                result =>
            {
                Exception exception = null;

                try
                {
                    client.EndProcessLogMessages(result);
                }
                catch (Exception ex)
                {
                    if (ex.MustBeRethrown())
                    {
                        throw;
                    }

                    exception = ex;
                }

                // report error to the callers
                foreach (var ev in asyncContinuations)
                {
                    ev.Continuation(exception);
                }

                // send any buffered events
                this.SendBufferedEvents();
            },
                null);
#endif
        }
        private void Send(NLogEvents events, IEnumerable <AsyncLogEventInfo> asyncContinuations)
        {
            if (!this.OnSend(events, asyncContinuations))
            {
                return;
            }

#if WCF_SUPPORTED
            WcfLogReceiverClient client;

            if (string.IsNullOrEmpty(this.EndpointConfigurationName))
            {
                // endpoint not specified - use BasicHttpBinding
                Binding binding;

#if !SILVERLIGHT2
                if (this.UseBinaryEncoding)
                {
                    binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
                }
                else
#endif
                {
                    binding = new BasicHttpBinding();
                }

                client = new WcfLogReceiverClient(binding, new EndpointAddress(this.EndpointAddress));
            }
            else
            {
                client = new WcfLogReceiverClient(this.EndpointConfigurationName, new EndpointAddress(this.EndpointAddress));
            }

            client.ProcessLogMessagesCompleted += (sender, e) =>
            {
                // report error to the callers
                foreach (var ev in asyncContinuations)
                {
                    ev.Continuation(e.Error);
                }

                // send any buffered events
                this.SendBufferedEvents();
            };

            this.inCall = true;
#if SILVERLIGHT
            if (!Deployment.Current.Dispatcher.CheckAccess())
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events));
            }
            else
            {
                client.ProcessLogMessagesAsync(events);
            }
#else
            client.ProcessLogMessagesAsync(events);
#endif
#else
            var client = new SoapLogReceiverClient(this.EndpointAddress);
            this.inCall = true;
            client.BeginProcessLogMessages(
                events,
                result =>
            {
                Exception exception = null;

                try
                {
                    client.EndProcessLogMessages(result);
                }
                catch (Exception ex)
                {
                    if (ex.MustBeRethrown())
                    {
                        throw;
                    }

                    exception = ex;
                }

                // report error to the callers
                foreach (var ev in asyncContinuations)
                {
                    ev.Continuation(exception);
                }

                // send any buffered events
                this.SendBufferedEvents();
            },
                null);
#endif
        }
        public void CompareSerializationFormats()
        {
            var events = new NLogEvents
            {
                BaseTimeUtc = DateTime.UtcNow.Ticks,
                ClientName  = "foo",
                LayoutNames = new StringCollection {
                    "foo", "bar", "baz"
                },
                Strings = new StringCollection {
                    "logger1", "logger2", "logger3"
                },
                Events =
                    new[]
                {
                    new NLogEvent
                    {
                        Id            = 1,
                        LevelOrdinal  = 2,
                        LoggerOrdinal = 0,
                        TimeDelta     = 34,
                        Values        = "1|2|3"
                    },
                    new NLogEvent
                    {
                        Id            = 2,
                        LevelOrdinal  = 3,
                        LoggerOrdinal = 2,
                        TimeDelta     = 345,
                        Values        = "1|2|3",
                    }
                }
            };

            var serializer1 = new XmlSerializer(typeof(NLogEvents));
            var sw1         = new StringWriter();

            using (var writer1 = XmlWriter.Create(sw1, new XmlWriterSettings {
                Indent = true
            }))
            {
                var namespaces = new XmlSerializerNamespaces();
                namespaces.Add("i", "http://www.w3.org/2001/XMLSchema-instance");

                serializer1.Serialize(writer1, events, namespaces);
            }

            var serializer2 = new DataContractSerializer(typeof(NLogEvents));
            var sw2         = new StringWriter();

            using (var writer2 = XmlWriter.Create(sw2, new XmlWriterSettings {
                Indent = true
            }))
            {
                serializer2.WriteObject(writer2, events);
            }

            var xml1 = sw1.ToString();
            var xml2 = sw2.ToString();

            Assert.Equal(xml1, xml2);
        }